How to close WPF window (dialog box) when Enter key is pressed?
Your code is working fine for me. it close dialog when I press enter. You can write e.Handled = true; line after your search functionality in tbxSearchString_PreviewKeyDown event. So it will not close dialog.
<Grid> <TextBox Name="tbxSearchString" HorizontalAlignment="Left" Width="100" Height="30" Grid.Row="0" PreviewKeyDown="tt_PreviewKeyDown"></TextBox> <StackPanel Orientation="Horizontal" Grid.Row="1" Height="45" VerticalAlignment="Bottom" HorizontalAlignment="Right" Width="190"> <Button Content="OK" Height="25" Margin="10,10,10,10" Width="75" Name="btnOK" TabIndex="1600" IsDefault="True" Click="btnOK_Click" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" /> <Button Content="Cancel" Height="25" Margin="10,10,10,10" Width="75" Name="btnCancel" TabIndex="1700" IsCancel="True" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Click="btnCancel_Click" /> </StackPanel> </Grid>
Code behind
private void btnOK_Click(object sender, RoutedEventArgs e) { DialogResult = true; } private void btnCancel_Click(object sender, RoutedEventArgs e) { this.Close(); } private void tbxSearchString_PreviewKeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Enter) { this.Search(); e.Handled = true; } }
there is no built-in way to close the dialog window in wpf. what you have to do, is to set the DialogResult for your default button. so all you need is the following:
xaml
<Button Content="OK" Height="25" Margin="10,10,10,10" Width="75" Name="btnOK" TabIndex="1600" IsDefault="True" Click="btnOK_Click" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" />
codebehind:
private void btnOK_Click(object sender, RoutedEventArgs e) { DialogResult = true; }
You shouldn't be calling Close()
or handling PreviewKeyDown
yourself.
The proper way to do this is to have Ok/Cancel buttons, and use Button.IsDefault
, Button.IsCancel
, and Window.DialogResult
. If the 'enter' press is unhandled in your textbox, the keypress will propagate to the Window
and the default button will be pressed.
MyForm.xaml:
<Button x:Name="btnOk" Content="Ok" Click="btnOk_Click" IsDefault="True"/><Button x:Name="btnCancel" Content="Cancel" Click="btnCancel_Click" IsCancel="True"/>
MyForm.xaml.cs:
private void btnOk_Click(object sender, RoutedEventArgs e){ DialogResult = true;}private void btnCancel_Click(object sender, RoutedEventArgs e){ DialogResult = false;}
Now hitting enter or escape on any textbox in the form will close the form (with the proper result)