Drake
Drake

Reputation: 111

Windows Form - Override Enter with an other key

Is there a way in Windows Form to activate the currently focused button/control with the Q key? Or override the Enter, so that pressing Q activates the currently focused control like Enter does? I want the user to be able to control the application with just the left hand on Tab and Q to cycle controls and activate them.

private void Form2_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Q)
            {
                e.Handled = true;
            }

I already have this, but what do I need after the e.Handled to activate the current focus?

Upvotes: 1

Views: 65

Answers (1)

Reza Aghaei
Reza Aghaei

Reputation: 125197

As an option you can override ProcessCmdKey and check if the key is Q then send Enter using SendKeys.Send and return true to indicate you that you processed the key:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    if (keyData == Keys.Q)
    {
        SendKeys.Send("{Enter}");
        return true;
    }
    return base.ProcessCmdKey(ref msg, keyData);
}

You can limit the behavior to buttons by checking this.ActiveControl is Button if you need.

Upvotes: 2

Related Questions