我想创建一个文本框,允许用户仅输入正双精度数。为此,我创建了一个从System.Windows.Forms.Textbox继承的类,并添加了一个KeyPress事件,如下所示:
public partial class PositiveDoubleOnlyTB : TextBox
{
private void InitializeComponent()
{
this.SuspendLayout();
//
// PositiveDoubleOnlyTB
//
this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.PositiveDoubleOnlyTB_KeyPress);
this.ResumeLayout(false);
}
private void PositiveDoubleOnlyTB_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) &&
(e.KeyChar != '.'))
{
e.Handled = true;
SystemSounds.Beep.Play();
}
// only allow one decimal point
if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1))
{
e.Handled = true;
SystemSounds.Beep.Play();
}
}
}
问题是,当我在此自定义TextBox中输入数据时,不会引发KeyPress事件。有人可以帮我显示出什么问题吗?
答案 0 :(得分:1)
public class PositiveDoubleOnlyTB : TextBox
{
protected override void OnKeyPress(KeyPressEventArgs e)
{
if (!(char.IsDigit(e.KeyChar) || e.KeyChar == '.' && base.Text.IndexOf('.') == -1))
{
e.Handled = true;
}
base.OnKeyPress(e);
}
}