Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle Ctrl + Enter with TextBox when AcceptsReturn is true?

In my UWP application, I want my TextBox to be able to go to new line by pressing down the Enter key but I also need to trigger an action when Ctrl+Enter are pressed.

The issue is, I can't seem to find a way to prevent the text to go to the next line when I press down Ctrl+Enter. Here is the code I have tried.

XAML

<TextBox x:Name="TextBox1" AcceptsReturn="True" />

In the constructor

TextBox1.AddHandler(KeyDownEvent, new KeyEventHandler(TextBox1_KeyDown), true);

Handler

private void TextBox1_KeyDown(object sender, KeyRoutedEventArgs e)
{
    var ctrl = Window.Current.CoreWindow.GetKeyState(VirtualKey.Control);
    if (ctrl.HasFlag(CoreVirtualKeyStates.Down) && e.Key == VirtualKey.Enter)
    {
        e.Handled = true;
    }
}
like image 345
Jessica Avatar asked Oct 31 '25 20:10

Jessica


1 Answers

You could create a custom class that inherits from TextBox and override its OnKeyDown method where you have full control of firing the base.OnKeyDown method to prevent from adding a new line.

class CTRLEnterTextBox : TextBox
{
    protected override void OnKeyDown(KeyRoutedEventArgs e)
    {
        if (Window.Current.CoreWindow.GetKeyState(VirtualKey.Control).HasFlag(CoreVirtualKeyStates.Down) && e.Key == VirtualKey.Enter)
        {
            e.Handled = true;
        }
        else
        {
            base.OnKeyDown(e);
        }
    }
}
like image 132
Marian Dolinský Avatar answered Nov 02 '25 09:11

Marian Dolinský