简体   繁体   中英

How to determine whether Right Ctrl/Shift/Alt or Left is being clicked in C#?

I want to use Right or Left Control/Shift/Alt in C# but When I type

 private void Form1_KeyDown(or KeyPress)(object sender, KeyEventArgs e)
    {
        if (e.Modifiers == Keys.RControlKey) //(or e.KeyCode)
        {
            //Code
        }
    }

but it doesn't work...same with Shift and Alt

So what is the wrong here?

Not sure this solve your question or not.

 private void Form1_KeyUp(object sender, KeyEventArgs e)
 {
    switch(e.KeyCode)
    {
    case Keys.LMenu:
    //Your code for Left Alt Key
    break;
    case Keys.LControlKey:
    //Your code for Left Control Key
    break;
    case Keys.LShiftKey:
    //Your code for Left Shift Key
    break;
    case Keys.RControlKey:
    //Your code for Right Control Key
    break;
    case Keys.RMenu:
    //Your code for Right Alt Key
    break;
    case Keys.RShiftKey:
    //You code for Right Shift Key
    break;
    }
}

KeyUp Event:

https://msdn.microsoft.com/en-us/library/system.windows.forms.control.keyup(v=vs.110).aspx

Keys:

https://msdn.microsoft.com/en-US/library/system.windows.forms.keys(v=vs.110).aspx

Eg, if you press RControlKey+A, it creates several events.

private void watcher_keyDown(object sender, KeyEventArgs e)
{
    Console.WriteLine("keyDown: " + e.KeyData.ToString());
}

private void watcher_KeyPress(object sender, KeyPressEventArgs e)
{
    Console.WriteLine("keyPress: " + e.KeyChar.ToString());
}

public void watcher_KeyUp(object sender, KeyEventArgs e)
{
    Console.WriteLine("keyUp: " + e.KeyData.ToString());
}

keyDown: RControlKey
keyDown: A, Control
keyPress: 
keyUp: A, Control
keyUp: RControlKey, Control

From the 1st or the last event you can know which one (left or right) was clicked. This means you may need to cache the key code as there are 2 keyUp/keyDown events.

In the KeyEventArgs there are properties Ctrl, Alt and Shift that shows if these buttons are pressed. Or you can do check if (Keyboard.IsKeyDown(Key.P) && Keyboard.IsKeyDown(Key.LeftCtrl)) {} in your event handler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM