Marcin Zdunek
Marcin Zdunek

Reputation: 1011

C# WinForms: bring back focus to form after button click

my simple WinForms app consists of one Form which has 2 important methods:

private void MainWindow_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Q)
    {
        qKeyPressed = true;
    }
    keyTimer.Start();
}

private void MainWindow_KeyUp(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Q)
    {
        qKeyPressed = false;
    }
    keyTimer.Stop();
}

In form's constructor I use button1.TabStop = false; to set button1 focus to false, so my form can handle methods KeyUp and KeyDown. I want my form to be focused even after button1 click event. I tried:

button1.TabStop = false;
this.Focus();

in private void button1_Click(object sender, EventArgs e) but this doesn't seem to work and button after click looks like focused and methods KeyUp and KeyDown are disabled. How can my problem be solved? Thanks in advance

Upvotes: 0

Views: 1798

Answers (1)

Phiter
Phiter

Reputation: 14992

Run this in the button click function:

this.ActiveControl = null;

When you click the button, you set it as the active control. Removing this property will let you put focus on your form.

Upvotes: 3

Related Questions