MessageBox in worker thread - winapi

I have an application which calls into plugin DLLs. Some of those calls are done from a worker thread (i.e. not the UI thread), and just might popup a dialog with MessageBox. According to this (http://www.codeproject.com/Articles/121226/MessageBoxes-and-worker-threads) the effective UI thread is switched to the thread calling MessageBox. This "crashes" the application since the message pump stops receiving messages. Any way to switch back the UI thread to the correct one ? Any work-around ?

The culprit was AttachThreadInput, see this message.

Related

Design pattern for cancelling or ignoring obsolete task on a worker thread

I apologize if there's an obvious answer to this, but I just haven't located it yet.
I'm creating an application that loads some information from a database when the user navigates into an Explorer directory. I'm doing this on a background worker thread (using ATL's CWorkerThread), and calling SetEvent when the navigation occurs. When the background thread is done loading the data, it posts a custom message to a message-only window back on the UI thread. Then the UI thread can do stuff with the loaded info if it wants.
Of course, if the user navigates into a directory, and the worker-thread starts working, but the user quickly navigates away, the current worker-thread task is no longer necessary. So the task should be either cancelled if in progress, or if the worker thread has already posted its completion message to the UI thread, the UI thread should be prepared to check it and ignore it, since it's now stale.
My question is whether there is a nice design pattern and helpful example for this type of situation. I think I've seen situations in which a looping worker thread checks a boolean (like fCancelled) to see if it should still continue doing something. But how about when the completion message is already posted? Is there any standard way in which the worker thread and UI thread can communicate that the message is stale and should be disregarded?
Thank you very much for any input.

Sleep(suspend) and Resuming windows form starts program on worker thread instead of main thread

The windows form I am working on subscribes to Microsoft.Win32.SystemEvents.PowerModeChanged and on Suspend it runs the Close() method on the form. On Resume it runs the Run() function like it would on initial load. The problem is that when the computer is woken from sleep mode the PowerModeChanged event is triggered on a worker thread named ".Net SystemEvents" and when Run() is called it recreates the form on this worker thread instead of the main thread.
This form is a project I inherited from another developer and I am new to windows form programming. I am wondering if there is a better way to handle the sleep/wake process rather than closing the forms and recreating them on wake or a way to force the creation onto the main thread. Note: If I remove the code and have it do nothing when the computer is slept (suspended) and nothing when it wakes (resumes) then the program continues to work correctly (running on the main thread). Any help will be appreciated. Thanks all.
Capture the UI thread SynchronizationContext in a static field, and Post() on it to go back to the UI thread.

creating window in child thread in vc++

I want to create a window and show some image display (like animation based on SetTimer()) on window created using CreateWindow() function. But it should be created on separate thread and should remain alive until user closes this. I tried but was unsuccessful.
EDITED
I just googled I found this link How To Create Windows in a Multithreaded Application but one thing i want to know when Window Procedure get invoked. if it is invoked by system then how i can call it from my child thread.
Windows (represented by HWNDs) in Windows have a thread affinity. Their WindowProc is always invoked in the context of the thread they are created with.
As such, they are a convenient way to serialize calls between threads as the PostMessage and SendMessage APIs can be called from any thread in the application, but the WindowProc will get executed in the context of the original creating thread.
Because WM_TIMER messages posted to message queues are the mechanism by which SetTimer works, again you need to be careful when calling SetTimer in a multithreaded app - The timer messages will be processed by the calling thread (if the hwnd parameter is NULL) or the window's thread.
You also, as a result, have to be careful to put a message loop on every thread that might create windows, or want to process timers.
Keep your user-interface on the main Windows thread. Setting a timer using the Windows API doesn't require an additional thread (as your WndProc will get the timer message WM_TIMER).
Even if you have a long running task to perform that might necessitate the use of an additional thread, keep the window on the main thread, do your work in the worker-thread and post back to the main thread with updates.

How can my app find the sender of a windows message?

I have an app which uses a keyboard hook procedure in a library. The wParam in the hook for one message is 255 which we think is "(reserved / OEMClear)". I'd like to work out the source of this message as it causes my application to crash in the library, and given it shouldn't be happening it would be good to identify it. The message comes in repeatedly on only one PC we have - other computers don't see the message at all.
So, is there a way to trace the source of a message sent to a window please, or all those on the system?
There is no built-in way to find out who sent the window message, not even win32k keeps track of this; you might be able to find it out with a kernel debugger and a conditional breakpoint.
However, I would argue that you don't really need this information; you need to make your app properly handle any message sent to it.
I came up with a technique for determining who is sending a win32 window message across threads/processes during one-off debugging/troubleshooting sessions. It requires making a couple of assumptions so it's not 100% reliable, but so far I haven't found a case where it didn't work.
The basic idea is to exploit the fact that, when the message arrives, the recipient window thread is typically blocked waiting in its message loop (specifically, GetMessage()). When the message is delivered, the sending thread readies the receiving thread, pulling it out of its wait state.
It turns out that Windows provides ways to precisely trace which threads are readying which other threads, using Event Tracing for Windows. Using this feature, it is often possible to determine which thread sent the message - it's the thread that readied the receiving thread. It's even possible to see what the call stack of the sending thread was at the time it sent the message, and even the kernel side (win32k) part of the stack!
The basic procedure goes like this:
Use the Windows Performance Recorder to start a trace. Make sure to include the "CPU usage" profile.
Trigger the sending of the message you are interested in.
Stop the trace.
Open the trace in the Windows performance Analyzer.
In the "CPU Usage (Precise)" graph, "Stacks" graph preset, zoom in on the time the message was received.
One way is to locate the receiving thread and determine when it woke up.
If correlation is difficult, it might be worth instrumenting the receiving thread using e.g. TraceLogging to produce a clear reference time point.
You should be able to find a context switch event where the receiving thread is readied in GetMessage.
The "Readying Process", "Readying Thread Id" and "Readying Thread Stack" columns will then show the details of the readying thread, which is likely to be the sender of the message.
For example, in the below screenshot, TID 7640 receives a shell hook message originating from WindowsTerminal.exe, TID 1104:
(I originally suggested using Spy++ or winspector, but they do not hook into the sending of messages. That doesn't even make sense! A window receives messages but they don't send them, a thread does that. I'll leave my suggestion about using a debugger.)
Sometimes debugging can help. Try downloading the windows PDB files and setting a breakpoint that hits only when one of these messages occur. Looking at the call stack at that point can often shed some light on why things are happening. Posted messages and messages send from other processes will foil this approach.
Im not sure if this does what you want it to but have a look at Process Monitor by sysinternals.
http:// technet.microsoft.com/en-us/sysinternals/bb896645.aspx
It shows everything that happens to a process so i assume it catches messages as well. The site was down at time of writing so i couldnt check.

How would I handle a close request for in a non-windowed application?

I'm working on a C++ Windows application, that runs as a process but not a windowed application (does not have WndProc). It has it's own message loop, which is used to process a quit message, and that's how we safely exit the application from within it's self.
What I want to do is somehow send a message to the process from another process, in order to tell the process to exit safely.
In Linux, we would do this by trapping signals, but I'm not sure how it's done on Windows.
PostThreadMessage can post messages to threads without requiring a window proc.
In the first process, do a GetCurrentThreadId to get a system wide id for the current thread. And somehow get that id to the second app.
In the second app, OpenThread will convert to a thread handle, that you can then use with PostThreadMessage.
Do note that if your 'windowprocless' application ever pops up a message box, the message box enters its own modal message loop, which will silently destroy any thread messages. If any kind of window is ever created on the thread you would be far better off creating an invisible message window that messages can be sent to to control the app.
Do you have the control over both processes i.e., do you have the code of both processes? If yes I suggest to expose a API to exit safely.

Resources