2011-12-22 84 views
0

即使我的控件沒有焦點,我想要在按下ALT鍵時進行捕捉。如何在用戶按下修改鍵時捕捉?

System.Windows.Forms.Control中有類似的東西嗎?

public void OnModifierKeyPressed(KeyEventArgs e); 

或者也許處理任何WndProc消息?

在此先感謝。


編輯:

我需要(如按鈕的作用)來捕獲當用戶按下ALT鍵繪製的加速鍵下劃線在我的控制。我敢肯定,下面的消息被髮送到控制,當用戶按下Alt鍵和控制不具有焦點:

WndProcMessage as integer: 
296 
8235 
15 
133 
20 

EDIT2:


最後,我發現所涉及的信息,here

Msg: WM_UPDATEUISTATE      0x0128 
WParam: UISF_HIDEACCEL       0x2 

但是,正如科迪格雷說,這是沒有必要,你可以使用Control.ShowKeyboardCues prope RTY。

+0

你當然可以捕獲用戶時Alt鍵presset **與**另一個關鍵。單獨使用Alt不會觸發關鍵事件。但我可能完全錯誤:-) – 2011-12-22 11:43:34

+0

嘗試在這篇文章中的代碼:http://stackoverflow.com/questions/2226476/problems-detecting-alt-key-on-the-control-keyup-event – keyboardP 2011-12-22 11:47:35

+0

啊,新信息表明你試圖以錯誤的方式解決問題。我需要更新我的答案... – 2011-12-22 11:49:57

回答

4

只有帶焦點的控件纔會收到鍵盤事件。因此,在您的自定義控件沒有重寫或事件處理的方法時,您可以在您的自定義控件當前沒有焦點時檢測按鍵。

無論如何,添加到您的問題的新信息表明這是無關緊要的。如果你想要在適當的時候繪製鍵盤加速器,那麼有一個更簡單的解決方案。

Paint事件處理程序爲您的自定義控件(繪製控件的文本),您應該檢查Control.ShowKeyboardCues property的值。如果值爲true,那麼您應該使鍵盤加速器可見;否則,你應該省略繪製它們。

同樣,您還應該檢查Control.ShowFocusCues property的值。這告訴你是否圍繞控件繪製焦點矩形。
使用ControlPaint.DrawFocusRectangle method繪製所述焦點矩形。

喜歡的東西:
(我沒有在我面前一個.NET編譯器,所以代碼可能有錯誤...)

// Draw the text 
using (StringFormat sf = new StringFormat()) 
{ 
    sf.Alignment = StringAlignment.Center; 
    sf.LineAlignment = StringAlignment.Center; 
    sf.HotkeyPrefix = this.ShowKeyboardCues ? HotkeyPrefix.Show : HotKeyPrefix.Hide; 

    if (this.Enabled) 
    { 
     using (Brush br = new SolidBrush(this.ForeColor)) 
     { 
      g.DrawString(this.Text, this.Font, br, this.ClientRectangle, sf); 
     } 
    } 
    else 
    { 
     SizeF sz = g.MeasureString(this.Text, this.Font, Point.Empty, sf); 
     RectangleF rc = new RectangleF(Point.Empty, sz); 
     ControlPaint.DrawStringDisabled(g, this.Text, this.Font, this.BackColor, rc, sf); 
    } 
} 

// Draw the focus rectangle 
if (this.ShowFocusCues && this.ContainsFocus) 
{ 
    ControlPaint.DrawFocusRectangle(g, this.ClientRectangle);   
} 
+0

完美答案,謝謝! – 2011-12-22 12:22:17