Reputation: 19
I'm using Visual Studio C# and trying to check if the ENTER key has been pressed while in a text box
private void PasswordTextBox_TextChanged(object sender, EventArgs e)
{
if(keyenterhasbeenpressed) //I dont know what to put here
{
MessageBox.Show("You pressed the enter key");
}
}
So when someone clicks enter in that text box it will do something.
Upvotes: 0
Views: 5867
Reputation: 141
The TextChanged
event isn't really suited for checking for keypresses.
It's best used to examine the sender object which is the textbox itself.
To check for the ENTER key you can do the following:
private void PasswordTextBox_KeyDown(object sender, EventArgs e)
{
if(e.KeyCode == Keys.Enter)
{
MessageBox.Show("You pressed the enter key");
}
}
or
private void PasswordTextBox_KeyPress(object sender, EventArgs e)
{
if(e.KeyChar == 13)
{
MessageBox.Show("You pressed the enter key");
}
}
It depends on what event best suits your needs. You can always put a break point (assuming visual studio) and check what data is available to you in the eventargs and sender object
Upvotes: 1
Reputation: 890
Inorder to link the function with the key press event of the textbox add the following code in the designer.cs of the form
this.textbox1.KeyDown += new System.Windows.Forms.KeyEventHandler(this.OnKeyDownHandler);
Now define the function 'OnKeyDownHandler' in the cs file of the same form
private void OnKeyDownHandler(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
//enter key has been pressed
// add your code
}
}
Upvotes: 0