博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
WPF-TxtBox控件利用KeyDown来控制键盘输入
阅读量:4538 次
发布时间:2019-06-08

本文共 1190 字,大约阅读时间需要 3 分钟。

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;
            }
        }

 

 

 

多谢大神帮助

转载于:https://www.cnblogs.com/ChinaSum/p/3289677.html

你可能感兴趣的文章
koa2 从入门到进阶之路 (一)
查看>>
Java / Android 基于Http的多线程下载的实现
查看>>
求职历程-----我的简历
查看>>
[总结]数据结构(板子)
查看>>
网页图片加载失败,用默认图片替换
查看>>
C# 笔记
查看>>
2013年10月13日学习:SQL通过命令语句来创建表
查看>>
剑指offer : 二维数组中的查找
查看>>
第三章 python基础
查看>>
java基础题
查看>>
[转]人人店短信插件开发
查看>>
[转]c# System.IO.Ports SerialPort Class
查看>>
14. 最长公共前缀
查看>>
Redis文档
查看>>
项目重构
查看>>
(笔试题)和一半的组合数
查看>>
leetcode--Algorithm--Array_Part 1 Easy- 566 Reshape the Matrix
查看>>
AC自动机算法详解 (转载)
查看>>
python3-day5(模块)
查看>>
Linux配置JDK
查看>>