Having a keyboard key that has multiple purposes

夙愿已清 提交于 2019-12-13 09:14:33

问题


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.



来源:https://stackoverflow.com/questions/44337300/having-a-keyboard-key-that-has-multiple-purposes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!