WinAPI What happens if I don't Translate and Dispatch unhandled message - c++

On GetMessage reference from microsoft we have the next example:
BOOL bRet;
while( (bRet = GetMessage( &msg, hWnd, 0, 0 )) != 0)
{
if (bRet == -1)
{
// handle the error and possibly exit
}
else
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
What if I just ignore unhandled messages in the main loop of my program and move on?
Is there any risk to it? Will Windows complain/leak memory/hold resources for longer than necessary if I don't translate+dispatch this message if I don't actually need/want to handle it?

According The Message Loop,
The TranslateMessage function is related to keyboard input. It
translates keystrokes (key down, key up) into characters. You do not
really have to know how this function works; just remember to call it
before DispatchMessage. The link to the MSDN documentation will give
you more information, if you are curious.
The DispatchMessage function tells the operating system to call the
window procedure of the window that is the target of the message. In
other words, the operating system looks up the window handle in its
table of windows, finds the function pointer associated with the
window, and invokes the function.
If I don't translate+dispatch, loop will not be able to handle keyboard input and window messages. For example, the window cannot be moved, cannot be redrawn or closed. This has nothing to do with memory leaks
Having said that, a standard Message loop should be:
while (GetMessage(&msg, NULL, 0, 0))
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
Accelerators are what matters here, otherwise known as "short-cut keys". Your program wants to respond to them regardless of which window has the focus. Like F1 shows the program's help file, regardless which control has the focus. You don't want to have to write code that subclasses every control window to recognize F1.
Refer: why exactly TranslateMessage

Related

Terms and conditions of applicability of `AttachThreadInput`

This is a simple modification of a win32 initial code - generated from base template:
if (!InitInstance(hInstance,true)
{
return false;
}
std::thread{ [hInstance,main_thread= GetCurrentThreadId()] {
MSG msg{};
if (!InitInstance(hInstance,true)
{
return;
}
auto const current_thread{ GetCurrentThreadId() };
HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_WIN32APP));
if (!AttachThreadInput(main_thread, current_thread, true))
return;
// Main message loop:
while (GetMessage(&msg, nullptr, 0, 0))
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
AttachThreadInput(main_thread, current_thread, false);
} }.join();
Two windows are created and shown. But obviously, messages sent to the window created in main thread are not processed. What is missing? I couldn't find anything in tones of msdn docs and lots of forum posts. All I can find in forums is lots of complains about SetFocus and modal dialogs - which is not what I am looking for.
Thanks in Advance.
Ok. I had to go back and focus on the exact wording of the original dock. The term Input refers to HID. My confusion was due to the need for existence of message queues for both threads. So on the event of an input, different messages (pseudo) simultaneously get sent to both threads. Both threads will observe HID events; their perception of evets will be different, due different sequences recieved messages.
Thanks everyone for the hints.

Forcing a ListBox to Update

I am using C++ with MFC, and I have a ListBox tied to a variable that I'm updating as I run through a function:
void CFileSelection::OnBnClickedFiletousb()
{
m_LogC.AddString(_T("Starting move to USB, Please Wait..."));
UpdateData(FALSE);
// Code to move files from disk to USB
m_LogC.AddString(_T("Move to USB Successful."));
}
However, despite the UpdateData, the ListBox doesn't populate with either string until it has completed it's task. Is there a way to make it update the screen before the rest of the code is executed?
Use this function after changing the text on the listbox. Your issue is that the other calls are blocking the MessageThread, but you can force an update with this.
void ProcessWindowMessages()
{
MSG msg;
while (::PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) // let them see the message before we go into longer term wait
{
TranslateMessage(&msg); // translate it
DispatchMessage(&msg); // and let windows dispatch it to WinProc
}
}
Alternatively you can also call
yourlistboxVariable->UpdateWindow();

Creating Responsive Windows winapi c++

I am just learning to create a gui using the winapi, but i have run into an issue. I can create a window like this
#include "stdafx.h"
#include <windows.h>
int main()
{
HWND hwnd = CreateWindow(L"STATIC",NULL,WS_VISIBLE|WS_SYSMENU|WS_CAPTION,0,0,600,600,NULL,NULL,NULL,NULL);
UpdateWindow(hwnd);
MSG msg;
while(GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
_gettch();
}
But the windows will not close when the close button is clicked, and the window can not be dragged around or moved. I was wondering how i would enable these features of the window.
Static windows are not there for normal windows, you should try and look up how to register and handle your own class with RegisterWindowEx then use the same class name to create a window. You have to have your own window procedure in order to handle messages.
All window classes registered by the system run their own default window procudure and as far as I know none of them handle WM_CLOSE ( that is the close button ) this is why you can't close it.
For you main windows always use something like WS_OVERLAPPEDWINDOW so it'll be clear if it's okay or not and from that eliminate the flags you don't need.
How you set it up :
WNDCLASSEX wndcls;
HWND hMainWnd;
// Register your own window class
ZeroMemory(&wndcls,sizeof(WNDCLASSEX));
wndcls.cbSize=sizeof(WNDCLASSEX);
wndcls.style=CS_VREDRAW+CS_HREDRAW;
wndcls.lpfnWndProc=&appWndFunc;
wndcls.hInstance=hInstance;
wndcls.hIcon=hMainIcon; // or just LoadIcon(hInstance,MAKEINTRESOURCE(IDI_MAIN_ICON))
wndcls.hIconSm=hMainIcon;
wndcls.hCursor=LoadCursor((HINSTANCE)NULL,IDC_ARROW);
wndcls.hbrBackground=(HBRUSH)COLOR_APPWORKSPACE;
wndcls.lpszClassName="myWndClass";
if (RegisterClassEx(&wndcls)==0)
{
// failed to register class name
return false;
}
// Create window with your own class
hMainWnd=CreateWindowEx(0,\
"myWndClass","widnow title",\
WS_OVERLAPPEDWINDOW|WS_VISIBLE,\
0,\
0,\
250,\
250,\
hMainWnd,NULL,hInstance,NULL);
if (hMainWnd==(HWND)NULL)
{
// failed to create main window
return false;
}
Then your main loop :
bool bAppMainLoop=false
while(!bAppMainLoop)
{
WaitMessage();
while(PeekMessage(&emsg,NULL,0,0,PM_NOREMOVE))
{
if(GetMessage(&emsg,NULL,0,0)==0)
{
bAppMainLoop=true;
break;
}
TranslateMessage(&emsg);
DispatchMessage(&emsg);
}
}
This is a bit more than usual setup, so let me explain , in order to not burn CPU, you wait for a message with WaitMessage, it'll block until something happens, like move window, click, paint etc. PeekMessage will return true if there is a message so calling it in a while loop will make sure it drains the message quene, GetMessage will obtain the message if it returns 0 it means that your app called the PostQuitMessage(0) so a WM_QUIT arrived was found in the message loop that means it's time to break out from the message loop. The rest Translate and Dispatch does what it name says.
Finally you need your own window procedure :
LRESULT CALLBACK appWndFunc(HWND hWnd,UINT uMsg,WPARAM wParam,LPARAM lParam)
{
if (uMsg==WM_CLOSE)
{
PostQuitMessage(0);
return 0;
}
return DefWindowProc(hWnd,uMsg,wParam,lParam);
}
DefWindowProc is essential that handles all commonly occurring messages from the system, thus you don't need to handle those here. You simply respond to the WM_CLOSE message which is sent when you want to close the window and post a quit message into the message loop that you will catch and exit.
Additional info :
It's not required to release your stuff since windows does that for you so it wont be locked the next time you start your program , but it's a good practice to at least Unregister your window class after your main loop.
Btw that is the wrong main function : WinMain that is the correct one. Plus to avoid even more bugs make sure you compile a windows GUI application.

Win32 ReleaseDC and DestroyWindow returning 0

I have a single window created with the CS_OWNDC style for an engine I'm coding and it's showing properly, but when I'm closing the program and I call the ReleaseDC(hWnd, hDC) the function returns 0 always (and according to MSDN it means it couldn't be released).
The DestroyWindow(hWnd) is also returning 0.
I am calling GetDC(hWnd) during the window creation.
What is weird is that I only get this error if I pass through the messaging function, even if it has nothing coded inside.
My main code is looking like this:
WindowManager windowManager;
HWND mainWindow = windowManager.Initialize("Title", "ClassName", 1024, 768, 32, WindowProc);
MSG msg;
while(true)
{
if(PeekMessage(&msg, 0, 0, 0, PM_REMOVE))
{
if(msg.message == WM_QUIT) { break; }
else
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
}
windowManager.Clear(); //this calls ReleaseDC(hWnd, DC) and DestroyWindow(hWnd) among other release codes
What I don't understand is that if I comment the whole while loop, I don't get the release or destroy window errors.
Calling GetLastError() gives me a 0 too.
On MSDN it says the DestroyWindow must be called from the same thread, but I'm not coding any multi thread functions so I don't think that's the case.
What could be causing this?

Game loop in Win32 API

I'm creating game mario like in win32 GDI . I've implemented the new loop for game :
PeekMessage(&msg,NULL,0,0,PM_NOREMOVE);
while (msg.message!=WM_QUIT)
{
if (PeekMessage(&msg,NULL,0,0,PM_REMOVE)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else // No message to do
{
gGameMain->GameLoop();
}
}
But my game just running until I press Ctrl + Alt + Del ( mouse cursor is rolling ).
I've always been using something like that:
MSG msg;
while (running){
if (PeekMessage(&msg, hWnd, 0, 0, PM_REMOVE)){
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else
try{
onIdle();
}
catch(std::exception& e){
onError(e.what());
close();
}
}
onIdle is actual game lopp implementation, onError() is an error handler (takes error description as argument), and "running" is either a global bool variable or a class member. Setting "running" to false shuts down the game.
I think this really depends on your context. Windows will only send a WM_QUIT in response to your application calling PostQuitMessage. A common (if not great) solution here is to use a bool to exit the message loop when your program wants to end.
I guess the program may ask user for continue or exit, inside GameLoop function call. On exit Post WM_QUIT message to the window.
PostMessage(hWnd, WM_QUIT, 0, 0 );
hWnd-> The handle of the game window
else make a call to
DestroyWindow(hWnd);
This will send a WM_DESTROY to your window procedure. There you can call
PostQuitMessage(0);