简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM