MDI Capture Key Strokes

ZeroEffect

Junior Contributor
Joined
Oct 24, 2004
Messages
204
Location
Detroit, MI
I was able to find this thread to help me out awhile ago.

http://www.xtremedotnettalk.com/showthread.php?t=69918&highlight=modifierkeys

Ok So I can do this with all my projects except a MDI project where I want the Main MDI container to respond to the keyboard strokes. Baically I want to use Shift & Blah & blah to make some "hidden" functions visible. Just thising the normal user doesn't need to mess with.

Is this possible? Or would I have to add the code to all the forms in the MDI container to do this.

Thanks

ZeroEffect
 
You can set the MDI form's KeyPreview property to true, then handle the KeyDown event. For example:
C#:
private void MDIForm_KeyDown(object sender, KeyEventArgs e)
{
    string s = string.Empty;
    if (e.Shift) s+= " SHIFT ";
    if (e.Control) s += " CONTROL ";
    if (e.Alt) s += " ALT ";
    s += e.KeyCode;

    Debug.WriteLine(s);
}

-ner
 
Thanks for the reply. I didn't know about the Key Preview property.


This is how I am detecting multipule key presses but it doesn't seem to work and stepping through is a bit difficult.

Visual Basic:
        If (ModifierKeys = Keys.Shift) And (ModifierKeys = Keys.R) And (ModifierKeys = Keys.C) Then
            MenuItem22.Visible = True
        End If

Thanks again for the help and example.

ZeroEffect
 
Last edited:
Key combinations

Your conditional statement will never succeed since it is impossible for a variable to take 3 values at once. If it is a combination of values, then you have to test for specific parts using bitmasking (the And operator).

The ModifierKeys member of the KeyEventArgs only represents combinations of Ctrl, Shift, and Alt. The KeyCode member specifies the keycode (eg R or C). Note that this can only ever contain one key - it is impossible to represent R and C simultaneously. This means that to check for a combination such as Shift+R+C, you would need to either query the keyboard state or use a state variable, since the combination would likely cause two events to fire - Shift+R and Shift+C.

To test for Shift+C, you might do:

Visual Basic:
If (e.Shift) And (e.KeyCode = Keys.C) Then
    'Shift+C
End If

To capture Shift+R+C, you would need to capture Shift+R and Shift+C independently and check that they have both occured before continuing. Done properly this will require use of the KeyDown and the KeyUp events. However, combinations using only one character key and any combination of Ctrl, Shift, and Alt can be captured much more easily, using the above method.

Good luck :cool:
 
Back
Top