2008-08-07 136 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); 
    }