Home > Net >  PerformClick KeyDown doesn't work c# but works fine in vb net
PerformClick KeyDown doesn't work c# but works fine in vb net

Time:05-26

I'm trying to convert VB.NET code to C#, from all the code I found this PerformClick issue and I don't know what happened.

My VB.Net code:

Private Sub FormLogin_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
    Select Case e.KeyCode
        Case Keys.Enter
            FlBtnLogin.PerformClick()
    End Select
End Sub

The code worked, but when I tried to convert it to C#, it didn't work.

My C# code

private void FormLogin_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        FlBtnLogin.PerformClick();
    }
}

Event Handler

this.KeyDown  = new System.Windows.Forms.KeyEventHandler(this.FormLogin_KeyDown);

Any help and instruction would be appreciated, thanks

CodePudding user response:

You would need to set the KeyPreview property of the form to true. If it is false, which it is by default, then the form will not raise keyboard events when a child control that can raise keyboard events has focus. Set it to true and the form will raise the events before the child control does. This is true in both C# and VB, so it's nothing specifically to do with the code you are converting.

CodePudding user response:

As per @John which is the best option, this is another option if you want to have your events in a specific Control when the KeyPreview is OFF.

This code will only work if the form is on focus, but won't work if you put the focus/cursor on other controls.

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        MessageBox.Show("Enter!");
    }
}

While this event will be called when the focus is on a TextBox.

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        MessageBox.Show("Enter!");
    }
}

So you must add the event on the control where you will likely press the Enter Key which is the TextBox for password.

  • Related