Low level mouse hook - mouse freeze on breakpoint - c++

I would like to draw and move my windows by myself (using chromium embedded framework).
To do this, i need a global callback when the mouse is being moved, outside of my window - so i installed a low level mouse hook:
hMouseLLHook = SetWindowsHookEx(WH_MOUSE_LL, (HOOKPROC)mouseHookProc, hInstance, NULL);
The hook simple grabs the mouse events and calls "CallNextHookEx". No problems here, everything works as excpected.
My problem now: if the debugger breaks or an exception is being thrown, I can't move the mouse anymore..
I tried processing the hook in another thread, like so:
HANDLE mouseProcHandle = CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)mouseProcessor, NULL, NULL, &dwMouseProcThread);
DWORD WINAPI Win32Application::mouseProcessor(LPVOID lpParm) {
hMouseLLHook = SetWindowsHookEx(WH_MOUSE_LL, (HOOKPROC)mouseHookProc, ((Win32Application*)Application::getInstance())->hInstance, NULL);
MSG message;
while (GetMessage(&message, NULL, 0, 0)) {
TranslateMessage(&message);
DispatchMessage(&message);
}
UnhookWindowsHookEx(hMouseLLHook);
return 0;
}
But this also does not solve the problem. Is there a workaround, solution or another method to do this?
Also, I think a low level hook may not be necessary, as I only need to be informed about the moevement and it wouldn't be a problem if I would be the last one in line, so the system/other processes can process the mouse callbacks first.

To shed a little more light on this: When you intercept all mouse move events they all end up in your hook which can modify or swallow them. The system therefore calls for every mouse move event your hook and waits until your hook routine is done with it until it calls your hook again for the next pending mouse move event.
Guess what happens when you break into the debugger in your hook event? No more mouse events until you have stepped through your hook routine. Normally you could bring down your whole system with such a central hook. But luckily Windows did anticipate bad hooks. You will notice that after some timeout the system responds to mouse events again. My guess would be that Windows simply removes your hook when it does hang once.
Now about debugging: The only way to safely break into the debugger is to never touch the mouse after you are in the hook. Not very practical. The only way out is to trace the interesting things and look into your log file what did happen inside the hook.
If you are after example code how to hook mouse and keyboard events you can have a look here:
http://etwcontroler.codeplex.com/SourceControl/latest#ETWControler/Hooking/Hooker.cs

As your debugger stop the whole program (all threads of it)
there is probably no workaround if using the hook.
Not as accurate, but you could poll GetCursorPos in a thread instead.

Related

Prevent window movement

I currently have a small game which runs in a win32 window. I just noticed that when I hold the top of the window (the bar which has the closing button) it freezes my application. I would like to disable this as it manages to completely destroy my application (timers continue to count).
It seems that with even the most minimalistic settings for creation of the window it still has this feature. How can I disable this? I currently have:
HWND hWnd = CreateWindowW( L"Game",L"Game",
0x00000000L | 0x00080000L,
wr.left,
wr.top,
wr.right-wr.left,
wr.bottom-wr.top,
NULL,
NULL,
wc.hInstance,
NULL );
I read that my thread is ignored while dragging, if I am forced into using 2 threads could someone please provide a small example of usage?
Or should I stop the timers? (what message should I catch, and would it even be catched?)
Update
I am using instances of my time class to handle timings which looks something like:
Timer::Timer() {
__int64 frequency;
QueryPerformanceFrequency( (LARGE_INTEGER*)&frequency );
invFreqMilli = 1.0f / (float)((double)frequency / 1000.0);
StartWatch();
}
void Timer::StartWatch() {
startCount = 0;
currentCount = 0;
watchStopped = false;
QueryPerformanceCounter( (LARGE_INTEGER*)&startCount );
}
My Win32 message loop contains: mousemove, keyup and keydown.
When DefWindowProc handles WM_SYSCOMMAND with either SC_MOVE or SC_SIZE in the wParam, it enters a loop until the user stops it by releasing the mouse button, or pressing either enter or escape. It does this because it allows the program to render both the client area (where your widgets or game or whatever is drawn) and the borders and caption area by handling WM_PAINT and WM_NCPAINT messages (you should still receive these events in your Window Procedure).
It works fine for normal Windows apps, which do most of their processing inside of their Window Procedure as a result of receiving messages. It only effects programs which do processing outside of the Window Procedure, such as games (which are usually fullscreen and not affected anyway).
However, there is a way around it: handle WM_SYSCOMMAND yourself, resize or move yourself. This requires a good deal of effort, but may prove to be worth it. Alternatively, you could use setjmp/longjmp to escape from the Window Procedure when WM_SIZING is sent, or Windows Fibers along the same lines; these are hackish solutions though.
I solved it (using the first method) this past weekend, if you're interested I have released the code to the public domain on sourceforge. Just make sure to read the README, especially the caveat section. Here it is: https://sourceforge.net/projects/win32loopl/
Since the title bar to the user that he/she can move the window, you could remove that title bar and borders altogether. See "opening a window that has no title bar with win32" for an example.
When the game launches or is paused, you could show your own UI elements to allow the user to move the game window in these specific situations but only then.
You can check for the size/move loop using the WM_ENTERSIZEMOVE and WM_EXITSIZEMOVE messages.

