2015-10-20 32 views
0

我目前正在嘗試做一個keydown註冊。基本上只是爲了查看哪些鍵我使用最多。 問題是隻希望它檢測到F1-F12按鈕。 另一個問題是不知道如何攻擊它,因爲它必須是globalevent。KeyDown問題c#

if (e.KeyCode.ToString() == "F1") 
{ 
    MessageBox.Show("F1 pressed"); 
} 

是我一直在嘗試,到目前爲止,我不得不專注於它的應用程序工作壽。

我不希望用戶自己註冊熱鍵。 我希望他們設置,這是從Set global hotkeys using C#

+0

你想讓它在全球範圍內工作嗎?我的意思是,在每一個應用程序,而不僅僅是你的? – Nasreddine

+0

非常好耶。 – Hajpz

+0

搜索低級鍵盤掛鉤。代碼項目中也有一個解決方案。我認爲這就是你想要的。進入第一個搜索結果https://www.google.com/search?q=low+leve+key+press+event+c%23&ie=utf-8&oe=utf-8 –

回答

0

當我需要做的在C#有什麼不同這一點,我只需要導入的User32.dll,並利用GetASyncKeyState功能如下:

[DllImport("User32.dll")] 
private static extern short GetAsyncKeyState(System.Windows.Forms.Keys vKey); 

private void globalKeyThread() 
{ 
    int state; 
    System.Windows.Forms.Keys keyToCheck = Keys.Space; 

    while (true) 
    { 
     state = Convert.ToInt32(GetAsyncKeyState(keyToCheck)); 

     if (state == -32767) 
     { 
     // Handle what happens when key is pressed. 
     } 

     Thread.Sleep(10); 
    } 
} 
+0

沒有錯誤,當我使用該但是該應用程序似乎沒有得到,我按空間。 – Hajpz

0
private void globalKeyThread() 
     { 
      System.Windows.Forms.Keys keyToCheck = Keys.F12; 

      while (true) 
      { 
       state = Convert.ToInt32(GetAsyncKeyState(keyToCheck)); 

       if (state == -32767) 
       { 
        // Handle what happens when key is pressed. 
        timer1.Start(); 
       } 

       Thread.Sleep(10); 
      } 
     } 

這裏的問題可能是Int32的迴應? 由於應用程序不是很瞭解我想要做什麼。