When you press Enter anywhere in a HTML form
it triggers its action
, that is equivalent of pressing the submit
button.
How to make a window that when I press Enter anywhere it will trigger an event?
Set the IsDefault
property on the button to true to enable the Enter key to activate that button's action. There is also the IsCancel
property that does the same thing for the Escape key.
Assign the PreviewKeyDown
event to the window in XAML then check the KeyEventArgs
in codebehind to determine if the user pressed the Enter key.
XAML code:
<Window
[...]
PreviewKeyDown="Window_PreviewKeyDown">
Code behind:
private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
// Whatever code you want if enter key is pressed goes here
}
}
According to this https://wpf.2000things.com/tag/isdefault/
IsDefaulted will be true if all of the following is true:
- IsDefault for the Button is set to true
- Some other control currently has focus
- The control that currently has focus does not itself handle the ENTER key
In my case I was trying to hit Enter
from TextBox
which already handles Enter Key. Turnaround was to set AcceptsReturn = false
for TextBox
. This option works if you do not need multiline textbox and Enter Key should submit entered text.
Also Text Binding should be updated while typing
<TextBox Text="{Binding Text, UpdateSourceTrigger=PropertyChanged}"
AcceptsReturn="False"/>
I found that the DatePicker
control will swallow the Enter keypress so the default button doesn't get clicked. I wrote this event handler to fix that. Use the PreviewKeyUp
to ensure that the DatePicker
performs its date formatting code before clicking the default button.
private void DatePicker_PreviewKeyUp(object sender, KeyEventArgs e) {
// event handler to click the default button when you hit enter on DatePicker
if (e.Key == Key.Enter) {
// https://www.codeproject.com/Tips/739358/WPF-Programmatically-click-the-default-button
System.Windows.Input.AccessKeyManager.ProcessKey(null, "\x000D", false);
}
}
<Button Name="btnDefault" IsDefault="true" Click="OnClickDefault">OK</Button>
You can do this by setting the button IsDefault property to True.
You can get detailed information from Microsoft's documents.
© 2022 - 2024 — McMap. All rights reserved.