Determine which window the message was sent (SetWindowsHookEx & WH_KEYBOARD) - c++

I need to be able to determine which window the message is intended for, but I don’t understand how to do it correctly. In WH_MOUSE has a special structure (MOUSEHOOKSTRUCT) that stores the hwnd of the window, but where to get the hwnd in WH_KEYBOARD?
LRESULT CALLBACK messageHandler(int nCode, WPARAM wParam, LPARAM lParam)
{
// ???
}
DWORD WINAPI messageDispatcher(LPVOID thread)
{
hookHandle = SetWindowsHookEx(WH_KEYBOARD, messageHandler, GetModuleHandle(nullptr), *reinterpret_cast<DWORD*>(thread));
if (!hookHandle)
{
return GetLastError();
}
MSG message{};
while (GetMessage(&message, 0, 0, 0) > 0)
{
TranslateMessage(&message);
DispatchMessage(&message);
}
return 0;
}
In theory, I could use GetForegroundWindow, but it seems to me that this is a terrible option, because the window can receive a keyboard message from some other process (if another process sends a SendMessage to this window) and not the fact that the current window will be exactly the one for which the message was intended.

At the time a keyboard action is generated, the OS doesn't know yet which window will eventually receive the message. That is why the WH_KEYBOARD hook doesn't provide a target HWND, like a WH_MOUSE hook does (since a mouse message carries window-related coordinates).
When a keyboard message is being routed to a target, the message gets delivered to the window that currently has input focus.
Per About Keyboard Input:
The system posts keyboard messages to the message queue of the foreground thread that created the window with the keyboard focus. The keyboard focus is a temporary property of a window. The system shares the keyboard among all windows on the display by shifting the keyboard focus, at the user's direction, from one window to another. The window that has the keyboard focus receives (from the message queue of the thread that created it) all keyboard messages until the focus changes to a different window.
Since your hook runs inside of the message queue of the target thread, you can use GetFocus() to get the target HWND at that time:
Retrieves the handle to the window that has the keyboard focus, if the window is attached to the calling thread's message queue.
Otherwise, you can use a WH_CALLWNDPROC/RET hook instead, which gets called when the message is actually delivered to a window. However, you can't block messages with this hook (as you were asking about in your previous question).

I think what you might be looking for is a hook of type WH_JOURNALRECORD.
With this, the callback procedure that Windows will call in response to the various events that this hook intercepts is of type JournalRecordProc, and the lparam parameter passed to this function points to an EVENTMSG structure, which looks like this:
typedef struct tagEVENTMSG {
UINT message;
UINT paramL;
UINT paramH;
DWORD time;
HWND hwnd;
} EVENTMSG;
And there is your hwnd!

Related

Winapi - Alternatives to WM_CLOSE

