2014-01-13 24 views
2

我想檢查C#Windows窗體應用程序中插入鍵的狀態。下面是最少的代碼(不工作;形式有兩個單選按鈕):確定Windows窗體應用程序中的插入模式

using System; 
using System.Windows.Forms; 

using System.Windows.Input; 
// Also added PresentationCore and WindowsBase refereneces 

namespace InsertModeDemo1 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void Form1_Load(object sender, EventArgs e) 
     { 
      if (Keyboard.IsKeyToggled(Key.Insert)) 
       radioButtonInsert.Checked = true; 
      else 
       radioButtonOverstrike.Checked = true; 
     } 
    } 
} 
+0

爲什麼在winforms中包含wpf相關的程序集? –

+0

這些程序集中的鍵盤和鍵名稱空間 –

回答

5

嘗試用Control.IsKeyLocked代替。

private void Form1_Load(object sender, EventArgs e) 
{ 
    if (Control.IsKeyLocked(Keys.Insert)) 
    radioButtonInsert.Checked = true; 
    else 
    radioButtonOverstrike.Checked = true; 
} 

參考文獻:Control.IsKeyLocked

注意

文檔說的方法只適用於CAPS LOCK,NUM LOCK,或SCROLL LOCK只關鍵。但用Keys.Insert測試方法已經證明,它也適用於INSERT鍵。

+0

您是否閱讀過文檔? –

+0

是的,我做到了。你有沒有在投票答覆之前嘗試/測試上述代碼?我有!儘管文檔說了什麼,它確實適用於'Keys.Insert'。並且,不會引發一個'NotSupportedException' ... – IronGeek

+0

工作的道歉。我懷疑文檔有誤 –

0

你有兩個選擇:

  1. 聽鍵更改事件,這意味着,你需要保持軌道上根據按鈕何時按下的狀態。
  2. 使用win32 interop,看看例如here
相關問題