Search code examples
c#eventstextboxkeypress

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?


Solution

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