Click here to Skip to main content
15,913,587 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have to track if F2 key is pressed on the form and perform some action after that ; I have written following code but nothing seems to happen

Code:
C#
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
      {

          if (e.KeyChar == (char)Keys.F2)
          {
              MessageBox.Show("F2 pressed");
              //do something
          }
      }


Please suggest possible solution.....?
Posted

You will probably need to implement a keyboard hook:
Processing Global Mouse and Keyboard Hooks in C#[^]

or attach the handler to every control on your form. I would prefer the former.

Best regards
Espen Harlinn
 
Share this answer
 
The KeyPress event is not raised by non character keys and the only way to detect keys such as F2 is by the KeyDown and Keyup events msdn[^].

You'll also need to ensure that the KeyPreview property of the form is true.

Alan.
 
Share this answer
 
v2
Comments
Mantu Singh 8-Oct-11 8:06am    
Thanks a lot ! that worked
XML
refer this link

<a href="http://www.java2s.com/Code/CSharp/GUI-Windows-Form/FormKeyPressaction.htm">http://www.java2s.com/Code/CSharp/GUI-Windows-Form/FormKeyPressaction.htm</a>[<a href="http://www.java2s.com/Code/CSharp/GUI-Windows-Form/FormKeyPressaction.htm" target="_blank" title="New Win
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900