I know with Windows notification message, WM_CLOSE refers to closing the window via "X" button on the top right hand corner of the window.
Does anyone know the notification message for closing with File->Exit?
The reason I asked is because I'm trying to implement JNI native code to gracefully close window when user initiated system shutdown. refer to my earlier post (Winapi - SetWindowLongPtr in ShutdownBlockReasonCreate / Destroy implementation of JNI native code) for background.
When clicking on 'X' to close, confirmation dialog box comes up which prevents shutdown reason message from disappearing (when I expect it to disappear after a while). I know File->Exit from menu bar doesn't ask for confirmation, but how do I implement this using windows notification message?
After some digging around the only suggestions I found is to use DestroyWindow. So I tried closing the window using DestroyWindow() function, but it only "Destroys" the window, rather than ending the whole application. Here's my switch statement in my WndProc CallBack function:
switch (message) {
case WM_QUERYENDSESSION:
PostMessage(hWnd, WM_CLOSE, 0, 0);
return 0;
case WM_ENDSESSION:
PostMessage(hWnd, WM_CLOSE, 0, 0);
return 0;
case WM_CLOSE:
DestroyWindow(hWnd);
break;
case WM_NCDESTROY:
RemoveWindowSubclass(hWnd, AppWndProc, uIdSubclass);
break;
}
Any help would be much appreciated!
Cheers
I know with Windows notification message, WM_CLOSE refers to closing the window via "X" button on the top right hand corner of the window.
Actually, when the window's standard "X" button is clicked (or the standard "Close" item on the window's top-left corner menu is selected if enabled, or the window receives an ALT+F4 keystroke), a WM_SYSCOMMAND message is issued to the window with the wParam containing the SC_CLOSE flag. If that message is passed to DefWindowProc() (the default behavior), it then issues a WM_CLOSE message to the window.
See Closing the Window.
It is possible that other conditions can also cause a WM_CLOSE message to be issued.
Does anyone know the notification message for closing with File->Exit?
What happens when that menu item is selected is defined by the application, not the OS. The application can do whatever it wants, including destroying the window immediately if it wants to.
However, that being said, if the menu is a standard Win32 menu, then the window will receive a WM_COMMAND message containing the ID of the menu item that was selected, at least.
The reason I asked is because I'm trying to implement JNI native code to gracefully close window when user initiated system shutdown.
By default, you don't need to do anything for that. The OS automatically closes all open windows during system shutdown. Rather than closing your window manually, you should instead react to your window being closed, if you need to clean up any resources.
When clicking on 'X' to close, confirmation dialog box comes up which prevents shutdown reason message from disappearing (when I expect it to disappear after a while).
Then the application is not handling system shutdown correctly.
Most applications present such a confirmation box in response to receiving the WM_CLOSE message. If the confirmation is aborted, the application discards the message and moves on. However, applications shouldn't prompt the user for confirmation during system shutdown. But not all applications follow that rule.
I know File->Exit from menu bar doesn't ask for confirmation
Again, that is for the application to decide, not the OS.
how do I implement this using windows notification message? After some digging around the only suggestions I found is to use DestroyWindow.
Correct. Or, you can alternatively post a WM_QUIT message to the message queue instead. See the PostQuitMessage() function.
So I tried closing the window using DestroyWindow() function, but it only "Destroys" the window, rather than ending the whole application.
It is the application's responsibility to terminate itself, usually by exiting its message loop when its main window has been destroyed.
Here's my switch statement in my WndProc CallBack function:
There is no need to post WM_CLOSE in response to WM_QUERYENDSESSION or WM_ENDSESSION. Let the OS handle that for you.
If you don't want the confirmation to appear during system shutdown, change your code to something more like this:
bool shuttingDown = false;
LRESULT CALLBACK AppWndProc(
_In_ HWND hWnd,
_In_ UINT message,
_In_ WPARAM wParam,
_In_ LPARAM lParam,
_In_ UINT_PTR uIdSubclass,
_In_ DWORD_PTR dwRefData
) {
switch (message) {
case WM_QUERYENDSESSION:
shuttingDown = true;
break;
case WM_ENDSESSION:
if (wParam == FALSE)
shuttingDown = false;
break;
case WM_CLOSE:
if (shuttingDown) {
DestroyWindow(hWnd);
// or:
// PostQuitMessage(0);
return 0;
}
break;
case WM_NCDESTROY:
RemoveWindowSubclass(hWnd, AppWndProc, uIdSubclass);
break;
}
return DefSubclassProc(hWnd, message, wParam, lParam);
}
There's no specific message to handle your File>Exit. You must handle it as any other menu item:
Define an identifier for your menu item. Choose anything you want, it has no particular meaning for windows.
When constructing your menu, specifiy this identifier in AppendMenu/InsertMenu/etc. or in your resource file
In your window procedure, intercept the WM_COMMAND message. If LOWORD(wParam) corresponds to the identifier, this means that the menu item has been activated
A typical way of handling an exit command is to send a WM_CLOSE message, as you are already doing in your example code.
So you will avoid code duplication and be sure that the behavior will be the same regardless of how the user choose to exit your application (via menu, click on the "x", or Alt+F4)
In the handing of WM_CLOSE, you can choose to show a message box, destroy the window, post a quit message, or whatever else you want. BY default the DefWindowProc calls DestroyWindow, which in turn sends the WM_DESTROY message.
Note that WM_CLOSE is also triggered when selecting the "Close" item of the system menu (Alt+Space or click on the window icon on the left next to the window title)

