简体   繁体   中英

How can I fire a key press event on a keyboard when a user presses enter button wpf

I have a login button in wpf login form. I want that user has two options, the first one is to have user fill the username and password and press the login button using mouse, and the second option is that a user can press the ENTER key from keyboard. How can I get this to work? The mouse click does the job, but pressing ENTER does not work.

<Button Canvas.Left="157" Canvas.Top="292" Height="24" BorderThickness="0" BorderBrush="White" Content="Login" Name="btnLogin" Width="99" Click="btnLogin_Click"  Keyboard.KeyDown="bttnLogin_Enter"  />

And My code for this is :---

    private void bttnLogin_Enter(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Enter)
        {
            try
            {
                 /// My code here
             }
           catch()
              {
              }
        }
     }

ButtonIsDefault属性设置为True

Just set IsDefault="True" on your button. This will make your button get clicked automatically when the user hits enter. No need for the KeyDown event.

Other than setting IsDefault property to true for a Button, which will set the Enter action for the whole form, you could catch Enter key pressed against a textbox as well. If you want to capture Enter multiple key pressed against multiple textboxes then check the following example

Suppose you have textbox

<StackPanel>
  <TextBlock Width="300" Height="20">
    Type some text into the TextBox and press the Enter key.
  </TextBlock>
  <TextBox Width="300" Height="30" Name="textBox1"
           KeyDown="OnKeyDownHandler"/>
  <TextBlock Width="300" Height="100" Name="textBlock1"/>
</StackPanel>

In Code behind:

private void OnKeyDownHandler(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Return)
    {
        textBlock1.Text = "You Entered: " + textBox1.Text;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM