1.支持整数和小数两种输入方式
2.可以通过VS的属性窗口,设置InputType属性来选择是哪种输入方式
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace UserController {
public partial class IntegerInput : TextBox {
public enum InputTypeEnum {
IntegerType = 0,
DobuleType = 1
}
private InputTypeEnum inputType;
public InputTypeEnum InputType {
get { return inputType; }
set { inputType = value; }
}
public IntegerInput() {
InitializeComponent();
}
public IntegerInput(IContainer container) {
container.Add(this);
InitializeComponent();
}
protected override void OnKeyPress(KeyPressEventArgs e) {
base.OnKeyPress(e);
int kc = e.KeyChar;
if (InputTypeEnum.IntegerType == InputType) {
IntegerType(kc, e);
} else {
DobuleType(kc, e);
}
}
private void IntegerType(int kc,KeyPressEventArgs e) {
if (kc == (char)8 || (kc >= '0' && kc <= '9')) {
e.Handled = false;
} else {
e.Handled = true;
}
}
private void DobuleType(int kc, KeyPressEventArgs e) {
if (kc == (char)8 || (kc >= '0' && kc <= '9')) {
e.Handled = false;
} else if (kc == 46) {
if (this.Text.Length <= 0)
e.Handled = true; //小数点不能在第一位
else {
float f;
float oldf;
bool b1 = false, b2 = false;
b1 = float.TryParse(this.Text, out oldf);
b2 = float.TryParse(this.Text + e.KeyChar.ToString(), out f);
if (b2 == false) {
if (b1 == true)
e.Handled = true;
else
e.Handled = false;
}
}
} else {
e.Handled = true;
}
}
}
}
其中,小数输入代码借鉴网络