WinAPI timer callback not called while child window is in focus

I'm working on a 3D editor app using Direct3D and WinAPI. I create a main window, which has a child window that takes up a portion of the main window's client area. This is used by D3D as the render target. I then also create a separate window with CreateWindow, which is built the same way as the main window (i.e a "main window" and an internal child used as a render target), and I make this window a child of the main application window (to ensure that they are minimized/restored/closed together).
The D3D rendering is executed by the render target child windows processing their WM_PAINT messages. To reduce unnecessary overhead, I set the window procedures to only render on WM_PAINT if GetForegroundWindow and GetFocus match the respective window handles. In other words, I only want a window's rendering to be refreshed if it's on top and is focused.
This is my main message loop:
HWND mainWnd;
HWND mainRenderWnd;
HWND childWnd;
HWND childRenderWnd;
// ...
MSG msg = {};
while (WM_QUIT != msg.message)
{
if (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE))
{
if (!TranslateAccelerator(mainWnd, accel, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
else
{
// Run non-UI code...
}
}
When the main window gets WM_SETFOCUS, I have it set the focus to its render target child window, since I'll want to process inputs there (e.g camera controls):
// ...
LRESULT CALLBACK MainWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch(uMsg)
{
//...
case WM_SETFOCUS:
{
SetFocus(mainRenderWnd);
return 0;
}
//...
}
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
I do the same in the window procedure for childWnd, setting the focus to childRenderWnd. This window is opened and closed by the user, i.e at any one time it may or may not exist, but when it does and is not minimized, it needs to be the foreground window with focus. Also, to control the framerate for the child window, I use a Timer to refresh it:
static constexpr UINT_PTR RENDER_TIMER_ID = (UINT_PTR)0x200;
void TimerCallback(HWND Arg1, UINT Arg2, UINT_PTR Arg3, DWORD Arg4)
{
if (IsIconic(childWnd) || !(GetFocus() == childRenderWnd))
return;
// Invalidate the render area to make sure it gets redrawn
InvalidateRect(childRenderWnd, nullptr, false);
}
// ...
SetTimer(childWnd, RENDER_TIMER_ID, 16, (TIMERPROC)TimerCallback);
With all this set up, mainWnd and mainRenderWnd seem to work just fine. However, childRenderWnd refuses to have anything rendered to it when it is in the foreground and in focus. While debugging, I found that while this is the case, the timer callback never gets executed, nor does a WM_TIMER message get dispatched to the child window.
On the other hand, the moment I deliberately move focus out of the child window and onto the main window (while keeping both open), the timer message gets sent, and the callback is executed. Another problem is that when I minimize the app while both windows are open, and then restore them both, the render target of neither of the windows is refreshed. Instead, it seems like the focus got "flipped", as I have to click on my child window first, then my main window, and that makes it refresh properly (while the child still refuses to render anything).
What am I missing? I searched for others having problem, e.g an incorrect message pump setup blocking WM_TIMER, but nothing seems to explain what's going on here.
Thanks in advance for the help!
IInspectable and Raymond Chen's comments have helped lead me to the answer. I tried to reproduce the error in a minimal app and finally came upon the source of my trouble. Originally, the main window would just call InvalidateRect in the message loop if there were no messages to be dispatched, effectively redrawing itself every chance it got. This originally did not seem to cause any harm, the scene was rendered just fine, and the window responded to inputs. Once I introduced a second window, however, it must have flooded the message loop with paint messages, making it impossible for any timer messages to get through.
The solution, quite simply, was to give a timer to both windows to set the rate at which they would refresh their D3D render targets. Coupled with focus checks, I can now easily alternate between both windows, with only one refreshing itself at any given time.
The question remains whether the WinAPI timer system is the best choice. My bad code aside, people have mentioned that the timer's messages are low-priority, which might make it a poor choice for framerate control in the long run.
EDIT: I ended up going with IInspectable's suggestion to use a while loop within the main message loop to process to dispatch all messages, and once those are processed, I perform a frame update. This allows me to consistently update all windows and control the frame rate without risking the issue of window messages being stuck.

How to set hook for mouse clicked on particular application only

I am creating mouse hook on mouse click event with below code:
mousehook = SetWindowsHookEx(WH_MOUSE_LL, MouseHookProc, NULL, 0);
It is able to call the MouseHookProc function on the mouse click.
But if I click on the other application or on the plain desktop screen still this MouseHookProc function gets called.
How can I restrict this hook event to my current application only?
First, I would think that if you're only looking for mouse events within your application, you could probably just use the main message pump instead of a hook.
However, using a low-level mouse hook, this would handle working in your app and not interfere when in another app
MSLLHOOKSTRUCT *hookStruct = (MSLLHOOKSTRUCT*)lParam;
// hMyMainAppHWND in the line below would already be defined
// and set when your program starts and gets its handle
if(GetAncestor(WindowFromPoint(hookStruct->pt),GA_ROOTOWNER) != hMyMainAppHWND){
// if the owner of the window where the mouse event occurred
// isn't your application's owning window, pass the event on
return CallNextHookEx(mousehook, nCode, wParam, lParam);
} else {
// The event occurred on your application
// Do your stuff here
// Don't forget to do one of the following:
// if you want to consume the event, making it as though it never happened:
// return TRUE;
// if you want the event to be processed as normal:
// return CallNextHookEx(mousehook, nCode, wParam, lParam);
}

Windows Messages Bizarreness

Probably just a gross oversight of some sort, but I'm not receiving any WM_SIZE messages in the message loop. However, I do receive them in the WndProc. I thought the windows loop gave messages out to WndProc?
LRESULT CALLBACK WndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam )
{
switch(message)
{
// this message is read when the window is closed
case WM_DESTROY:
{
// close the application entirely
PostQuitMessage(0);
return 0;
} break;
case WM_SIZE:
return 0;
break;
}
printf("wndproc - %i\n", message);
// Handle any messages the switch statement didn't
return DefWindowProc (hWnd, message, wParam, lParam);
}
... and now the message loop...
while(TRUE)
{
// Check to see if any messages are waiting in the queue
if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
// translate keystroke messages into the right format
TranslateMessage(&msg);
// send the message to the WindowProc function
DispatchMessage(&msg);
// check to see if it's time to quit
if(msg.message == WM_QUIT)
{
break;
}
if(msg.message == WM_SIZING)
{
printf("loop - resizing...\n");
}
}
else
{
//do other stuff
}
}
If a message is sent by the system to your window while it's in DefWindowProc or elsewhere in that netherworld that's the Windows message queue, then that message is not going to be seen by your message loop at all.
Note that this is only true for sent messages. Posted messages will show up in the message loop.
If you want to filter all messages, use SetWindowsHookEx with your thread ID, and the appropriate hook type. Or better yet, process them properly in your WndProc.
While you've got hold of the sizing gripper, I believe that Windows is running its own message loop. That will dispatch to your message queue, but your loop is out of the picture while the sizing is ongoing.
The frame window will call SetCapture to capture all subsequent mouse messages. Then it'll resize your window as the mouse moves. It'll also pump the message loop; you can see some similar code here: ftp://ftp.ringdale.com/support/Nlynx/Tech%20Support%20Docs/Midrange/EmeraldSeries/ADK/DDE/C/APITERM/TRACK.C. Note the message loop in the middle of that function.
It pumps the queue itself so that the sizing code doesn't have to return until after the resize tracking is complete.
Edit: I bring up the tracking rectangle code since that's how window resizing used to work, showing just a thin rectangular outline of the window, until we got dynamic window resizing where the entire window updates on the fly while you resize. The behavior internally is likely similar.
Edit 2: Still, credit to the guys who mentioned posted vs sent messages... sent messages won't ever go through the message pump. Sent messages quickly boil down to a function call of your wnd proc. Unless they're sent to windows owned by a different thread, which becomes a lot more complex; they get added to an internal queue belonging to the destination thread's message queue, and are processed internally - before posted messages are returned -inside GetMessage. Getting the sent message's return value back to the source thread involves more gyrations :)
WM_SIZING and WM_SIZE are not the same message. I think ordinary mouse operations to resize a window send WM_SIZING first, but if some program sends a WM_SIZE message then you're only going to get WM_SIZE without WM_SIZING.

