Getting Enter key to execute a button from a textbox

This forum can be browsed by the general public. Posting is limited to current SAPIEN license holders with active maintenance and does not offer a response time guarantee.
Forum rules
DO NOT POST LICENSE NUMBERS, ACTIVATION KEYS OR ANY OTHER LICENSING INFORMATION IN THIS FORUM.
Only the original author and our tech personnel can reply to a topic that is created in this forum. If you find a topic that relates to an issue you are having, please create a new topic and reference the other in your post.

Any code longer than three lines should be added as code using the 'Select Code' dropdown menu or attached as a file.
User avatar
clum09
Posts: 150
Joined: Thu Apr 24, 2008 9:11 am

Re: Getting Enter key to execute a button from a textbox

Post by clum09 »

Hi all,

I tried to use the code here on my PowerShell Studio 2012 script, but it does not do anything for some reason.

Below is my code:

$textbox1_KeyDown=[System.Windows.Forms.KeyEventHandler]{
if($_.KeyCode -eq 'Enter')
{
&$buttonOK_Click
}
}

Is there any property I need to set for the textbox1 control in order for this to work?

Thanks.

User avatar
davidc
Posts: 5913
Joined: Thu Aug 18, 2011 4:56 am

Re: Getting Enter key to execute a button from a textbox

Post by davidc »

The code works for me. The easiest way to determine if the block is triggering is to set a breakpoint or write a message. Could the problem be in the Click event? What is the expected result?

David
David
SAPIEN Technologies, Inc.

User avatar
clum09
Posts: 150
Joined: Thu Apr 24, 2008 9:11 am

Re: Getting Enter key to execute a button from a textbox

Post by clum09 »

Davidc,

I got it working now. I had to create the KeyDown event for the textbox1 control. I called the event name as enterKey. For the OK button, I had to create an event (I call it OKBtn). The enterKey event calls the OKBtn event (not execute the button) when the Enter key is press while the cursor is inside the textbox1 control. The property of the textbox1 control will have the following line added as the property after the enterKey event was created: $textbox1.add_KeyDown($enterKey).

After that I just edited the code per your instruction as follows:

$enterKey=[System.Windows.Forms.KeyEventHandler]{
#Event Argument: $_ = [System.Windows.Forms.KeyEventArgs]
#TODO: Place custom script here
if($_.KeyCode -eq 'Enter')
{
& $OKBtn
}
}

I had to add $enterKey event for all the textbox controls that I want to have the event under the OK button activated. Therefore, the OK button is never executed - only the event created under the OK button that is executed.

I don't know this is how it works, but it appears to be that way, which is opposite to what I thought it should have worked.

Thanks.