文本框转换发送键:Alt + Enter ->进入 [英] Textbox convert sent key : Alt + Enter -> Enter
问题描述
我希望能够在不需要实现新类的情况下修改 wpf 文本框的行为.
I'd like to be able to modify the behaviour of the wpf textbox without the need of implementing a new class.
我想要一个类似 enter/Alt+Enter 的 Excel 行为,当用户点击Enter"时,文本框被验证(movefocus ...),但是当他点击ALT+Enter"时,文本框必须添加一个新的行(我的文本框支持多行:AcceptsReturn 为 true).
I want an Excel like enter / Alt+Enter behavior, when the user hits "Enter" the textbox is validated (movefocus ...), but when he hits "ALT+Enter", the textbox has to add a new line (my textbox supports multiline : AcceptsReturn is true).
我尝试过(在文本框 PreviewKeyDown 事件中):- 按照此链接提出构建 KeyEventArgs 和 TextCompositionEventArgs :How我可以在 C# 中以编程方式生成按键事件吗?- 我试过 SendKeys.SendWait("{ENTER}") 但它发送了许多新的行命令
I've tried (in the textbox PreviewKeyDown event): - Raising to construct a KeyEventArgs and a TextCompositionEventArgs following this link : How can I programmatically generate keypress events in C#? - I've tried SendKeys.SendWait("{ENTER}") but it sends many new line commands
有没有办法做到这一点?
Is there a way to do this ?
谢谢
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
上添加一个新行.如果他们只是按 Enter,则在文本绑定上触发 UpdateSource
If the user presses Alt+Enter, simply add a new line onto the existing TextBox.Text
. If they hit just Enter, trigger an UpdateSource
on the Text Binding
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;
}
}
要使 NewLine 正常工作,请确保 TextBox
For the NewLine to work, make sure AcceptsReturn="True"
on your TextBox
这篇关于文本框转换发送键:Alt + Enter ->进入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!