AcceptButton Doesn't work


I try to use the AcceptButton to close the window when the Enter Key is press but it not works.


$windows2 = New-object System.Windows.Forms.Form
    $windows2.size = New-object System.Drawing.size(500,300) 
    $windows2.AcceptButton = $buttonOK2
    $windows2.PreviewKey = $true
    $windows2.text = "Test"

    $buttonOK2 = New-object System.Windows.Forms.Button
    $buttonOK2.Location = New-object System.Drawing.Size(60,55)
    $buttonOK2.size = New-object System.Drawing.Size(80,25)
    $buttonOK2.Text = "Close"


    $userID_Textbox = New-object System.Windows.Forms.TextBox
    $userID_Textbox.Location = New-object System.Drawing.Size(55,15)
    $userID_Textbox.size = New-Object System.Drawing.Size(100,20)
    $userID_Textbox.Anchor = [System.Windows.Forms.AnchorStyles]::left -bor [System.Windows.Forms.AnchorStyles]::top
    $userID_Textbox.AutoSize = $false


The Focus is automatically on the “Close” button but if I click on the textbox and press “Enter” nothing happen instead of close the window.

Someone can help me ?

Thank you.



I found a how to do it.

It missed $buttonOK2.Dialogresult = “Ok”

I want to know now if it’s possible to do it with multiples tabs.

I have 4 tabs with one button on each tab, each buttons have a different action.

It’s possible to configure AcceptButton regarding the selectedtab and assigned to a different button ?

Thank you.

didn’t get your question. Can you explain a little more ?


Thank you for your answer, I found the solution :slight_smile: