How can I prevent a keydown event of a form in C # from firing more than once?

According to the official documentation, the KeyDown event in the Windows Forms control occurs only once, but it is easy to demonstrate that the event fires continuously as the key is held down:

    private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
        label1.Text = string.Format("{0}", globalCounter++);
    }

How can you use an event to fire only once?

+3
source share
5 answers

I'm generally a VB guy, but it seems to work for me as a demo code, using the form as an input source:

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        private bool _keyHeld;
        public Form1()
        {
            InitializeComponent();
            this.KeyUp += new KeyEventHandler(Form1_KeyUp);
            this.KeyDown += new KeyEventHandler(Form1_KeyDown);
            this._keyHeld = false;
        }

        void Form1_KeyUp(object sender, KeyEventArgs e)
        {
            this._keyHeld = false;
        }

        void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            if (!this._keyHeld)
            {
                this._keyHeld = true;
                if (this.BackColor == Control.DefaultBackColor)
                {
                    this.BackColor = Color.Red;
                }
                else
                {
                    this.BackColor = Control.DefaultBackColor;
                }
            }
            else
            {
                e.Handled = true;
            }
        }
    }   
}

, , , , , , .

TextBox VB, . , #, .

, , .

+2

KeyDown keyrepeat Windows, , - KeyUp , , .

+2

KeyUp.

+2
source

You can override the ProcessCmdKey method.

0
source

you can use the counter!

0
source

Source: https://habr.com/ru/post/1707235/


All Articles