WM_TIMER stops suddenly in ATL ActiveX control

I originally had an ActiveX control that registered a Windows timer (with SetTimer()) that fires every few seconds. That worked fine so far. Now in order to implement a full screen mode, I added a child window to my control that is supposed to show the content while the control itself manages all the ActiveX stuff.
The problem that I have with this approach is that my WM_TIMER suddenly stops firing at some time. I have traced it back to UIDeactivate() being called on my control but I don't know why this method is called (I believe it has something to do with losing focus) when it wasn't called before.
I would also like to know why my WM_TIMER events suddenly stop while everything else still seems to work fine. And what could it have to do with showing the content in a child window instead of on the ActiveX control itself?
Timers stops for a reason. Which might be:
You do stop timer by KillTimer call
Your window is re-created and timer is not re-enabled
Your control is windowless and you actually don't have a HWND handle
There is a collision in timer identifiers, there is something else (e.g. internal subclassed window) out there to use the same identifier, it sets, kill the timer and you no longer see WM_TIMER messages you enabled earlier
The window thread is busy (frozen) with some activity which does not include message dispatching, so timer itself exists, is healthy and alive, just no messages sent
The things to do - without yet additional information on the issue on hands:
Check threads of your window, and your Set/KillTimer calls to make sure they all make sense together
Use Spy++ tool to check messages posted for your window and/or in the thread of the interest, to find out if you really have WM_TIMERs missing, or they just don't reach your code; also you might see other interesting messages around
Here's an excerpt from ATL implementation of CComControlBase (I would guess that your control inherits from that). Check the part marked with <<<<<<<<<<<:
inline HRESULT CComControlBase::IOleInPlaceObject_InPlaceDeactivate(void)
{
if (!m_bInPlaceActive)
return S_OK;
if(m_bUIActive) {
CComPtr<IOleInPlaceObject> pIPO;
ControlQueryInterface(__uuidof(IOleInPlaceObject), (void**)&pIPO);
ATLENSURE(pIPO != NULL);
pIPO->UIDeactivate();
}
m_bInPlaceActive = FALSE;
// if we have a window, tell it to go away.
//
if (m_hWndCD)
{
ATLTRACE(atlTraceControls,2,_T("Destroying Window\n"));
if (::IsWindow(m_hWndCD))
DestroyWindow(m_hWndCD); <<<<<<<<<<<<<<<<<<<<<<<<<<<
m_hWndCD = NULL;
}
if (m_spInPlaceSite)
m_spInPlaceSite->OnInPlaceDeactivate();
return S_OK;
}
On deactivation, the control window gets destroyed. Therefore it can't process WM_TIMER anymore.

Why must SetWindowsHookEx be used with a windows message queue

