How to simulate Alt + Tab using Win32 hooks?

I wrote this program in C ++ using VS2010 to determine when the user makes the double middle mouse button, switch to the next window (as Alt + Tab does) and stop the hook chain. Here is my code:

DLL:

extern "C"__declspec (dllexport) LRESULT CALLBACK HookProc(int nCode, WPARAM wParam, LPARAM lParam) { if (nCode<0) return CallNextHookEx(NULL,nCode,wParam,lParam); if (wParam == WM_MBUTTONDBLCLK) { PostMessage(GetActiveWindow(),WM_SYSCOMMAND,SC_NEXTWINDOW,0); } else return CallNextHookEx(NULL,nCode,wParam,lParam); // if EVERYTHING_IS_OK return TRUE; } 

EXE:

 do{ nMenu = choose(); switch (nMenu) { case 1: hLib = LoadLibrary(cLibName); hProc = (HOOKPROC) GetProcAddress(hLib, "HookProc"); hHook = SetWindowsHookEx(WH_MOUSE, hProc, hLib, NULL); break; case 2: UnhookWindowsHookEx(hHook); break; case 0: ; } } while (nMenu); 

I run the program and set the hook, then the program freezes and the mouse stops working in most applications (it works in Chrome though). What am I doing wrong?

+4
source share
1 answer

Hooks are evil if they are not used only as notifications. MSDN strongly recommends calling CallNextHookEx() for any reason. You cannot know at what point you are in the calling chain. This makes your code fragile, even if it can work first.

You depend on other hook API users to be nice with you, i.e. call you. If someone (for example, you) does not, your code breaks.

Without going into details where your code breaks down, I think it’s not surprising that

mouse stops working in most applications

if you close other users of the mouse hook by returning TRUE , right?

+3
source

Source: https://habr.com/ru/post/1384483/


All Articles