c# - Mouse hook getting disconnected -


i'm trying implement color picker takes color pixel everywhere in screen. i'm planning use global mouse hook listen wm_mousemove in order update color mouse moved around , listen mouse clicks confirm (wm_lbuttondown) or cancel(wm_rbuttondown) operation.

i have followed 1 of many tutorials around , came (in console application, test out if process works):

static intptr hook; static bool click; static nativemethods.lowlevelhookstruct llhs;  static void main(string[] args) {   hook = nativemethods.setwindowshookex(nativemethods.wh_mouse_ll, mousehookcallback, (intptr)null, 0);   if (hook != intptr.zero)   {     console.writeline("hook set");     while (!console.keyavailable) {       console.writeline("{0} {1} {2}", hook, llhs.pt.x, llhs.pt.y);        if(click) console.writeline("click!");       click = false;        system.threading.thread.sleep(250);      }   } } 

and

public static intptr mousehookcallback(int ncode, intptr wparam, intptr lparam) {   if (ncode >= 0)   {     nativemethods.lowlevelhookstruct hookstruct = (nativemethods.lowlevelhookstruct)marshal.ptrtostructure(lparam, typeof(nativemethods.lowlevelhookstruct));      if (nativemethods.mousemessages.wm_mousemove == (nativemethods.mousemessages)wparam)     {       llhs = hookstruct;     }      if (nativemethods.mousemessages.wm_lbuttondown == (nativemethods.mousemessages)wparam)     {       click = true;     }     else if (nativemethods.mousemessages.wm_rbuttondown == (nativemethods.mousemessages)wparam)     {     }   }    return nativemethods.callnexthookex(hook, ncode, wparam, lparam); } 

nativemethods class keep dllimport related stuff.

once run console application, mouse cursor gets stuck couple of seconds, , in console - while cursor is stuck

hook set 3945554872 0 0 3945554872 0 0 3945554872 0 0 3945554872 0 0 ... 

going @ in debug, seems hook never called, not once. idea might wrong?

following @hans passant comment moved test code winforms application, , callbacks started coming.

then matter find out callback being garbage collected, had change

hook = nativemethods.setwindowshookex(nativemethods.wh_mouse_ll, mousehookcallback, (intptr)null, 0); 

to

private nativemethods.lowlevelhookproc _hookcallback;  ...  _hookcallback = new nativemethods.lowlevelhookproc(mousehookcallback); hook = nativemethods.setwindowshookex(nativemethods.wh_mouse_ll, _hookcallback, (intptr)null, 0); 

in order keep reference callback not gced.


Comments

Popular posts from this blog

python - How to insert QWidgets in the middle of a Layout? -

python - serve multiple gunicorn django instances under nginx ubuntu -

module - Prestashop displayPaymentReturn hook url -