I am getting key strokes from keyboard. First I start listening keystrokes as follows:
Code
Process _this = Process.GetCurrentProcess(); ProcessModule mod = _this.MainModule; hd = HookFunc; kh = _kh; hhk = API.SetWindowsHookEx(13, hd, API.GetModuleHandle(mod.ModuleName), 0);Then according to some condition I stop listening keystrokes as follows:
Code
return API.UnhookWindowsHookEx(hhk);The problem is, when I want to listen to keystrokes again, It does NOT capture them.
Any help please?
Best Regards.

VulpesRank #55 · 29.2K reputationPosted Jan 5, 2012, 6:28 AM EST
Are you sure that there's nothing in the hook function, HookFunc, which would prevent you from trapping the keystrokes a second time?
If there isn't, I'd make sure that the call to SetWindowsHookEx is in fact succeeding by checking the return value. A return value of IntPtr.Zero indicates failure.
As you may know, it's possible to get the reason for failure by setting the SetLastError flag to True in the DllImport attribute for the unmanaged function (probably done automatically if you're using an API wrapper) and then calling the managed method Marshal.GetLastWin32Error() to get the error code.
Sam HobbsRank #108 · 20.5K reputationPosted Jan 5, 2012, 11:00 PM EST
The following works for me; I can set and remove the hook multiple times. Your problem exists with something you are not showing. It is likely a simple mistake, because we usually look for more complicated explanations.
Except after a few dozen keys, the garbage collector will eventually clobber something that the unmanaged code needs. I do not know what, so I will leave that for you to figure out.
public static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);VulpesRank #55 · 29.2K reputationPosted Jan 6, 2012, 12:26 AM EST
Puzzlingly, your model of the app is much the same as mine though I'm not experiencing the same problem :-/
I don't think it can be the reason why Cenk's app is not working as he's reassigning the delegate to 'hd' each time he's setting the hook.
Sam HobbsRank #108 · 20.5K reputationPosted Jan 6, 2012, 12:56 AM EST
Note that the garbage collection issue does not happen to me until I have at least typed a couple dozen characters.
VulpesRank #55 · 29.2K reputationPosted Jan 6, 2012, 1:09 AM EST
Sam HobbsRank #108 · 20.5K reputationPosted Jan 6, 2012, 1:42 AM EST
RaysefoRank #4,173 · 360 reputationPosted Jan 6, 2012, 3:23 AM EST