Looking for a user to press a key or not?

I want to see what the user pressed a keyboard key. I tried the code:

    [DllImport("User32.dll")]
    private static extern short GetAsyncKeyState(System.Windows.Forms.Keys vKey);
    [DllImport("User32.dll")]
    private static extern short GetAsyncKeyState(System.Int32 vKey);
    .....
     if ((GetAsyncKeyState(Keys.F10) == -32767))
       {....}

      

What it does is that it just checks for the F10 key press. He doesn't care if it's Shift + F10 or Ctrl + F10 or F10. But I wanted to see them separately, say if it is Shift + F10, then tell me that the user pressed Shift + F10, if it is F10, then tell me that the user pressed F10. How can I get there an easy way?

+1


source to share


3 answers


Can you check as below?



//in pseudocode
if (f10pressed) {
    if (shiftpressed) {
        //Shift+F10
    } else if (ctrlpressed) {
        //Ctrl+F10
    } else {
        //F10
    }
}

      

0


source


There is no easy way; GetAsyncKeyState () will return you the exact key you supplied, ignoring the concept of modifier keys. Processing WM_CHAR handles some modifiers that you want, but for all of them (shift, alt, ctrl) you must explicitly check out the other keys.



0


source


You need to check GetAsyncKeyState

for each key you are interested in. In this case, you check F10 and then check shift, ctrl, alt and others. See virtual key codes for possible values ​​and see GetAsyncKeyState .

short key = GetAsyncKeyState(Keys.F10);
// Check the most significant bit to see if the key is down
if ( ( key & 0x8000 ) > 0 )
{
     // Check  shift is down 0x10 is value for VK_SHIFT
     key = GetAsyncKeyState( 0x10 );
     if ( key & 0x8000 ) > 0 )
     {
         // Shift key is down as well
     }
     // Repeat for other key states.
}

      

Looking at C # enum there are a number of possible offset values, you may need to experiment a little.

0


source







All Articles