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;
}
}
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);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With