2010-07-08 61 views
1

我正在開發一個應用程序,需要處理OS發送給任何應用程序的所有消息。SetWindowsHookEx函數問題C#

的代碼工作正常,只有WH_KEYBOARD_LL,但失敗,WH_GETMESSAGE或WH_CALLWNDPROC

class Program 
{ 
    private const int WH_KEYBOARD_LL = 13; 
    private const int WH_GETMESSAGE = 3; 
    private const int WH_CALLWNDPROC = 4; 
    private const int WM_KEYDOWN = 0x0100; 
    private static HookProc _proc = new HookProc(HookCallback); 
    private static IntPtr _hookID = IntPtr.Zero; 

    static void Main(string[] args) 
    { 
     TextWriter tw = new StreamWriter("date.txt"); 
     tw.Write(DateTime.Now); 
     tw.Close(); 

     _hookID = SetHook(_proc); 
     Application.Run(); 
     UnhookWindowsHookEx(_hookID); 
    } 
    private static IntPtr SetHook(HookProc proc) 
    { 
     using (Process curProcess = Process.GetCurrentProcess()) 
     using (ProcessModule curModule = curProcess.MainModule) 
     { 
      return SetWindowsHookEx(WH_CALLWNDPROC , proc, 
       GetModuleHandle(curModule.ModuleName), 0); 
     } 
    } 

    private delegate IntPtr HookProc(int code, IntPtr wParam, IntPtr lParam); 

    private static IntPtr HookCallback(int code, IntPtr wParam, IntPtr lParam) 
    { 
     // This method is never called 

     return CallNextHookEx(_hookID, code, wParam, lParam); 
    } 

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] 
    private static extern IntPtr SetWindowsHookEx(int idHook, 
     HookProc lpfn, IntPtr hMod, uint dwThreadId); 

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] 
    [return: MarshalAs(UnmanagedType.Bool)] 
    private static extern bool UnhookWindowsHookEx(IntPtr hhk); 

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] 
    private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, 
     IntPtr wParam, IntPtr lParam); 

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] 
    private static extern IntPtr GetModuleHandle(string lpModuleName); 
} 

}

編輯:

我認爲這個問題是在.NET框架的工作

.NET Framework不支持全局鉤子 除WH_KEYBOARD_LL低級鉤子和WH_MOUSE_L L低級別掛鉤,您無法在Microsoft .NET Framework中實現全局掛鉤。

http://support.microsoft.com/kb/318804

回答

0

爲什麼你傳遞curModule.ModuleName到WINAPI?