111,118
社区成员
发帖
与我相关
我的任务
分享
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
}
}
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());
}
}