win32 / opengl and callback functions.. how are they structured? - windows

I'm working on a win32 c/cpp project involving openGL. I'm just starting and had a few basic questions regarding how a standard win32 program works. Following a tutorial, I made the winmain create a new window, enable openGL for the window, and then enter the main loop where if there are messages, the program handles them, and otherwise, the program moves onto drawing openGL animations. Following that, I simply shut down openGL and destroy the window. I'm not too confused about what's happening in here, but this is where I get lost:
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
switch (message)
{
case WM_CREATE:
return 0;
case WM_CLOSE:
PostQuitMessage( 0 );
return 0;
case WM_DESTROY:
return 0;
case WM_KEYDOWN:
switch ( wParam )
{
case VK_ESCAPE:
PostQuitMessage(0);
return 0;
}
return 0;
default:
return DefWindowProc( hWnd, message, wParam, lParam );
}
though I do see in the winmain that I register this function to my window class via
wc.lpfnWndProc = WndProc;
How exactly does this process work? Can someone explain the pipeline to me - as the winmain method runs, it goes onto drawing the opengl animation, but as soon as a key is pressed, it enters message handling... and then what? How does my winmain method communicate with the WndProc method? What's actually happening from the machine's point of view?

In your WinMain there should be a pair of TranslateMessage / DispatchMessage calls. TranslateMessage is responsible for getting keystrokes being delivered correctly and DispatchMessage traverses the window hierachy to deliver the messages to the window that has the input focus, effectively calling the function which pointer was registered as default window message handler (Window Procedure) with the message as parameters.

Related

Erasing Window Background