I've been trying some things with hooks, and I don't understand why hooks must be used with a message queue
hook = SetWindowsHookEx(WH_KEYBOARD_LL, KeyboardProc, NULL, 0);
MSG msg;
while(GetMessage(&msg, NULL, 0, 0) > 0)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
UnhookWindowsHookEx(hook);
Why doesn't something like this work ?
hook = SetWindowsHookEx(WH_KEYBOARD, KeyboardProc, NULL, 0);
cin >> aKey;
UnhookWindowsHookEx(hook);
Using boost threads, and a barrier doesn't work either. Why can't the waiting between the hook and unhook be done in another manner ?
EDIT:
I did a mistake when I created this sample, I create a WH_KEYBOARD_LL hook, not WH_KEYBOARD, (I don't think it makes a big difference)
Also the loop never executes only waits on the GetMessage function.
The loop executes only when I post the quit message PostThreadMessage(id, WM_QUIT, 2323, NULL); so I don't understand what does it do beside waiting, is there some internal processing ?
RELATED:
C++ SetWindowsHookEx WH_KEYBOARD_LL Correct Setup
How can I set up a CBT hook on a Win32 console window?
The low-level hooks, WH_KEYBOARD_LL and WH_MOUSE_LL are different from all the other hooks. They don't require a DLL to be injected into the target process. Instead, Windows calls your hook callback directly, inside your own process. To make that work, a message loop is required. There is no other mechanism for Windows to make callbacks on your main thread, the callback can only occur when you've called Get/PeekMessage() so that Windows is in control.
A global hook like WH_KEYBOARD is very different. It requires a DLL and the callback occurs within the process that processes the keyboard message. You need some kind of inter-process communication to let your own program be aware of this. Named pipes are the usual choice. Which otherwise of course requires that this injected process pumps a message loop. It wouldn't get keyboard messages otherwise.
Favor a low-level hook, they are much easier to get going. But do pump or it won't work. And beware of timeouts, if you're not responsive enough then Windows will kill your hook without notice.
Understanding the low-level mouse and keyboard hook (win32)
Windows Hooks hook the Windows message loop: http://msdn.microsoft.com/en-us/library/ms644959#wh_keyboardhook
The WH_KEYBOARD hook enables an application to monitor message traffic
for WM_KEYDOWN and WM_KEYUP messages about to be returned by the
GetMessage or PeekMessage function. You can use the WH_KEYBOARD hook
to monitor keyboard input posted to a message queue.
Console applications don't pump messages themselves - the console process does. So it won't work unless the process has a message loop.
See:
How can I set up a CBT hook on a Win32 console window?
C++ SetWindowsHookEx WH_KEYBOARD_LL Correct Setup

How to use mouse hook so current window never sees specific mouse message?

I want some window to never receive mouse wheel up/downs, i can control this messages trough my mouse hook fine but is there a way to make a window never receive those messages?
I can validate the window trough mouse hook and check if its active then just never send that message to it.
I installed mouse hook globally so i believe i have everything needed.
AFAIK hooks may not block the message from reaching the wndproc of the appropriate window.
You may however achieve what you need by subclassing the appropriate windows. That is, replace the window procedure of the appropriate window (use SetWindowLongPtr with GWL_WNDPROC flag) by your wndproc. It should pass all the messages to the original wndproc, apart from those that you want to filter-out.

Mouse jiggling / message processing loop

I have written a multithreaded program which does some thinking and prints out some diagnostics along the way. I have noticed that if I jiggle the mouse while the program is running then the program runs quicker. Now I could go in to detail here about how exactly I'm printing... but I will hold off just for now because I've noticed that in many other programs, things happen faster if the mouse is jiggled, I wonder if there is some classic error that many people have made in which the message loop is somehow slowed down by a non-moving mouse.
EDIT: My method of "printing" is as follows... I have a rich edit control window to display text. When I want to print something, I append the new text on to the existing text within the window and then redraw the window with SendMessage(,WM_PAINT,0,0).
Actually its a bit more complicated, I have multiple rich edit control windows, one for each thread (4 threads on my 4-core PC). A rough outline of my "my_printf()" is as follows:
void _cdecl my_printf(char *the_text_to_add)
{
EnterCriticalSection(&my_printf_critsec);
GetWindowText(...); // get the existing text
SetWindowText(...); // append the_text_to_add
SendMessage(...WM_PAINT...);
LeaveCriticalSection(&my_printf_critsec);
}
I should point out that I have been using this method of printing for years in a non-multithreaded program without even noticing any interaction with mouse-jiggling.
EDIT: Ok, here's my entire messageloop that runs on the root thread while the child threads do their work. The child threads call my_printf() to report on their progress.
for(;;)
{
DWORD dwWake;
MSG msg;
dwWake = MsgWaitForMultipleObjects(
current_size_of_handle_list,
hThrd,
FALSE,
INFINITE,
QS_ALLEVENTS);
if (dwWake >= WAIT_OBJECT_0 && dwWake < (WAIT_OBJECT_0 + current_size_of_handle_list))
{
int index;
index = dwWake - WAIT_OBJECT_0;
int j;
for (j = index+1;j < current_size_of_handle_list;j++)
{
hThrd[j-1] = hThrd[j];
}
current_size_of_handle_list--;
if (current_size_of_handle_list == 0)
{
break;
}
}
else if (dwWake == (WAIT_OBJECT_0 + current_size_of_handle_list))
{
while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
else if (dwWake == WAIT_TIMEOUT)
{
printmessage("TIMEOUT!");
}
else
{
printmessage("Goof!");
}
}
EDIT: Solved!
This may be an ugly solution - but I just changed the timeout from infinite to 20ms, then in the if (dwWake == WAIT_TIMEOUT) section I swapped printmessage("TIMEOUT!"); for:
while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
I'm not closing this question yet because I'd still like to know why the original code did not work all by itself.
i can see 3 problems here:
the documentation for WM_PAINT says: The WM_PAINT message is generated by the system and should not be sent by an application. unfortunately i don't know any workaround, but i think SetWindowText() will take care of repainting the window, so this call may be useless.
SendMessage() is a blocking call and does not return until the message has been processed by the application. since painting may take a while to be processed, your program is likely to get hanged in your critical section, especially when considering my 3rd point. PostMessage() would be much better here, since you have no reason to need your window to be repainted "right now".
you are using QS_ALLEVENTS in MsgWaitForMultipleObjects(), but this mask DOES NOT include the QS_SENDMESSAGE flag. thus your SendMessage() call is likely ignored and does not wake your thread. you should be using QS_ALLINPUT.
can you check the behavior of your application with an INFINITE timeout and the above 3 modifications included ?
If I remember correctly, WM_PAINT is a very low priority message, and will only get relayed when the message queue is otherwise empty. Also, Windows will coalesce multiple WM_PAINT messages into one. I could see the mouse movement resulting in fewer redraw events, each handling a larger update, thus improving performance.
Well I can't totally help you because we don't have enough info but I had a similar problem where my application would not refresh unless I moved the mouse or after some (not unsignificant) delay.
When investigating the problem I found that basically, the GUI thread will sleep if there is no more messages to process. Jiggling the mouse will create new windows messages to be sent to the windows, waking the thread from sleep.
My problem was that I was doing my processing in the OnIdle (MFC, not sure about you) function, and that, after doing the processing one time, the thread would go to sleep.
I don't think that is your problem since you seems to post a windows message (WM_PAINT) from your thread, what I wasn't doing in my case (which should wake up the gui thread) but maybe this can help you get in the right direction to solve your problem?
Edit: I though about it a little, maybe there is a special case for WM_PAINT (like you forget to call Invalidate or something, I'm not an expert in windows programming) so maybe try to post another message like WM_USER to your application and see if it fix your problem (this should be sure to wake up the gui thread I think). Also posting the full call to the SendMessage function could help.
Edit2: Well, after seeing your comment to Kelly French above you seems to have exactly the same symptoms I had so I would guess that, for whatever reason, your call to PostMessage do not seems to wake up the gui thread or something similar. What are you passing for first argument to PostMessage? What I did in my case was to call PostMessage with argument WM_USER, 0, 0 to my app. You can also try the PostThreadMessage variant while keeping the current threadID of the main thread in a variable (see GetCurrentThreadId).
Also you could try to call Invalidate on your object. Windows keeps memory of if an object need to be repainted and will not do it if it is not needed. I do not know if a direct call to WM_PAINT override this or not.
Well that's all I can think of. At least you found a fix even if it is not the most elegant.
Are you completely sure that the program really runs faster? Or is it output that is refreshed more frequently?
Are you using SendMessage or PostMessage? I'm curious if perhaps switching to the other will make things work "better" in this particular environment.
Taken from developerfusion:
There’s another similar API which
works exactly like SendMessage and
that is PostMessage API. Both require
same parameters but there’s a slight
difference. When a message is sent to
a window with SendMessage, the window
procedure is called and the calling
program (or thread) waits for the
message to be processed and replied
back, and until then the calling
program does not resume its
processing. One thing is wrong with
this approach however, that is if the
program that is busy carrying out long
instructions or a program that has
been hung and hence no time to respond
to the message will in turn hang your
program too because your program will
be waiting for a reply that may never
arrive. The solution to this is to use
PostMessage instead of SendMessage.
PostMessage on the otherhand returns
to the calling program immediately
without waiting for the thread to
process the message, hence saving your
program from hanging. Which of them
you have to use depends on your
requirement.
Is your GUI window maximized? Does it happen whether the mouse movement happens over your app window or over some other window like another app or the desktop? When the mouse moves over your app, the mouse_move messages get sent to your message queue. This may wake up the thread or be forcing a WM_PAINT message.
I doubt that the printing is actually going faster. I suspect that the increased number of messages caused by the mouse movement is forcing more window invalidation events so the text updates are happening on a more granular basis. When the mouse isn't being moved does the printing happen in larger blocks, say blocks of 20 characters vs 5 characters at a time?
Could you clarify what you mean by faster printing? Is it absolute, like 100 characters per minute vs 20 characters per minute? Or is it more like 100 characters per minute either way but they show up in blocks when the mouse is still?
One possibility is that you are seeing the effect of the OS doing thread priority boosting / retarding for certain GUI messages.
I am assuming you have one ”GUI & Other Stuff” thread, and multiple worker threads. When there is no GUI activity, the “Other Stuff” thread goes to a lower priority. When you wiggle the mouse or timeout, the “Other Stuff” thread goes to a higher priority.
Changing the worker threads to a lower priority and then wiggling the mouse, would confirm or refute this.
I think it has to do with processing in foreground and background. If the operating system thinks your window is not top priority it shifts your job to background. If you are forcing the window to be on top, it will put all its resources to work on your window and drops the other items it is working on. Its real and its been here since DOS. http://en.wikipedia.org/wiki/Foreground-background You might try calling the following at critical times in your code.
Private Declare Function SetForegroundWindow Lib "user32" (ByVal hwnd As Long) As Long