Tell me what you need to add to this code so that the action takes place by pressing the Enter key?

private void textBox1_KeyDown(object sender, KeyEventArgs e) { } 

    2 answers 2

     if (e.KeyCode == Keys.Enter) 

      In WPF, the TextBox element by default handles pressing the ENTER key as a transition to the next WPF control (similar to pressing TAB in an open application window).

      The AcceptsReturn = "True" property of the TextBox element allows you to get the opportunity to handle the press event ENTER with the KeyUp Event. This property also allows you to create new lines in the TextBox element. New lines are not a problem, in those cases when you need it. If your sole purpose is to handle the ENTER key event in the TextBox element, this property is not convenient .

      My solution to this problem is to use a bubble strategy. The solution is simple and short. To do this, you must attach the KeyUp event handler to the parent element (any) of the TextBox object :

      XAML:

       <Window x:Class="TextBox_EnterButtomEvent.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:TextBox_EnterButtomEvent" mc:Ignorable="d" Title="MainWindow" Height="350" Width="525"> <Grid KeyUp="Grid_KeyUp"> <Grid.RowDefinitions> <RowDefinition/> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> <RowDefinition Height ="0.3*"/> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> <RowDefinition/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition/> <ColumnDefinition/> <ColumnDefinition/> </Grid.ColumnDefinitions> <TextBlock Grid.Row="1" Grid.Column="1" Padding="0" TextWrapping="WrapWithOverflow"> Input text end press ENTER: </TextBlock> <TextBox Grid.Row="2" Grid.Column="1" HorizontalAlignment="Stretch"/> <TextBlock Grid.Row="4" Grid.Column="1" Padding="0" TextWrapping="WrapWithOverflow"> You have entered: </TextBlock> <TextBlock Name="txtBlock" Grid.Row="5" Grid.Column="1" HorizontalAlignment="Stretch"/> </Grid></Window> 

      The logical part in C # (note the event handler for pressing the ENTER key is attached to the Grid element:

        public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Grid_KeyUp(object sender, KeyEventArgs e) { if(e.Key == Key.Enter) { TextBox txtBox = e.Source as TextBox; if(txtBox != null) { this.txtBlock.Text = txtBox.Text; this.txtBlock.Background = new SolidColorBrush(Colors.LightGray); } } } } 

      RESULT:

      enter image description here