Reputation: 21
I am trying to get global mouse position. I have a hook working that can get the mouse position, however it only has access to it inside the hook code. Trying to access the data inside main doesn't work.
The best way to explain this is with code:
LRESULT CALLBACK mouseHookProc(int nCode, WPARAM wParam, LPARAM lParam)
{
PMSLLHOOKSTRUCT p = (PMSLLHOOKSTRUCT) lParam;
position.x = p->pt.x;
position.y = p->pt.y;
std::cout<<position.x<<std::endl;
return CallNextHookEx(NULL, nCode, wParam, lParam);
}
int WINAPI WinMain (HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpszArgument,int nCmdShow)
{
HHOOK mouseHook = SetWindowsHookEx(WH_MOUSE_LL,mouseHookProc,hInstance,NULL);
MessageBox(NULL, "Press OK to close.", "", MB_OK);
return 0;
}
With the above code, moving the mouse will show the new position in the console window. However, if I put the std::cout<<position.x<<std::endl;
inside of main, it will just say 0. position
is a global variable.
Code when the output is inside of main:
LRESULT CALLBACK mouseHookProc(int nCode, WPARAM wParam, LPARAM lParam)
{
PMSLLHOOKSTRUCT p = (PMSLLHOOKSTRUCT) lParam;
position.x = p->pt.x;
position.y = p->pt.y;
return CallNextHookEx(NULL, nCode, wParam, lParam);
}
int WINAPI WinMain (HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpszArgument,int nCmdShow)
{
HHOOK mouseHook = SetWindowsHookEx(WH_MOUSE_LL,mouseHookProc,hInstance,NULL);
for(;;)
{
std::cout<<position.x<<std::endl;
}
MessageBox(NULL, "Press OK to close.", "", MB_OK);
return 0;
}
The first chunk of code works fine, it detects the mouse position, I just don't know how to get the x,y data into my main.
Upvotes: 0
Views: 5185
Reputation: 145239
re this posted code:
LRESULT CALLBACK mouseHookProc(int nCode, WPARAM wParam, LPARAM lParam)
{
PMSLLHOOKSTRUCT p = (PMSLLHOOKSTRUCT) lParam;
position.x = p->pt.x;
position.y = p->pt.y;
return CallNextHookEx(NULL, nCode, wParam, lParam);
}
int WINAPI WinMain (HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpszArgument,int nCmdShow)
{
HHOOK mouseHook = SetWindowsHookEx(WH_MOUSE_LL,mouseHookProc,hInstance,NULL);
std::cout<<position.x<<std::endl;
MessageBox(NULL, "Press OK to close.", "", MB_OK);
return 0;
}
Here's what the main function specifies should happen:
SetWindowsHookEx
(this happens once).position
(this happens once).MessageBox
(this happens once).That's all.
During the call to MessageBox
the hook procedure is called (whenever you move your mouse), but it doesn't do anything visible, just an internal update.
Why did you expect more?
How to fix:
MessageBox
, which doesn't do any output, code up your own.WinMain
monstrosity with a standard C and C++ main
.Upvotes: 2
Reputation: 3669
For global hook the hook procedure mouseHookProc
should be in a DLL so that it can be injected into processes.
Check this:
http://www.codeproject.com/Articles/1037/Hooks-and-DLLs
Upvotes: 1