Having a keyboard key that has multiple purposes

2019-09-20 14:45发布

问题:

I want to make a key combination with Keys SHIFT + D hence when both keys are pressed, purpose X starts. But my Key D is also being used to start purpose Y. How do I make sure when I'm pressing the key SHIFT + D, purpose X and only Purpose X is started and not Purpose Y.

FYI --- Shift will be pressed before D.

I tried solving this problem myself, here is my code...

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
   if (e.KeyCode == moveRight && isJumping != true && isHovering != true)
    {
        if (Shft_KeyPressed == true)// This block was suppose to fix my problem
        {
            canFly = true; // method for Purpose X will then start if this is true

        } else
        {
            facingDirection = 1;
            standTimer.Stop();
            Walking_Animator(); // This is Purpose Y        
        }            

    } else if (e.Shift)
    {
        Shft_KeyPressed = true;
        Flying_Animator(); // this is Purpose X
    } 
}

回答1:

To check if D is pressed or Shift + D is pressed you can rely on KeyData property of event argument.

KeyData
A Keys representing the key code for the key that was pressed, combined with modifier flags that indicate which combination of CTRL, SHIFT, and ALT keys was pressed at the same time.

if (e.KeyData == Keys.D)
{
    // Just D is pressed
}
if (e.KeyData == (Keys.D | Keys.Shift))
{
    // Exactly Shift + D is pressed
}

Note 1: You can also use Shift property to check if Shift key is pressed. But keep in mind if Shift is true, it doesn't mean Shift is the only pressed modifiers key. But above criteria which I checked guarantees that the pressed combination is Shift + D.

Note 2: If you are using KeyDown event, to receive the keys even when other controls of the form contain focus, you should set KeyPreview to true. Also as another option you can override ProcessCmdKey without setting KeyPreview. You have access to key data combination in ProcessCmdKey as well.