Eirik van Riel Eirik van Riel - 1 month ago 15
C# Question

ConsoleKey.F6 makes the shortcut U?

I'm a brand new programmer who is making his first application also known as a webbrowser. I'm trying to setup keyboard shortcuts to do different functions but I'm struggling intensely.

I'm very unsure as to what I'm doing wrong but with the below code it'll make the keyboard shortcut U?

I have no idea what the problem could be or how to solve it. I've looked around and I haven't seen anyone with a similar problem.
This happens with any project I try to open. If I have a completely blank Windows forms application and set Form1 Keypress with the following code, then the key U will open the mbox. F6 does nothing.

Other keyboard shortcuts do not work.

I have tried both ConsoleKey.F6 and Keys.F6.

private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.F6)
{
MessageBox.Show("Test");
}
}


Anyone have any ideas?

Jim Jim
Answer
  • First make sure the KeyPreview property of the form is set to true:

enter image description here

  • Then create the event Form1_KeyDown:

enter image description here

Use the e.KeyCode to compare the key pressed:

private void Form1_KeyDown(object sender, KeyEventArgs e)   
{  
    if (e.KeyCode == Keys.U)
    {
        MessageBox.Show("You pressed the U key");
    }
}
Comments