.NET WinForm keyDown事件方向键不响应----C# C++/CLI

在做3D漫游时,分别运用WASD和方向键,控制视角前后左右,KeyDown事件记录漫游开始标记,但是WASD可以Debug进入,方向键却始终无法进入,很奇怪的是,进不了KeyDown,却能响应KeyUp事件

但是Ctrl+方向键和Alt+方向键却可以进入,经过一番查找。很多文章中分析可能是因为方向键默认是用来处理控件焦点移动,由控件自己处理,暂时没有权威说法,但此问题是按下述套路解决的。

Control::ProcessDialogKey这个函数可以告诉程序案件时由控件自己处理还是写的程序来处理

This method is called during message preprocessing to handle dialog characters, such as TAB, RETURN, ESC, and arrow keys.This method is called only if the IsInputKey method indicates that the control is not processing the key.The ProcessDialogKey simply sends the character to the parent's ProcessDialogKey method, or returns false if the control has no parent.The Form class overrides this method to perform actual processing of dialog keys.This method is only called when the control is hosted in a Windows Forms application or as an ActiveX control.

大概意思就是TAB, RETURN, ESC, and arrow keys这几个键是控件自己处理,但是重写以后可以自定义处理。(我只是理解他的意思,但做不到准确翻译,表达能力有限)。

解决方案就是,遇到方向键,return false,那么控件就不会自动处理,交给KeyDown响应了。

C#代码

protected override bool ProcessDialogKey(Keys keyData)
{

     if (keyData == Keys.Up || keyData == Keys.Down || keyData == Keys.Left || keyData == Keys.Right)
     {
          return false;
      }
      else
      {
           return base.ProcessDialogKey(keyData);
      }
}

C++/CLI代码

virtual  bool ProcessDialogKey( System::Windows::Forms::Keys keyData)override
{
    if (keyData == System::Windows::Forms::Keys::Up || keyData == System::Windows::Forms::Keys::Down || keyData == System::Windows::Forms::Keys::Left || keyData == System::Windows::Forms::Keys::Right)
    {
          return false;
    }
    else
    {
          return __super::ProcessDialogKey(keyData);
    }
}
原文地址:https://www.cnblogs.com/yaoguangyuan/p/5362470.html