7

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;
        }
Werner van den Heever
  • 745
  • 6
  • 17
  • 40

4 Answers4

8

try this

private void Form1_Load(object sender, EventArgs e)
{
    this.KeyPreview = true;
    this.KeyDown += new KeyEventHandler(Form1_KeyDown);
}

void Form1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode.ToString() == "F1")
    {
        MessageBox.Show("F1 pressed");
    }
}
7

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)
}
Community
  • 1
  • 1
Microsoft DN
  • 9,706
  • 10
  • 51
  • 71
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

terrybozzio
  • 4,424
  • 1
  • 19
  • 25
0

Use KeyDown instead of KeyPress:

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyData == Keys.F1)
    {
        // your code here
    }
}

Also set KeyPreview to true

ProgramFOX
  • 6,131
  • 11
  • 45
  • 51