无法捕获Windows窗体中UP / DOWN-Arrow-Keys的KeyDown事件

问题描述 投票:0回答:3

在C#Winforms中,我尝试捕获向上箭头键和向下箭头键的KeyDown事件。因此我做了以下事情:

  1. 将窗体的KeyPreview属性设置为true
  2. 覆盖表单'OnKeyDown'方法

无论如何,永远不会为上/下键调用该方法,尽管例如调用左/右箭头键。然后我试图覆盖表单'OnKeyUp'方法,仅用于测试。奇怪的是,现在也为上/下箭头调用'OnKeyUp'方法。我也试图覆盖'ProcessCmdKey',结果相同:它没有被调用上/下箭头。

我不能使用KeyUp事件的原因是我需要意识到如果按键按下一段时间,所以我需要多次调用事件,这与KeyUp不同。

关于这里可能出现什么问题的任何建议?

c# winforms keydown keyup arrow-keys
3个回答
0
投票
private bool downKey = false, rightKey = false, leftKey = false;

private void TetrisGame_KeyDown(object sender, KeyEventArgs e)
{
      Graphics g = Graphics.FromImage(canvas);
      if (e.KeyCode == Keys.Down && CurrentBlock.canMoveDown())
      {
            downKey = true;
            CurrentBlock.moveDown(g);
            if (rightKey && CurrentBlock.canMoveRight()) CurrentBlock.moveRight(g);
            else if (leftKey && CurrentBlock.canMoveLeft()) CurrentBlock.moveLeft(g);
      }
      else if (e.KeyCode== Keys.Down)
      {
            downKey = true;
            newBlock();
      }
      else if (e.KeyCode == Keys.Right && CurrentBlock.canMoveRight())
      {
            rightKey = true;
            CurrentBlock.moveRight(g);
            if (downKey && CurrentBlock.canMoveDown()) CurrentBlock.moveDown(g);
                else if (downKey) newBlock();
      }
      else if (e.KeyCode == Keys.Right)
      {
            rightKey = true;
            if (downKey && CurrentBlock.canMoveDown()) CurrentBlock.moveDown(g);
            else if (downKey) newBlock();
      }
      else if (e.KeyCode == Keys.Left && CurrentBlock.canMoveLeft())
      {
            leftKey = true;
            CurrentBlock.moveLeft(g);
            if (downKey && CurrentBlock.canMoveDown()) CurrentBlock.moveDown(g);
            else if (downKey) newBlock();
      }
      else if (e.KeyCode == Keys.Left)
      {
            leftKey = true;
            if (downKey && CurrentBlock.canMoveDown()) CurrentBlock.moveDown(g);
            else if (downKey) newBlock();
      }
      this.Refresh();
}

private void TetrisGame_KeyUp(object sender, KeyEventArgs e)
{
      if (e.KeyCode == Keys.Down)
            downKey = false;
      else if (e.KeyCode == Keys.Right)
            rightKey = false;
      else if (e.KeyCode == Keys.Left)
            leftKey = false;
}

0
投票

似乎我的项目中有一个自定义控件已经覆盖了ProcessCmdKey方法。这个覆盖吞噬了我的箭头按键。直到现在我才知道这个覆盖。


0
投票

检查Custom Control基类中有哪些事件可用。然后覆盖欲望事件或使用反射器查看自定义控件DLL的内部代码。

© www.soinside.com 2019 - 2024. All rights reserved.