文本框转换发送键:Alt + Enter ->进入
本文关键字:Enter 进入 Alt 转换 文本 | 更新日期: 2023-09-27 18:14:47
我希望能够修改wpf文本框的行为,而不需要实现一个新的类。
我想要一个像输入/Alt+ enter行为的Excel,当用户点击"enter"时,文本框被验证(movefocus…),但是当他点击"Alt+ enter"时,文本框必须添加新行(我的文本框支持多行:AcceptsReturn为真)。
我已经尝试过(在文本框PreviewKeyDown事件):-在这个链接后面构造一个KeyEventArgs和一个textcompostioneventargs:我如何在c#中以编程方式生成按键事件?-我试过SendKeys.SendWait("{ENTER}"),但它发送了许多新行命令
有办法吗?
谢谢
private void m_MeasurementName_PreviewKeyDown(object sender, KeyEventArgs e)
{
var tb = (sender as TextBox);
if (Keyboard.Modifiers == ModifierKeys.Alt && Keyboard.IsKeyDown(Key.Enter))
{
// 1st try
var key = "'n'r";
var routedEvent = Keyboard.KeyDownEvent;
tb.RaiseEvent(new TextCompositionEventArgs(InputManager.Current.PrimaryKeyboardDevice, new TextComposition(InputManager.Current, tb, key)) { RoutedEvent = routedEvent });
// 2nd
var key = Key.Enter;
var routedEvent = TextCompositionManager.TextInputEvent;
tb.RaiseEvent(new KeyEventArgs(Keyboard.PrimaryDevice, PresentationSource.FromVisual(tb), 0, key) { RoutedEvent = routedEvent });
// 3rd
System.Windows.Forms.SendKeys.SendWait("{ENTER}");
// 4th Strangely works but not ... you know
MessageBox.Show("ALT+ENTER");
e.Handled = true;
}
else if (Keyboard.IsKeyDown(Key.Enter))
{
tb.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
e.Handled = true;
}
}
如果用户按下Alt+Enter,只需在现有的TextBox.Text
上添加新行。如果他们直接按回车键,触发文本绑定
UpdateSource
private void m_MeasurementName_PreviewKeyDown(object sender, KeyEventArgs e)
{
var tb = (sender as TextBox);
if (Keyboard.Modifiers == ModifierKeys.Alt && Keyboard.IsKeyDown(Key.Enter))
{
tb.Text += "'r'n";
tb.SelectionStart = tb.Text.Length;
e.Handled = true;
}
else if (Keyboard.IsKeyDown(Key.Enter))
{
var textBinding = BindingOperations.GetBindingExpression(
tb, TextBox.TextProperty);
if (textBinding != null)
textBinding.UpdateSource();
e.Handled = true;
}
}
要使换行生效,请确保TextBox
上的AcceptsReturn="True"