Click here to Skip to main content
15,888,142 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
How Could I capture all keyboard key including key left, key right, key up event in c# .net
Posted
Updated 31-Aug-13 0:06am
v2

Once I found there were some situations where I was not able to capture keystrokes with that method. The method described in this post helped me and mey be useful in some cases: http://social.msdn.microsoft.com/Forums/vstudio/en-US/cf884a91-c135-447d-b16b-214d2d9e9972/capture-all-keyboard-input-regardless-of-what-control-has-focus[^]
 
Share this answer
 
C#
private void Form1_Load(object sender, EventArgs e)
{
    this.KeyPreview = true;
    this.PreviewKeyDown += new PreviewKeyDownEventHandler(Form1_PreviewKeyDown);
    textBox1.PreviewKeyDown += new PreviewKeyDownEventHandler(Form1_PreviewKeyDown);
}

private void Form1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
    try
    {
        MessageBox.Show(e.KeyCode.ToString() + " key pressed on " + sender.ToString());
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}
 
Share this answer
 
use keydown event of any control ..
here i am used textbox'x KeyDown event..

C#
private void textBox1_KeyDown(object sender, KeyEventArgs e)
       {
           MessageBox.Show(e.KeyData.ToString());
       }
 
Share this answer
 
Comments
chandan0285 31-Aug-13 7:18am    
It could not capture key left, key right etc.
Sadique KT 31-Aug-13 7:49am    
it will capture...plz check your .Net Framework version..and event subscribed control...
chandan0285 31-Aug-13 7:58am    
I am using framework 4.5 and passing that value to label through string. If I am doing wrong then please specify what could I do.
Sadique KT 31-Aug-13 8:03am    
plz post your code part..
BillWoodruff 9-Oct-13 20:56pm    
@Sadique KT: Chandan is correct, the KeyDown Event of WinForms Controls will not handle arrow-key Events unless a modifier key is held down, like <control>. The Label WinForms Controls does not handle Keyboard Events by design, but can be "forced" to do so by over-riding three internal methods.

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