Search code examples
formspowershelltextboxctrl

How to allow Ctrl+A to select all in a Windows Form textbox (powershell)


I'm writing a .ps1 script with a windows forms GUI. When I run it from Powershell ISE, it allows the use of Ctrl+A to 'select all' in the text box. However when running the .ps1 outside of ISE, the action of CTRL+A does nothing.

Any idea what settings I can change on the text box to allow Ctrl+A? The only threads I could find on this topic were for writing in other languages like C.

Currently what I have:

$textBox = New-Object System.Windows.Forms.TextBox
$textBox.Location = New-Object System.Drawing.Point(10,40)
$textBox.Size = New-Object System.Drawing.Size(110,20)
$textbox.Add_KeyDown({
    if ($_.KeyCode -eq "Enter") {$okButton.PerformClick()}
    })
**$textbox.acceptstab = $true
$textbox.shortcutsenabled = $True**
$form.Controls.Add($textBox)

Solution

  • I can reproduce your issue here.

    One option is to incorporate this answer - https://stackoverflow.com/a/29957334/3156906 - and call Application.EnableVisualStyles().

    Your example then becomes (with an additional bit of set-up code to make it self-contained):

    Add-Type -AssemblyName "System.Windows.Forms"
    Add-Type -AssemblyName "System.Drawing"
    
    [System.Windows.Forms.Application]::EnableVisualStyles()
    
    $form = new-object System.Windows.Forms.Form
    
    $textBox = New-Object System.Windows.Forms.TextBox
    $textBox.Location = New-Object System.Drawing.Point(10,40)
    $textBox.Size = New-Object System.Drawing.Size(110,20)
    $textbox.Add_KeyDown({
        if ($_.KeyCode -eq "Enter") {$okButton.PerformClick()}
        })
    #$textbox.acceptstab = $true
    #$textbox.ShortcutsEnabled = $true
    
    $form.Controls.Add($textBox)
    
    $form.ShowDialog()
    

    You can then use Ctrl+A in the textbox to select the text.