2012-01-18 22 views
8

我想註冊一個熱鍵,我翻譯this C++代碼,我寫它:如何在C#中使用RegisterHotKey()?

using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Runtime.InteropServices; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     [DllImport("user32.dll")] 
     public static extern 
      bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, int vk); 
     [DllImport("user32")] 
     public static extern 
      bool GetMessage(ref Message lpMsg, IntPtr handle, uint mMsgFilterInMain, uint mMsgFilterMax); 

     public const int MOD_ALT = 0x0001; 
     public const int MOD_CONTROL = 0x0002; 
     public const int MOD_SHIFT = 0x004; 
     public const int MOD_NOREPEAT = 0x400; 
     public const int WM_HOTKEY = 0x312; 
     public const int DSIX = 0x36; 

     static void Main(string[] args) 
     { 
      if (!RegisterHotKey(IntPtr.Zero, 1, MOD_ALT | MOD_NOREPEAT, DSIX)) 
      { 
       Console.WriteLine("failed key register!"); 
      } 

      Message msg = new Message(); 

      while (!GetMessage(ref msg, IntPtr.Zero, 0, 0)) 
      { 
       if (msg.message == WM_HOTKEY) 
       { 
        Console.WriteLine("do work.."); 
       } 
      } 

      Console.ReadLine(); 
     } 
    } 

    public class Message 
    { 
     public int message { get; set; } 
    } 
} 

但它永遠RegisterHotKey()返回false。 我不知道有關方法傳遞的參數,IntPtr.Zero是是相當於爲null,消息類的第二個參數需要的對象。有人可以澄清嗎?任何幫助非常感謝!

+0

見[這裏](http://bloggablea.wordpress.com/ 2007/05/01 /全局熱鍵,用網/) – Shai 2012-01-18 14:46:33

+0

注意:您的MOD_NOREPEAT值是錯誤的。 https://msdn.microsoft.com/en-us/library/windows/desktop/ms646309(v=vs.85).aspx – 2016-09-24 15:51:00

+0

你的榜樣工程完美,如果你使用MOD_NOREPEAT和正確的GetMessage適當的恆定值()定義(其返回int,並使用從System.Windows.Interop命名空間MSG結構) – tigrou 2018-02-11 19:19:19

回答