实现只能输入数字的TextBox

来源:互联网 发布:mac jenkins安装路径 编辑:程序博客网 时间:2024/05/18 11:48

在进行WinForm编程的过程中经常会遇到需要TextBox只能输入数字的情况.

在网上搜一下要么就是重写TextBox的WndProc,要么就是自己处理KeyPress事件.

 

真有这么麻烦么?当然不:)

 

WinForm里的TextBox类实质上是对Windows公用控件里的EDIT类的封装.只允许

输入数字这种便利的功能M$当然早给我们做好了.只是在TextBox里没实现而已.

既然这样我就自己打开这个功能就是了:

 

using System; 
using System.ComponentModel; 
using System.Windows.Forms; 
using System.Windows.Forms.Design; 
using System.Runtime.InteropServices; 


class NumberTextBox:TextBox  

    const int ES_NUMBER = 0x2000; 
    protected override CreateParams CreateParams
    {
        get{
            CreateParams ret = base.CreateParams;
            ret.Style |= ES_NUMBER;
            return ret;
        }
    }

class test:Form 

    public test() 
    { 
        Text = "Number Only TextBox"
        NumberTextBox nt = new NumberTextBox(); 
        Controls.Add (nt); 
    } 
    static void Main () 
    { 
        Application.EnableVisualStyles(); 
        Application.Run (new test()); 
    } 
}

 

使用csc 编译后运行这段程序.会出现一个只有一个文本框的Form

试试输入非数字的字符.Windows抱怨了吧?如果是WinXP及其以后的系统,还会弹出一个提示:


对比下NumberTextBox类的代码量,再想想自己处理键盘事件.

是不是要方便得多呢:P.


转自:http://blog.csdn.net/ChrisAK/article/details/3623467

原创粉丝点击