2008-08-07 180 views
19

我是C#的新手,正在做一些现有应用程序的工作。我有一个DirectX视口,里面有组件,我希望能够使用箭头键进行定位。C#和箭头键

当前我重写ProcessCmdKey并捕获箭头输入并发送OnKeyPress事件。这工作,但我希望能够用改性剂(ALT + CTRL + SHIFT )。只要我持有修饰符并按下箭头,就不会触发我正在听的事件。

有没有人有任何想法或建议,我应该去哪里呢?

回答

10

在您重写的ProcessCmdKey中,您如何确定哪个键被按下?

keyData(第二个参数)的值将根据所按键和任何修饰键改变,例如,按下左箭头将返回代码37,向左移动将返回65573,向左移动CTRL-131109和alt-左262181.

您可以提取的改性剂和通过取与适当的枚举值按该键:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData) 
{ 
    bool shiftPressed = (keyData & Keys.Shift) != 0; 
    Keys unmodifiedKey = (keyData & Keys.KeyCode); 

    // rest of code goes here 
} 
6

我upvoted Tokabi's answer,但对于比较键上有StackOverflow.com here一些其他建议。以下是我用来帮助简化一切的一些功能。

public Keys UnmodifiedKey(Keys key) 
    { 
     return key & Keys.KeyCode; 
    } 

    public bool KeyPressed(Keys key, Keys test) 
    { 
     return UnmodifiedKey(key) == test; 
    } 

    public bool ModifierKeyPressed(Keys key, Keys test) 
    { 
     return (key & test) == test; 
    } 

    public bool ControlPressed(Keys key) 
    { 
     return ModifierKeyPressed(key, Keys.Control); 
    } 

    public bool AltPressed(Keys key) 
    { 
     return ModifierKeyPressed(key, Keys.Alt); 
    } 

    public bool ShiftPressed(Keys key) 
    { 
     return ModifierKeyPressed(key, Keys.Shift); 
    } 

    protected override bool ProcessCmdKey(ref Message msg, Keys keyData) 
    { 
     if (KeyPressed(keyData, Keys.Left) && AltPressed(keyData)) 
     { 
      int n = code.Text.IndexOfPrev('<', code.SelectionStart); 
      if (n < 0) return false; 
      if (ShiftPressed(keyData)) 
      { 
       code.ExpandSelectionLeftTo(n); 
      } 
      else 
      { 
       code.SelectionStart = n; 
       code.SelectionLength = 0; 
      } 
      return true; 
     } 
     else if (KeyPressed(keyData, Keys.Right) && AltPressed(keyData)) 
     { 
      if (ShiftPressed(keyData)) 
      { 
       int n = code.Text.IndexOf('>', code.SelectionEnd() + 1); 
       if (n < 0) return false; 
       code.ExpandSelectionRightTo(n + 1); 
      } 
      else 
      { 
       int n = code.Text.IndexOf('<', code.SelectionStart + 1); 
       if (n < 0) return false; 
       code.SelectionStart = n; 
       code.SelectionLength = 0; 
      } 
      return true; 
     } 
     return base.ProcessCmdKey(ref msg, keyData); 
    }