文本框转换发送密钥:Alt + Enter - >输入

时间:2011-11-15 16:12:26

标签: c# wpf textbox

我希望能够修改wpf文本框的行为,而无需实现新类。

我想要一个像enter / Alt + Enter行为的Excel,当用户点击“Enter”时,文本框被验证(movefocus ...),但当他点击“ALT + Enter”时,文本框必须添加一个新的line(我的文本框支持多行:AcceptsReturn为true)。

我试过(在文本框中的PreviewKeyDown事件): - 通过以下链接提升构建KeyEventArgs和TextCompositionEventArgs:How can I programmatically generate keypress events in 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;
        }
    }

1 个答案:

答案 0 :(得分:7)

如果用户按Alt + Enter,只需在现有TextBox.Text上添加新行。如果他们只按Enter键,则在文本绑定上触发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;
    }
}

要使NewLine正常运行,请确保AcceptsReturn="True"

上的TextBox