creating window in child thread in vc++ - winapi

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.

Related

How global SetWindowsHookEx manages to inject dll into all threads?

I created 2 hooks in my host application. 1st is WH_MOUSE set specifically for Taskbar's thread. 2nd is global WH_KEYBOARD_LL hook (dwThreadId is set to 0).
As you can see in Process Explorer, the "local" hook actually injected my dll into specific explorer.exe thread. However, there is no indication that my 2nd global hook got injected into any other processes, yet it still works perfectly... Moreover, it also works for all the new processes I start, even after the hook was set! How SetWindowsHookEx manages that?
I read that it only applies to processes that load user32.dll. My weak suspicion is that in a case of global hook, Windows somehow injects my custom dll code into user32.dll "hook-chain". And then, when new process that loads user32.dll is started, it automatically loads my hook with it? Is this correct or is there some other mechanism at work?
_LL (low-level) hooks are not injected anywhere, win32k (the kernel part of the window manager) calls the hook callback function directly. This is why that thread needs a message loop. Low-level hooks are always "global".
MSDN says:
Be aware that the WH_MOUSE, WH_KEYBOARD, WH_JOURNAL*, WH_SHELL, and low-level hooks can be called on the thread that installed the hook rather than the thread processing the hook.
You should think of hooks as having 3 modes:
Low-level (keyboard and mouse only)
Thread specific
All threads
The last two might require Windows to inject the .dll.

MessageBox in worker thread

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.

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.

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.

Does Application.ApplicationExit event work to be notified of exit in non-Winforms apps?

Our code library needs to be notified when the application is exiting. So we have subscribed to the System.Window.Forms.Application.ApplicationExit event. This works nicely for Winforms apps, but does it also work for other types of applications such as console apps, services, and web apps (such as ASP.NET)? The namespace would suggest that it doesn't, and it presumably gets raised when Application.Exit() is called (explicitly or implictly), which may not be correct to call for these other cases.
Is there some other event which would be better in these other cases or which would be more universal (great if it works for Winforms, too)? For example, is there an event for when Environment.Exit() is called (console app)?
I found a mention of an Exited event in System.Diagnostic.Process, but this appears to be for monitoring the exit of another process, and it does not appear to be received by a process about itself (for example, Process.GetCurrentProcess().Exited += Process_Exited; Process.GetCurrentProcess().EnableRaisingEvents = true;). I would think it might only be raised after the process has actually exited, so that wouldn't work.
This is particularly for .NET 2.0 and C#.
We finally found more about this (but by then my machine had been rebuilt and lost the cookies to my unregistered profile here; hopefully, it will let met post this answer).
Further investigation eventually found a few more events which we have found helpful:
System.Windows.Forms.Application.ThreadExit - Fires when a message loop exits
System.Windows.Forms.Application.ApplicationExit - Fires when all message loops exit
System.AppDomain.CurrentDomain.DomainUnload - Fires when a domain other than the default exits
System.AppDomain.CurrentDomain.ProcessExit - Fires when the default app domain exits
System.AppDomain.CurrentDomain.UnhandledException - Fires when an uncaught exception occurs, ending the app.
Only one of the DomainUnload or ProcessExit events are possible for a given app domain, depending on whether it is the default (top-level) domain for the process or was created as a subdomain (eg. on a web server). If an application doesn't know which it might be (as in our case), it needs to subscribe to both if it wants to catch the actual unload for itself. Also, it appears that UnhandledException (which as of .NET2.0 is always fatal) may prevent the other two events, so that may be a third case to handle. These three events should work for any .NET application.
There is a caveat that the execution time for ProcessExit is bounded (about 4 seconds?), so it may not be possible to do extensive "final" work in that event handler. It needs to be something which can be done quickly.
The Application events only apply to WinForms applications (we suspect they may not apply in pure WPF applications, however). The naming can be misleading because they are named for their most basic normal usage which has certain assumptions. ThreadExit does not relate to the actual System.Threading.Thread but rather to the message loop (Application.Run())) of a UI thread, and ApplicationExit similarly relates to the collection of application Forms on one or more UI threads. Normally, once the call to Application.Run() returns, called from the entry method of a thread, the entry method quickly concludes and the thread itself then ends. And once all UI threads have exited, a WinForms app is usually all done and exits.
Another event of note is the System.Windows.Forms.Application.ThreadException event. A Windows message loop can be configured to catch exceptions which occur in handling a message and send this event rather than let them be uncaught (and thus fatal) exceptions. Catching these exceptions allows the message loop (and that UI thread) to continue running (after aborting the current message handler). There can be only one subscriber to this event at any time for a given thread (subscriptions overwrite any previous subscriber), and it must be configured before any Form is created and subscribed before entering the message loop. See the MSDN help for this event and System.Windows.Forms.Applicaton.SetUnhandledExceptionMode() for more info.

Resources