c# - KeyHook in another thread -
in c# app want keyhook so, method invoked when key pressed invoked in thread. in way not happen, key omitted program, because application busy else. how can make in thread? have found information that, depending on thread in create hook, method invoked when key pressed invoked in thread, not happen. regardless of thread in hooked it, method invoked in main thread. please help. outline of code:
int hookproc(int code, int wparam, ref lparamstruct lparam) { // ... should invoked in thread - thread th, use call setwindowshook } void setwindowshook() { lpmsg msg = new lpmsg(); peekmessage(out msg, new intptr(0), 0, 0, pm_noremove); hhook = setwindowshookex(wh_keyboard_ll, hookproc, new intptr(0), 0); while (getmessage(out msg, new intptr(0), 0, 0)) { defwindowproc(msg.hwnd, msg.message, msg.wparam, msg.lparam); if (abortthreadflag) break; } unhookwindowshookex(hhook); }
setwindowshook invoked in way, id doesn't force method invoked in thread:
thread th = new thread(setwindowshook); th.start()
the point of message loop give windows opportunity call hook procedure. there no other way call code. cannot break in , force thread run code, cause horrible re-entrancy problems. hook procedure can run when code calls getmessage(). , run in context of thread. can verify looking @ return value of getcurrentthreadid().
using thread otherwise no fix slow hook procedure. windows won't dispatch other input events until hook procedure returns. make slow enough , windows kill hook forcibly recover. consider using worker thread feed thread-safe queue instead, allowing hook procedure return.
Comments
Post a Comment