KeyPress F1 does not work C#

23,535

Solution 1

Refer This

You can override the ProcessCmdKey method of your form class and use keyData == Keys.F1 to check whether F1 is pressed. Above link has example as follows.

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    if (keyData == Keys.F1)
    {
        MessageBox.Show("You pressed the F1 key");
        return true;    // indicate that you handled this keystroke
    }

    // Call the base class
    return base.ProcessCmdKey(ref msg, keyData)
}

Solution 2

Some keys(like f1,f2,arrow keys ,tab ....)cannot be "captured" by keychar for that you need to use keycode:

if (e.KeyCode == Keys.F1)
{
  // do stuff
}

keychar property - http://msdn.microsoft.com/en-us/library/system.windows.forms.keypresseventargs.keychar.aspx

Share:
23,535
Werner van den Heever
Author by

Werner van den Heever

Updated on July 31, 2020

Comments

  • Werner van den Heever
    Werner van den Heever almost 4 years

    I'm designing a device app. Compact Framework 2.0

    I want the user to press F1 to navigate to the next screen, but it does not work.

    Can't seem to find a solution.

    Is it possible?

    This is how I normally use Keypress:

    This works:

            if (e.KeyChar == (char)Keys.M)
            {
                MessageBox.Show("M pressed");
                e.Handled = true;
            }
    

    This dos NOT work:

            if (e.KeyChar == (char)Keys.F1)
            {
                MessageBox.Show("F1 pressed");
                e.Handled = true;
            }