PostMessage for cross application messages

I'm trying to send a keystroke to another application. I can successfully find the window handle since using SendMessage worked exactly as intended.
However, when I switched the SendMessage over to PostMessage, the application no longer received the messages.
I did, however, find a workaround by using HWND_BROADCAST as the window handle, and it works fine, but isn't the ideal way to go about it.
What I'm asking is, I have a valid hWnd, how can I send it messages using PostMessage and not SendMessage?
Edit
This is what I'm trying to do.
HWND Target = FindWindow(0, "Window Title Goes Here");
LPARAM lParam = (1 | (57<<16)); // OEM Code and Repeat for WM_KEYDOWN
WPARAM wParam = VK_SPACE;
PostMessage(HWND_BROADCAST, WM_KEYDOWN, wParam, lParam); // Works
PostMessage(Target, WM_KEYDOWN, wParam, lParam); // Doesn't Work
SendMessage(Target, WM_KEYDOWN, wParam, lParam); // Works, but I need Post
The PostMessage function does not work when the message numbers between 0 and WM_USER-1. Use RegisterWindowMessage function to register your own messages.
Sent messages and posted messages take completely different routeres. Target is recieving your posted message, it's just either filtering or dispatching it to another window. It gets to do what ever it wants with it. When you send the messages, it goes directly to the window procedure without filtering, so is most likely that cause of that issue.
I don't know why HWND_BROADCAST is working; my best guess is that a window other than Target is processing the message. Or maybe its even being sent to a different window than Target. (You do realize that HWND_BROADCAST sends the messages to every top level window)
There is a Win32 API function designed to send input, SendInput(), that places the messages on the input queue just like a user keypress. However this doesn't let you specify a window, it sends its input to the active window. To use it you would have to activate and switch focus to Target, which means the user would see that window move to the top (just like you Alt-Tabbed to it). Along that same route VBScript has a SendKeys() function that does the same thing, but is easier to use.
As a final alternative you could use SendMessageCallback() which will give you the behavior of an asynchronous SendMessage which is what I assume you want. (And is different than PostMessage. Posted messages go into the posted message queue, sent messages are delivered directly)
*For the lparam go here http://msdn.microsoft.com/en-us/library/ms646280%28v=vs.85%29.aspx, change the 32 bits (31...3 2 1 0) of lParam. Once you have the binary sentence you want for your paramaters (cRepeat, Scancode etc), convert it to hexadecimal.
try this :
void SendString(HWND h, char *text)
{
int len = strlen(text);
for(int i = 0; i < len; i++)
PostMessage(h, WM_CHAR, text[i], 0);
}
HWND Target = FindWindow(0, "Window Title Goes Here");
LPARAM lParam = //The hexadecimal value matching with the parameters you want* example 0x29A1.
WPARAM wParam = VK_SPACE;
PostMessage(HWND_BROADCAST, WM_KEYDOWN, wParam, lParam);
PostMessage(Target, WM_KEYDOWN, wParam, lParam);
SendString(Target, (char*)"themessageyouwant\n");