开发者

How to inherit from textbox and override keypress and keyup events?

开发者 https://www.devze.com 2023-04-11 03:01 出处:网络
I want to create a new class inherits from System.Windows.Forms.TextBox and assign keypress and keyup events to my control.

I want to create a new class inherits from System.Windows.Forms.TextBox and assign keypress and keyup events to my control.

Something like this :

    class CurrencyTextbox : TextBox
    {
        private void CurrencyTextbox_KeyPress(object sender, KeyPressEventArgs e)
        {
            char ch = e.KeyChar;

            if (!Char.IsDigit(ch) && ch != 8 && ch != 13)
            {
                e.Handled = true;
            }
        }

        private void CurrencyTextbox_KeyUp(object sender, KeyEventArgs e)
        {
            if (!string.IsNullOrEmpty(CurrencyTextbox.Text))
            {
                System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("en-US");
                Int64 valueBefore = Int64.Parse(开发者_Python百科CurrencyTextbox.Text, System.Globalization.NumberStyles.AllowThousands);
                CurrencyTextbox.Text = String.Format(culture, "{0:N0}", valueBefore);
                CurrencyTextbox.Select(CurrencyTextbox.Text.Length, 0);
            }
        }
    }


You should override the protected virtual void OnKeyUp(KeyEventArgs e).
Make sure to call base.OnKeyUp(e), or the event will not be raised.

You can also add a regular event handler by writing KeyUp += CurrencyTextbox_KeyUp

0

精彩评论

暂无评论...
验证码 换一张
取 消