WPF-TxtBox控件利用KeyDown来控制键盘输入

时间:2022-07-07 09:04:45

private void TextBox_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            TextBox txt = sender as TextBox;
            if (txt.Text.Length <= 10) //控制字符长度
            {
                //屏蔽非法按键
                if ((e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) || e.Key == Key.Decimal || e.Key.ToString() == "Tab")
                {
                    if (txt.Text.Contains(".") && e.Key == Key.Decimal)
                    {
                        e.Handled = true;
                        return;
                    }
                    e.Handled = false;
                }
                else if (((e.Key >= Key.D0 && e.Key <= Key.D9) || e.Key == Key.OemPeriod || e.Key == Key.Back || e.Key == Key.Delete) && e.KeyboardDevice.Modifiers != ModifierKeys.Shift)
                {
                    if (txt.Text.Contains(".") && e.Key == Key.OemPeriod)
                    {
                        e.Handled = true;
                        return;
                    }
                    e.Handled = false;
                }
                else if (e.Key == Key.Enter)
                {
                    TraversalRequest request = new TraversalRequest(FocusNavigationDirection.Next);// MoveFocus takes a TraveralReqest as its argument.
                    UIElement elementWithFocus = Keyboard.FocusedElement as UIElement;// Gets the element with keyboard focus.
                    if (elementWithFocus != null)
                    {
                        elementWithFocus.MoveFocus(request);// Change keyboard focus.
                    }
                    e.Handled = true;
                }
                else
                {
                    e.Handled = true;
                }
            }
            else if (e.Key == Key.Back)
            {
                e.Handled = false;
            }
            else
            {
                e.Handled = true;
            }
        }

多谢大神帮助