As far as I understand, Windows makes a division of labor with regards to the (re)painting of a given window; the division into background erasure and foreground painting. The WM_ERASEBKGNDmessage is sent to prepare an invalidated portion of a given window for painting, and usually this preparation consists of erasing the background so the actual painting can commence of a clean canvas. It seems to me this message is always sent when Windows invalidates part of a given window (and so is basically always sent in conjunction with a WM_PAINT message being posted). Whenever the application itself invalidates (part of) a given window, the last argument to the InvalidateRect function specifies whether a WM_ERASEBKGNDis to be sent or not. So I wrote a small program to test my assumptions, but its behavior eludes me a little. This is said program:
#ifndef UNICODE
#define UNICODE
#endif
#include <windows.h>
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hwInstance, PWSTR pCmdLine, int nCmdShow)
{
// Register the window class.
const wchar_t CLASS_NAME[] = L"Sample Window Class";
WNDCLASS wc = {0};
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = WindowProc;
wc.hInstance = hInstance;
wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
wc.lpszClassName = CLASS_NAME;
RegisterClass(&wc);
// Create the window.
HWND hwnd = CreateWindowEx(
0, // Optional window styles.
CLASS_NAME, // Window class
L"Learn to Program Windows", // Window text
WS_OVERLAPPEDWINDOW, // Window style
// Size and position
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
NULL, // Parent window
NULL, // Menu
hInstance, // Instance handle
NULL // Additional application data
);
if (hwnd == NULL)
{
return 0;
}
ShowWindow(hwnd, nCmdShow);
UpdateWindow(hwnd);
// Run the message loop.
MSG msg = {0};
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
static int eb_count = 0; // counts number of WM_ERASEBKGND messages
switch (uMsg)
{
case WM_DESTROY:
PostQuitMessage(0);
return 0;
case WM_PAINT:
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
RECT rect;
wchar_t text[40];
wsprintf(text, L"Number of WM_ERASEBKGND messages: %i\n", eb_count);
GetClientRect(hwnd, &rect);
DrawText(hdc, text, -1, &rect, DT_SINGLELINE | DT_CENTER | DT_VCENTER);
EndPaint(hwnd, &ps);
return 0;
case WM_RBUTTONDOWN: // repaint whenever RBUTTONDOWN
InvalidateRect(hwnd, NULL, FALSE);
UpdateWindow(hwnd);
return 0;
case WM_ERASEBKGND:
eb_count++;
return 0;
}
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
I am handling WM_ERASEBKGND in the window procedure (it is a case in my switch), so it should not be passed to the default window procedure. However, I don't do any actual background erasing (I simply increment a static variable) and I return 0 to indicate that no erasing actually took place. It seems to me that in this program, the background should never get erased. This does, however, happen in two distinct instances.
Whenever I maximize the window, the background of the invalid portion does get erased with the class background brush. But how is this possible? The window procedure certainly does no such thing upon receiving a WM_ERASEBKGND message.
A similar thing happens whenever DrawText repaints its string. I would expect that the incrementing numbers would get painted on top of eachother (leading to an illegible mess, of course). So it seems the 'DrawText' function also somehow erases the background of the rectangle in which it paints its string.
My last question pertains to my assumption that a WM_ERASEBKGND message is sent whenever Windows invalidates part of a window. I noticed that whenever the window is covered by another window and subsequently uncovered, no WM_ERASEBKGND message seems to be sent. Does this mean my assumption is wrong?
Sorry for the long read, but any and all help in answering these questions would be greatly appreciated.
... my assumption that a WM_ERASEBKGND message is sent whenever Windows invalidates part of a window. I noticed that whenever the window is covered by another window and subsequently uncovered, no WM_ERASEBKGND message seems to be sent ...
That's because, as of Vista and later, we have the Desktop Window Manager (DWM) lurking away in the, erm, background. This buffers the contents of all the on-screen windows so that Windows doesn't need to issue WM_ERASEBKGND or WM_PAINT requests when part of one is uncovered - it can just copy the so-called back-buffer back to the screen.
[Parts of] windows do still get invalidated - either by you or the OS - but not as often as they used to be back in the XP days. Try minimising and restoring a window for example - then it has to be redrawn. When you do that, the DWM probably throws away the back-buffer to save memory while the window is minimised.
Apart from that, what the others said in the comments.
As per the answer by #Paul Sanders most recently the Desktop Window Manager is a process that does, actually, cache the contents of windows so it can perform a blend effects when composing the desktop, which means that your Window does not always get repainted in the way it did in earlier editions of Windows.
Prior to that, the move from a co-operatively multitasked to a multithreaded OS (This painting model was in the Windows 3.0 API) introduced some race conditions that, iirc, Windows would try and cover up by doing a pre-emptive background-brush fill in some cases when some process changed the visibility of another processes window. This is what you see when you maximise the window.
Your call to DrawText is working, because DrawText - by default - does its own background erase - you need to call SetBkMode passing in the TRANSPARENT flag to render just the font.

winapi global hook WM_TIMER trace message sender

I'm trying to monitor a message sent by another window handle (particularly WM_TIMER) using WH_GETMESSAGE hook but it seems that I can only get the receiver handle, not the sender. Here's my code:
LRESULT WINAPI GetMsgProc(int nCode, WPARAM wParam, LPARAM lParam){
if (nCode < 0){
return CallNextHookEx(hGetMsgHook, nCode, wParam, lParam);
}
else{
MSG* msg = (MSG*)lParam;
HWND window = msg->hwnd;
unsigned int msgCode=LOWORD(msg->message);
char* className = new char[50];
if (msgCode == WM_TIMER){
GetClassNameA(window, className, 50);
//className of the receiver handle
}
}
return CallNextHookEx(hGetMsgHook, nCode, wParam, lParam);
}
How do I get the sender hwnd?
You are asking to find information that has no meaning. The WM_TIMER message is not sent from one window to another. It is a pseudo-message that is synthesised by the system.
Certain low priority messages are implemented this way. The other common example is WM_PAINT. Your program has a message loop that repeatedly calls GetMessage which pulls messages off the queue. When the queue of real messages is empty, pseudo-messages are generated if needed. At this point the system will synthesise WM_TIMER or WM_PAINT messages.
So, these messages are never actually sent. They are just synthesised on demand.
On top of that, messages are not sent by windows. Messages are sent by calls to SendMessage, PostMessage etc. These functions do not ask the caller to supply a window handle for the sender. And they can be called from anywhere and have no clear affinity with any sender window. So even for tradition true messages, the concept of sender window has no meaning.

Can I call TranslateMessage inside the message callback?

I don't have the canonical message loop running, so is there a way I can call TranslateMessage (or its equivalent) inside my message proc handler?
Basically I need WM_CHAR messages and unless I can call TranslateMessage I'm not going to get those. Currently I have the message proc setup, but no message loop.
// Static window function called by Windows for message processing. Implementation
// delegates message processing to MemberWndProc.
LRESULT CALLBACK FxPlayerTiny::WindowsMsgStatic(HWND hwnd, UINT iMsg, WPARAM wParam, LPARAM lParam)
{
msg = PeekMessage(&msg, HWnd, WM_KEYFIRST, WM_KEYLAST, PM_NOREMOVE);
if (msg type is key down){
TranslateMessage(&msg);
//DispatchMessage(&msg); -- needed?
}
else process msg normally
}
My message proc handler is the first point of entry of messages, being setup in the following manner:
WNDCLASSEX wc;
wc.lpfnWndProc = WindowsMsgStatic;
....
RegisterClassEx(&wc);
At some point, in order to get a queued message, you must call a function like GetMessage or PeekMessage. Those functions yield MSG objects and it is those MSG objects that you must pass to TranslateMessage and DispatchMessage.
In the code in the original version of the question, you are trying to call TranslateMessage and DispatchMessage too late. You call them inside your window proc. You should call them at the point where you first receive the MSG object. In other words, call TranslateMessage and DispatchMessage straight after the call to PeekMessage or GetMessage.

KeyPress with multiple modifiers not working in QWidget

I have added an override for my main widget's keyPressEvent:
void MainWindow::keyPressEvent(QKeyEvent* e)
{
if (e->key() == Qt::Key_F11)
{
if (e->modifiers() & Qt::AltModifier && e->modifiers() & Qt::ControlModifier)
{
// do stuff
}
}
}
The problem is that it does not work. If I try the AltModifier or ControlModifier alone it works (while changing the second condition of course), but not for both of them. The key() won't equal to Qt::Key_F11 while I do press F11. I'm using windows.
Edit: checked with logging and the result is that Ctrl+Alt+F11 and Ctrl+Alt+F12 do not send a key event (while other Ctrl+Alt+Fxx keys do).
Oook, so I managed to solve it though I'm not exactly pleased with the solution. At least there is no mystery and it works :).
The reason why I didn't receive the hotkeys Ctrl+Alt+F11 and Ctrl+Alt+F12
They were registered as global hotkeys. I managed to find this out using the ActiveHotkeys program of the fellow stackoverflow member moodforaday (thanks a lot for it!). Apparently there is no documented way to find out which program registered a particular hotkey (and it didn't do anything on my system). See moodforaday's thread about the issue.
The solution
One of the answers in the aforementioned thread led me to another question. Efotinis' answer was absolutely perfect for me. I did not have experience with setting up low-level keyboard hooks, but it was not nearly as difficult as it sounds. For future's sake, here is how I did it in my Qt application:
In my mainwindow.h:
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
// ... code
private:
void tryLogin();
friend LRESULT CALLBACK LowLevelKeyboardProc(int code, WPARAM wparam, LPARAM lparam);
};
LRESULT CALLBACK LowLevelKeyboardProc(int code, WPARAM wparam, LPARAM lparam);
In my mainwindow.cpp:
// setting up the hook in the constructor
SetWindowsHookEx(WH_KEYBOARD_LL,
LowLevelKeyboardProc,
NULL,
0);
The hook code (mostly from efotinis' answer):
LRESULT CALLBACK LowLevelKeyboardProc(int code, WPARAM wparam, LPARAM lparam)
{
KBDLLHOOKSTRUCT* kllhs = reinterpret_cast<KBDLLHOOKSTRUCT*>(lparam);
if (code == HC_ACTION)
{
if (wparam == WM_KEYDOWN && kllhs->vkCode == VK_F12 &&
(GetAsyncKeyState(VK_MENU) < 0 && GetAsyncKeyState(VK_CONTROL) < 0))
{
MainWindow* w = dynamic_cast<MainWindow*>(qApp->activeWindow());
if (NULL != w)
{
w->tryLogin(); // this should not be blocking!
return 1;
}
}
}
return CallNextHookEx(0, code, wparam, lparam);
}
As you can see, we get the pointer to the application window from the global QApplication object. We use dynamic_cast so in the active window happens to not be a MainWindow instance we would get a NULL pointer.
If you are wondering why the GetAsyncKeyState calls are checked for < 0, it's because this function returns with MSB set if the key is down. And when the MSB is set, the SHORT number is negative (on x86/x64 and compatible platforms). If windows ever gets ported to a platform where signed integers are represented differently, this code might break. The absolutely proper way would be to create a 16-bit mask and use that to check the MSB, but I'm lazy to do that. :)
One thing to note is that when you call a function from your hook, the Qt event loop has just begun processing. That means until you don't return from your function, it will block the UI (freezing it for a few seconds). If you wanted to show a dialog like I did, instead of exec(), call raise, activateWindow and show, while setting the window modality of the dialog to modal (in its constructor maybe).
You can unregister the hook with UnHookWindowsHookEx if you want to (which happens when the module containing the hook is unloaded). To do this, save the return value of the SetWindowsHookEx call.

Create a native Windows window in JNA and some GetWindowLong with GWL_WNDPROC

Good day,
I have been using JNA for a while to interact with the Windows API and now I am stuck when creating a window. As far as I have done the following:
1. Have created a child window of an existing window and obtained a valid handler to it.
2. Understood that every window in Windows has a non-stop message-dispatch loop.
3. Understood that the best way to include my window in the message-dispatch loop is to use something like the following code (not mine, but that is what I would do as well):
final LONG_PTR prevWndProc = new LONG_PTR(User32.INSTANCE.GetWindowLong(hwnd, User32.GWL_WNDPROC)); //this is to obtain a pointer to the WNDPROC of the parent window, which we are going to need later
wndProcCallbackListener = new WndProcCallbackListener()
{
public LRESULT callback(HWND hWnd, int uMsg, WPARAM uParam, LPARAM lParam)
{
if (uMsg == WTSAPI.WM_POWERBROADCAST)
{
System.out.println("WM_POWERBROADCAST Event: hWnd="+hwnd+", uMsg="+uMsg+", uParam="+uParam+", lParam="+lParam);
}
else if (uMsg == WTSAPI.WTS_SESSION_CHANGE)
{
System.out.println("WTS_SESSION_CHANGE Event: hWnd="+hwnd+", uMsg="+uMsg+", uParam="+uParam+", lParam="+lParam);
}
//Call the window's actual WndProc so the events get processed.
return User32.INSTANCE.CallWindowProc(prevWndProc, hWnd, uMsg, uParam, lParam);
}
};
//Set the WndProc function to use our callback listener instead of the window's one.
int result = User32.INSTANCE.SetWindowLong(hwnd, User32.GWL_WNDPROC, wndProcCallbackListener);
However, my problem is when I call the GetWindowLong() for the parent window (my first line of code) I get a 0 for the pointer which indicated the function did not complete successfully. A subsequent call to GetLastError() and a quick check in the error codes give me an 'Access is denied' error. This, of course, is logical, since I am trying from my own thread to access the address of the WNDPROC of another, but I was wondering if there is any way (there should be, of course) to circumvent that.
Any pointers? (pun intended)
Do not use GetLastError() after a JNA call. JNA & JNI may call other APIs that may change the last error. Declare SetWindowLong with the clause throws LastErrorException, like this:
int SetWindowLongA(int hWnd, int nIndex, WndProcCallbackListener dwNewLong)
throws LastErrorException;
Notice the 'A' after the name. It makes explicit use of ANSI version. You could use SetWindowLongW as well.
Make sure your callback implements both Callback and StdCall. I prefer using primitive types as much as possible, because this makes mapping fast and obvious to JNA:
public interface WndProcCallbackListener extends Callback, StdCall {
int callback(int hWnd, int Msg, int wParam, int lParam);
}

Resources