Search code examples
c#keypresskeyup

c# - KeyUp only on one form


I have a poblem. After press Enter I opening new form (form2), where I can add something to db. On Form2 is button Ok. If I this button active by press Enter, I closing form2.

Problem is that by this action I another time calling KeyUp on form1, and Im in loop..

here is example:

private void Form1_Load(object sender, EventArgs e)
        {
            this.KeyPreview = true;
            this.KeyUp += new System.Windows.Forms.KeyEventHandler(KeyEvent);
        }        
private void KeyEvent(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                dataGridViewSkladovePolozky.Focus();
                pridatDoKosiku();
            }
        }
private void buttonPridatDoKosiku_Click(object sender, EventArgs e)
        {
            pridatDoKosiku();
        }
private void pridatDoKosiku()
        {
            PridatDoKosiku pridatDoKosiku = new PridatDoKosiku(); 
            pridatDoKosiku.ShowDialog();
            refreshNakupniKosik(true);
            pridatDoKosiku.Dispose();
        }

Solution

  • Since you have already marked KeyPreview in your form, It will capture all key events. You can set a flag & manage like this.

    bool InFocus = false;
        private void Form1_Load(object sender, EventArgs e)
                {
                    this.KeyPreview = true;
                    this.KeyUp += new System.Windows.Forms.KeyEventHandler(KeyEvent);
                }        
        private void KeyEvent(object sender, KeyEventArgs e)
                {
               if(InFocus ) return;
                    if (e.KeyCode == Keys.Enter)
                    {
                        dataGridViewSkladovePolozky.Focus();
                        pridatDoKosiku();
                    }
                }
        private void buttonPridatDoKosiku_Click(object sender, EventArgs e)
                {
                    pridatDoKosiku();
                }
        private void pridatDoKosiku()
                {
                    PridatDoKosiku pridatDoKosiku = new PridatDoKosiku(); 
    InFocus = true;
                    pridatDoKosiku.ShowDialog();
                    refreshNakupniKosik(true);
                    pridatDoKosiku.Dispose();
    InFocus = false;
                }