系统的EDIT怎么设置仅允许小数,仅允许十六进制数等限制?

饺子87 2008-12-28 02:49:01

我写的只允许输入数字(包括小数点)的

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

namespace SaderControl
{

///<summary>
///OnlyNumberTextBox class
///</summary>

[Designer(typeof(OnlyNumberTextBox.OnlyNumberTextBoxDesigner))]
public class OnlyNumberTextBox:System.Windows.Forms.TextBox
{
#region Static Fields

[DllImport("user32.dll")]
private static extern bool MessageBeep(uint uType);

#endregion

#region Method Overrides

protected override bool ProcessKeyEventArgs(ref Message m)
{
int keyValue = m.WParam.ToInt32();
//(keyValue>47&&keyValue<58) [0-9]
//keyVale==46 小数点
//(keyValue>34&&keyValue<41) Home,End,方向键
//keyVale==8 回格键
if (keyValue > 47 && keyValue < 58
|| keyValue == 46
|| (keyValue > 34 && keyValue < 41)
|| keyValue == 8)
{
return base.ProcessKeyPreview(ref m);
}
else
{
if (m.Msg == 256 && keyValue == 46)
{
return base.ProcessKeyPreview(ref m);
}

if (m.Msg == 258)
{
MessageBeep(0);
}
return true;
}
}

#endregion

#region internal Classes

///<summary>
///OnlyNumberTextBoxDesigner class
///</summary>

internal class OnlyNumberTextBoxDesigner : ControlDesigner
{

#region Method Overrides

protected override void PreFilterProperties(System.Collections.IDictionary properties)
{
properties.Remove("Text");
}

#endregion

}

#endregion


}
}


ChrisAK :(不支持小数)
既然都用PInvoke调用API了再做那么多没必要.
系统的EDIT本身就有只允许输入数字的功能.
你只要把ES_NUMBER给TextBox加上就可以了.


C# codeusing System;
using System.ComponentModel;
using System.Windows.Forms;
using System.Windows.Forms.Design;
using System.Runtime.InteropServices;


class NumberTextBox:TextBox
{
[DllImport("user32.dll")]
static extern int SetWindowLong(IntPtr hWnd,int nIndex, int dwNewLong);
[DllImport("user32.dll")]
static extern int GetWindowLong(IntPtr hWnd,int nIndex);

const int GWL_STYLE = (-16);
const int ES_NUMBER = 0x2000;
protected override void OnCreateControl ()
{
base.OnCreateControl ();
int style= GetWindowLong (Handle,GWL_STYLE);
SetWindowLong (Handle,GWL_STYLE,style|ES_NUMBER);
}
}
class test:Form
{
public test()
{
NumberTextBox nt = new NumberTextBox();
Controls.Add (nt);
}
static void Main ()
{
Application.EnableVisualStyles();
Application.Run (new test());
}
}


你用CSC编译这段代码试试.
在XP之后的系统还会弹出一个提示说只能输入数字.
比自己写的要好得多.
...全文
63 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
饺子87 2008-12-30
  • 打赏
  • 举报
回复
分少没人鸟...
饺子87 2008-12-29
  • 打赏
  • 举报
回复
木有人舍得回答吗?
conan19771130 2008-12-29
  • 打赏
  • 举报
回复
饺子87 2008-12-28
  • 打赏
  • 举报
回复
前辈,见到你两次了,表老发这个连接了。这个我知道了。
ChrisAK说的方法似乎更简便,就是不知道有没有对应功能。

111,118

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • AIGC Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