Window drag event c# -


i trying hook window drag event of every active/visible windows using c# in system tray app. have code find , move windows figured out using pinvoke, unable figure out how hook drag event.

my goal run program in background , while dragging window able snap preset locations (showing preview windows while drag occurring , snapping when released).

how hook window drag event?

you try set cbt hook , handling case when window moved or sized, though hook monitors more case:

class yourclassname {     const int wh_cbt = 5;      private delegate intptr hookcallback(int ncode, intptr wparam, intptr lparam);      private intptr hhook;     private hookcallback hookcallback = new hookcallback(callback);      [dllimport("user32")]     private static extern intptr setwindowshookex(int idhook, hookcallback lpfn, intptr hmod, int dwthreadid);      [dllimport("user32")]     [return: marshalas(unmanagedtype.bool)]     private static extern bool unhookwindowshookex(intptr hhk);      [dllimport("user32")]     private static extern intptr callnexthookex(intptr hhk, int ncode, intptr wparam, intptr lparam);      [dllimport("kernel32")]     private static extern intptr getmodulehandle(string lpmodulename);      public void sethook()     {         using (process p = process.getcurrentprocess()         {             using (var mainmod = p.mainmodule)             {                 hhook = setwindowshookex(wh_cbt, hookcallback, getmodulehandle(mainmod.modulename, 0);             }         }     }      public bool unhook()     {         return unhookwindowshookex(hhook);     }      public intptr callback(int ncode, intptr wparam, intptr lparam     {         if (ncode < 0)             return callnexthookex(hhook, ncode, wparam, lparam);          switch (ncode)         {              case 0:                   // handle window move/size here                   // wparam handle of window being moved or sized               // other cases...         }          return callnexthookex(hhook, ncode, wparam, lparam);     } } 

don't forget call unhook() before terminating free system resources. more information on setwindowshookex see msdn page.


Comments