private void Form1_Load(object sender, EventArgs e)
{
this.txtBox.GotFocus += new EventHandler(txtBox_GotFocus);
}
//給只許輸入數字的輸入框複製/粘貼時使用
private struct StruPastText
{
public string _text;
public int _selStart;
public int _selLength;
public StruPastText(string txt, int Start, int Length)
{
_text = txt;
_selStart = Start;
_selLength = Length;
}
}
private StruPastText _pastText = new StruPastText();
private void txtBox_GotFocus(object sender, EventArgs e)
{
this.NotePastText(this.txtBox, ref _pastText);
}
private void txtBox_KeyPress(object sender, KeyPressEventArgs e)
{
this.CheckKeyIn(e, false);
}
private void txtBox_TextChanged(object sender, EventArgs e)
{
if (this.IsNumeric(this.txtBox.Text.ToString().Trim(), true, false))
{
this.NotePastText(this.txtBox, ref _pastText);
}
else
{
this.RestoreText(this.txtBox, _pastText);
}
}
private void CheckKeyIn(KeyPressEventArgs Key, bool AllowDot)
{
if (Char.IsControl(Key.KeyChar)) return;//注:回退键也属于控制键之一.
if (Char.IsDigit(Key.KeyChar)) return;
if (Key.KeyChar == '.')
{
if (!AllowDot) Key.KeyChar = (char)0;
return;
}
Key.KeyChar = (char)0;
}
private bool IsNumeric(string NumStr, bool MayEmpty, bool ContainDot)
{
//检查空值
if (NumStr + "" == "")
{
if (MayEmpty)
{
return true;
}
else
{
return false;
}
}
//检查小数点
if (ContainDot)
{
int DotPos = NumStr.IndexOf('.');
if (DotPos >= 0)
{
DotPos = NumStr.IndexOf('.', DotPos + 1);
if (DotPos >= 0) return false;
}
}
else
{
if (NumStr.IndexOf('.') >= 0) return false;
}
//检查各位数字
char[] ChrArr = NumStr.ToCharArray();
for (int i = 0; i <= ChrArr.GetUpperBound(0); i++)
{
if (!Char.IsDigit(ChrArr[i]))
{
if (ChrArr[i] != '.') return false;
if (!ContainDot) return false;
}
}
if (ContainDot)
{
if (NumStr.Replace('.', (char)0).Length <= 0) return false;//判断是否只含有".",如果只含有".",而无数字,返回错误.
}
//检查正确
return true;
}
/// <summary>
/// 因为用TextBox控件的Undo()方法有时效果不好,或者不灵,故用NotePastText方法和RestoreText方法来实现"取消"的效果.
/// </summary>
/// <param name="txtRestoreTo"></param>
/// <param name="TextFrom"></param>
private void RestoreText(TextBox txtRestoreTo, StruPastText TextFrom)
{
txtRestoreTo.Text = TextFrom._text;
txtRestoreTo.SelectionStart = TextFrom._selStart;
txtRestoreTo.SelectionLength = TextFrom._selLength;
}
/// <summary>
/// 因为用TextBox控件的Undo()方法有时效果不好,或者不灵,故用NotePastText方法和RestoreText方法来实现"取消"的效果.
/// </summary>
/// <param name="txtFrom"></param>
/// <param name="NoteTo"></param>
private void NotePastText(TextBox txtFrom, ref StruPastText NoteTo)
{
NoteTo._text = txtFrom.Text;
NoteTo._selStart = txtFrom.SelectionStart;
NoteTo._selLength = txtFrom.SelectionLength;
}