简体   繁体   中英

UserControl not raising a KeyPress event when a key is pressed in C#

I would like to create a textbox that allows user input only positive double numbers. To do so, I have created a class that inherits from System.Windows.Forms.Textbox and added a KeyPress event as follows:

    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();
            }

        }
    }

The problem is that when I input data in this custom TextBox a KeyPress event is not being raised. Could somebody help me showing what is wrong?

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM