[英]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. 在我的UWP应用程序中,我希望我的
TextBox
能够通过按下Enter键转到新行,但我还需要在按下Ctrl + Enter时触发操作。
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 . 问题是,当我按下Ctrl + Enter时,我似乎找不到阻止文本转到下一行的方法 。 Here is the code I have tried.
这是我试过的代码。
XAML 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. 您可以创建一个继承自
TextBox
的自定义类,并覆盖其OnKeyDown
方法,您可以完全控制触发base.OnKeyDown
方法以防止添加新行。
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);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.