Catch a key stroke before the actual control

This example shows how to catch a key stroke before it is forwarded to the actual control. <br/> This can be useful if you want to perform your own actions, before the actual control gets them.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// KeyDown event of some control
private void SomeControl_KeyDown(object sender, KeyEventArgs e)
{
    // 1. Event is called directly after the key stroke
 
    // If the user hits Enter, we catch the
    // event and do our own things
    if (e.KeyCode == Keys.Enter)
    {
        // Suppress key stroke, so that
        // the control don't receives it
        e.SuppressKeyPress = true;
 
        // Perform something important...
    }
}
 
// KeyPress event of some control
private void SomeControl_KeyPress(object sender, KeyPressEventArgs e)
{
    // 2. Event is called during the key stroke
}
 
// KeyUp event of some control
private void SomeControl_KeyUp(object sender, KeyEventArgs e)
{
    // 3. Event is called after the key stroke  
}
X

Url: http://www.jonasjohn.de/snippets/csharp/catch-key-stroke.htm

Language: C# | User: ShareMySnippets | Created: Oct 16, 2013