在 C# 中按下某个键时,UserControl 不会引发 KeyPress 事件
UserControl not raising a KeyPress event when a key is pressed in C#
我想创建一个仅允许用户输入正双数的文本框。为此,我创建了一个继承自 System.Windows.Forms.Textbox 的 class 并添加了一个 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();
}
}
}
问题是,当我在此自定义文本框中输入数据时,没有引发 KeyPress 事件。有人可以帮我指出问题所在吗?
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);
}
}
我想创建一个仅允许用户输入正双数的文本框。为此,我创建了一个继承自 System.Windows.Forms.Textbox 的 class 并添加了一个 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();
}
}
}
问题是,当我在此自定义文本框中输入数据时,没有引发 KeyPress 事件。有人可以帮我指出问题所在吗?
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);
}
}