Can I determine whether a Ctrl key press is Left Ctrl or Right Ctrl?

后端 未结 4 1831
温柔的废话
温柔的废话 2021-01-16 09:24

I want to determine whether a CTRL key is LEFT CTRL or RIGHT CTRL key when it is pressed. How can I do this?

相关标签:
4条回答
  • 2021-01-16 09:45

    Apparently not from within .NET, but it's possible from the Win32 APIs.

    • The System.Windows.Forms.Key enumeration tracks left, right, and middle mouse buttons, but only has one flag for Control keys, so no way to determine left or right for Control keys.
    • The Console.ReadKey() method suffers from the same problem.
    • You might be able to do something at the Win32 level. The WM_KEYDOWN message will track the extended keys (right Alt, right Control), so Windows is tracking this data ... it just isn't being passed on to .NET. You're on your own with regard to tapping into the Win32 API from within .NET.
    0 讨论(0)
  • 2021-01-16 09:58

    You can easily check the status of the Keyboard using System.Windows.Input.Keybaord.IsKeyDown() to determine if the Right or Left Control key is pressed:

    if (Keyboard.IsKeyDown(Key.LeftCtrl)
         {}
    else if (Keyboard.IsKeyDown(Key.RightCtrl)
         {}
    end if
    
    0 讨论(0)
  • 2021-01-16 10:05

    AFAIK you can't access this information from within .net.

    However, you can use the Win32 API GetAsyncKeyState to test if specific keys are currently down, and this can differentiate the left and right ctrl keys. (If you're writing a game this is more likely to work well for you than Keydown handlers, as GetAsyncKeyState tests whether the key is down "now" rather than whether it was pressed "at some time in the past", which gives considerably better responsiveness).

    0 讨论(0)
  • 2021-01-16 10:08

    Since you're writing a game, it might be helpful to also use DirectInput... Winforms isn't really meant for da gaimez IMO...

    Device di_device = new Device(SystemGUID.Keyboard);
    di_device.SetCooperativeMode(Nonexclusive|othercrap);
    di_device.Acquire();
    
    if(di_device.GetKeyboardState()[Keys.LControl])
    {
        blargh;
    }
    

    Code written in SO textbox, untested, something like that. Note that you must include Microsoft.DirectX.DirectInput

    Also note that i don't mean you should init a DirectInput device every time you need to get input. Create the device when you init your game, dispose of it when your program exits.

    DirectInput gives you more control... And chances are, you're going to want to use it. Of course at certain points, you will need to use Winforms instead [ie: while your program is rendering, what if the user presses a button pretty quickly? GKS won't tell you about it]

    0 讨论(0)
提交回复
热议问题