Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set keyboard focus to a TextBox in Powershell

Tags:

powershell

I'm looking to find out how to automatically set the keyboard focus to a text box in powershell.

I have a script that asks the user to select an option from a dropdown menu, then based on that selection, they have to input certain parameters. That all works fine.

For ease of use, I'd like the focus of the keyboard to shift to the input box each time a new one is shown, so the user doesn't have to keep clicking on it to enter some text.

My code so far :

function inputBox($parameter)
{
$objForm = New-Object System.Windows.Forms.Form 
$objForm.Text = $parameter
$objForm.Size = New-Object System.Drawing.Size(300,200) 
$objForm.StartPosition = "CenterScreen"

$objForm.KeyPreview = $True
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Enter") 
    {$paramValue=$objTextBox.Text;$objForm.Close()}})
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Escape") 
    {$objForm.Close()}})



$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Size(75,90)
$OKButton.Size = New-Object System.Drawing.Size(75,25)
$OKButton.Text = "OK"
$OKButton.Add_Click({$paramValue=$objTextBox.Text;$objForm.Close()})
$objForm.Controls.Add($OKButton)

$objLabel = New-Object System.Windows.Forms.Label
$objLabel.Location = New-Object System.Drawing.Size(10,20) 
$objLabel.Size = New-Object System.Drawing.Size(280,20) 
$objLabel.Text = $parameter
$objForm.Controls.Add($objLabel) 

$objTextBox = New-Object System.Windows.Forms.TextBox 
$objTextBox.Location = New-Object System.Drawing.Size(10,40) 
$objTextBox.Size = New-Object System.Drawing.Size(260,20) 
$objForm.KeyPreview = $True
$objForm.Controls.Add($objTextBox) 

$objForm.Topmost = $True

$objForm.Add_Shown({$objForm.Activate()})
[void] $objForm.ShowDialog()

return $paramValue

Any ideas?

Thanks!

like image 511
YYZ Avatar asked Jan 17 '23 02:01

YYZ


2 Answers

Following your code, where I can find a dropdown menu, to give focus to textbox when form is shown I've done:

$objForm.Add_Shown({$objForm.Activate(); $objTextBox.focus()})
like image 118
CB. Avatar answered Jan 22 '23 04:01

CB.


Try the Select method in case Focus() doesn't work:

if($textbox.CanFocus)
{
   $textbox.Focus()
}
else
{
   $textbox.Select()
}
like image 42
Shay Levy Avatar answered Jan 22 '23 02:01

Shay Levy