Search code examples
winformspowershelltextbox

Select all text in textbox when tabbing through form or clicking textbox


I have a powershell script form and I'm trying to select all the text within inputbox1 and inputbox2 when I press tab to move through the form or when I click in the textboxes. It seemed simple enough, but I haven't had any luck so far.

Do I need a certain mouse handler function for the click event?

$InputBox = New-Object System.Windows.Forms.TextBox 
$InputBox.Location = New-Object System.Drawing.Size(200,40) 
$InputBox.Size = New-Object System.Drawing.Size(150,40) 
$Form.Controls.Add($InputBox)


$InputBox2 = New-Object System.Windows.Forms.TextBox 
$InputBox2.Location = New-Object System.Drawing.Size(200,65) 
$InputBox2.Size = New-Object System.Drawing.Size(150,40)
$Form.Controls.Add($InputBox2) 

$InputBox3 = New-Object System.Windows.Forms.TextBox 
$InputBox3.Location = New-Object System.Drawing.Size(10,15) 
$InputBox3.Size = New-Object System.Drawing.Size(340,20) 
$InputBox3.text = $result
$Form.Controls.Add($InputBox3) 

$outputBox = New-Object System.Windows.Forms.TextBox 
$outputBox.Location = New-Object System.Drawing.Size(10,90) 
$outputBox.Size = New-Object System.Drawing.Size(490,400) 
$outputBox.MultiLine = $True 
$outputBox.ScrollBars = "Vertical" 
$Form.Controls.Add($outputBox) 

Solution

  • If I understand the question correctly, you want to select the content of the textbox when navigating to them, either by using (Shift) Tab of by clicking into them.

    This can be done by adding two event handler script blocks to each of the text boxes:

    The first will handle the selection of the text when using the TAB key to enter the box:

    $InputBox.Add_Gotfocus( { $this.SelectAll(); $this.Focus() })
    

    The second one does the same when clicking the mouse in a textbox:

    $InputBox.Add_Click( { $this.SelectAll(); $this.Focus() })
    

    Do this for all text boxes before you add them to the Form.

    P.S. Don't forget to dispose of the form when done using $Form.Dispose()