I written a some program. It hook a user input through SetWindowsHookEx. and it works very well.
and then I want to know how implement WindowsHook in different thread, for learning C#.
but i’m newly in C#, so i can’t find answer.
help me.
thanks.
edit
here is my InputHook class. some codes were abbreviated.
public class InputHooker
{
public delegate IntPtr inputHookedDelegate(int nCode, IntPtr wParam, IntPtr lParam);
public inputHookedDelegate keyHookHandler;
public InputHooker()
{
keyHookHandler = onKeyHooked;
}
public void StartInputHook()
{
using (Process curProcess = Process.GetCurrentProcess())
using (ProcessModule curModule = curProcess.MainModule)
{
curKeyHookID = SetWindowsHookEx(WH_KEYBOARD_LL, keyHookHandler, GetModuleHandle(curModule.ModuleName), 0);
}
}
private IntPtr onKeyHooked(int nCode, IntPtr wParam, IntPtr lParam)
{
return CallNextHookEx(curKeyHookID, nCode, wParam, lParam);
}
}
And I tried like following code;
MyInputHooker = new InputHooker();
Thread myInputHookThread = new Thread(new ThreadStart(MyInputHooker.StartInputHook));
myInputHookThread.Name = "UOCInputHookThread";
myInputHookThread.Priority = ThreadPriority.Normal;
myInputHookThread.Start();
but it dosen’t works. (SetWindowsHookEx was successed, but onKeyHooked dosen’t called in keyboard pressed.) instead, follwing code works very well.
MyInputHooker = new InputHooker();
MyInputHooker.StartInputHook();
The reason this is failing can be found in the WinAPI documentation here:
http://msdn.microsoft.com/en-us/library/ms644985(v=vs.85).aspx
What’s happening is that your newly-created thread is setting the hook and exiting immediately, so when Windows wants to call your hook procedure by sending a message to the thread, it can’t find it because it has already exited.
If this is just for learning purposes, you can put a message pump in the thread by calling
Application.Runat the end of yourStartInputHookmethod. (At least I think that will work — haven’t tried it myself.) For real code, the best thing to do is callSetWindowsHookExin your main application thread. I’m assuming that you’re doing that already in the case where it works and the application’s message pump is taking care of this for you.Honestly, if this is just for learning C#,
SetWindowsHookExmight be a bit too advanced. Using it requires knowledge of how a lot of things work under the covers.