I have a small Windows application which is allowed to run only once. The single instance check is done using a Windows mutex (CreateMutex).
The application should bring the already running application to the front and show an info message to the user.
The info message is created using the MessageBox function from Windows. However, each time I try to start a new instance of my application, a new messagebox is created (allowing me to open hundreds of messageboxes).
Is there a way to limit the number of message boxes to one (besides locking another mutex for the message box)?
There are three states of your program:
Normal (first instance),
Informing about second run (second instance, showing message box about it right now),
Extra (more than second instance, which knows about showed message box).
It seems reasanoble for the program in third state to quit silently. There are many ways to do it. And since you are already using mutex for detection of second state, is will be reasanoble to use the same logic for detection of third state too.
But you can do it another way:
Second instance of your program can inform first instance of the program about second run and quit.
And main (first) instance of the program will show the message box after receiving of this kind of message. In this case your program should ignore all such messages begore closing of current message box (to avoid showing of hungreds of such message boxes one by one).
From my point of view, first approach is better (i.e. to show message box by second/third/... instance of the program, and only after it to bring main instance to the front).
Related
I am making an RPG game with C++/x86 asm. My question is related to the C++ component. In C++/win32 how would I detect if the computer is shutting down or turning off, or whatever else - so that I can save the game session. My game has a 'save' option, but if the user or another program decides to shut off the computer how can I detect this with some kind of API hook so that I can instantly save the game session to the text file.
Now please don't suggest an option by creating a thread to run passively as I want to keep the file size to a minimum, so if you can suggest some sort of WM_ hook that would be great. I'd refer to MSDN but I don't want to be searching for hours through their WM directory.
You can handle session saving in response to the WM_ENDSESSION message. Note that after your message handler returns from handling this, your process may be terminated at any time, so you need to save it directly during the message handler, and not just set a flag to let some later code handle the saving, because that later code might not get to execute.
A comment suggests the WM_QUERYENDSESSION message. This has a slightly different meaning: it gives applications the chance to complain about the session ending, and gives the user a chance to not log off / shut down the system. Based on your question, you have no intention of preventing any such thing, so WM_ENDSESSION seems like a better match to me.
I’m writing a simple Windows console c++ application. If the application is started a second time (on the same computer) it should not span an new instance but pass command line arguments to the instance already running.
I have accomplished to ensure that the application only runs in one instance by using mutex but I am unable to notify the first application that it has been started as second time and pass on command line arguments.
Use case:
listener.exe -start // starts listener
listener.exe -stop // stops listener
If you just want to communicate a simple boolean value (start/stop, for example), then you probably need an Event object.
If you want to exchange more complex data between processes, you could use named pipes or perhaps blocks of shared memory.
The first listener should wait on an event object which is for shutdown. When you launch listener.exe -stop then it will just set the global event for shutdown and if first instance is running then it would exit. Named event object is required in order for the other processes to refer it. Also when you fire command 2nd time it will launch another process there is no implicit IPC with command interpreter.
listener.exe -start:
Create a named event (CreateEvent)
Wait on the event in the main thread or any suitable thread. (WaitForSingleObject)
On event initiate shutdown
listener.exe -stop
Get Handle to named event.
Set the event so that the thread of first process knows that shutdown event is fired and it exits
Some reference:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms686915(v=vs.85).aspx
There are many types of IPC. One technique that worked well for me on Windows was using a separate thread to process messages for a message only window. Once you determine you are the primary instance of the program, or listener(via mutex creation as in your scenario) create the message only window and start a thread to process messages. For secondary instances, if there is something on the command tail, pass it as a string to the message only window using WM_COPYDATA message. The listener program ignores all other messages except perhaps a token telling it to quit. Once the secondary instance passes the message to the message only window it exits.
This can work very well for a scenario where you may have dozens of secondary instances opening. One example would be the user selects 50 files in an Explorer folder, right clicks, and runs the program. The listener processes the message only window in a dedicated thread and queues up the strings(in this case filenames) for processing.
I have a message-only window (ATL::CWindowImpl) that registers itself for raw input using the RIDEV_INPUTSINK flag, meaning it gets all input regardless of whether the window is the foreground window. This works great when there's only one instance of that window.
However, when I create more than 1 instance of my window, only one receives the WM_INPUT messages (I'm currently creating two, and only the second one to be created gets the messages).
RegisterRawInputDevices (using RIDEV_INPUTSINK | RIDEV_NOLEGACY) is succeeding during the creation of both windows. Also, the window not receiving raw input is still receiving other messages, so it's not a problem with the window itself...
If it's relevant, I'm using the VC11 beta, and windows are created and dispatching messages on different threads (using std::thread).
Is this an API limitation (i.e. you are limited to one input sink per process)? Or is there a way to get this working?
Thanks in advance.
EDIT:
Right now my current workaround is to just have one window and for it to pass on the input messages to the other windows, however this is a mess, and won't work in the case I want it to work in (where I have my app loading plugins which may want raw input, I don't want them to have to register with my app unless I really have to do it that way...).
From MSDN (here and here) the whole API for Raw Input talks always about application and not about window... which means that an application registering for raw input will be trated by the OS as one entitiy... which you indirectly proved by registering a second receiving winow - the first one just stopped receiving because the OS delivers raw input to the application (represented by exactly onw window as the sink).
I made a MFC application which probably has two threads, one for receiving data from a socket using UDP protocol and one is the main thread of MFC app. While any data is received some objects, created in the main thread by new operator, would be notified to fetch the data through apply the observer design pattern. The problem is that sometimes after I clicked the close system button, the GUI of the app disappeared, but its process can still be found in the Task Manager. If I stop the data source (UDP client) this problem would never happen. Other important and maybe helpful information is listed below:
The Observer design pattern was implemented with STL container list. I have used the critical section protection in the Attach, Detach and Notify functions.
I deleted the observer objects before closing the UDP socket.
The data transfer rate may be a little faster than process data, because after closing the data source the data process is still working.
I can't figure out what lead my app can not exit completely. Please give me some clues.
This is usually caused by a thread you created and not exit it programmatically when you exit the appliation. There must be a while clause in your thread. The way to find where it is still running is:
use debug mode to start you application and click the exit button the top right corner to exit it.
Check from task manager and see if it is still running
if it is, excute Debug->Break All,
Open threads windows, double click each thread, you will find where your code is still looping.
Typically a process won't terminate because there's still a foreground thread running somewhere. You must ensure that your socket library isn't running any thread when you want to close your application.
First thing, with MFC, please use the notification based methods to get notifications on message arrivals, connections etc. So you can get rid of threads if you have.
It's quite easy to attache to a debugger and Break see which threads are existing and waiting for what.
Alternatively you can use ProcessExplorer with proper symbol configuration to see the call stacks of the threads available for the particular process.
The application can two kind of issues to exit, one could be infinite loop and other might be waiting/deadlock (e.g. socket read command is a blocking call). You can easily deduce the problem by attaching to debugger.
Otherwise please provide further information about the threads, code snippet possible.
I am developing a simple WinAPI application and started from writing my own assertion system.
I have a macro defined like ASSERT(X) which would make pretty the same thing as assert(X) does, but with more information, more options and etc.
At some moment (when that assertion system was already running and working) I realized there is a problem.
Suppose I wrote a code that does some action using a timer and (just a simple example) this action is done while handling WM_TIMER message. And now, the situation changes the way that this code starts throwing an assert. This assert message would be shown every TIMER_RESOLUTION milliseconds and would simply flood the screen.
Options for solving this situation could be:
1) Totally pause application running (probably also, suspend all threads) when the assertion messagebox is shown and continue running after it is closed
2) Make a static counter for the shown asserts and don't show asserts when one of them is already showing (but this doesn't pause application)
3) Group similiar asserts and show only one for each assert type (but this also doesn't pause application)
4) Modify the application code (for example, Get / Translate / Dispatch message loop) so that it suspends itself when there are any asserts. This is good, but not universal and looks like a hack.
To my mind, option number 1 is the best. But I don't know any way how this can be achieved. What I'm seeking for is a way to pause the runtime (something similiar to Pause button in the debugger). Does somebody know how to achieve this?
Also, if somebody knows an efficient way to handle this problem - I would appreciate your help. Thank you.
It is important to understand how Windows UI programs work, to answer this question.
At the core of the Windows UI programming model is of course "the message" queue". Messages arrive in message queues and are retrieved using message pumps. A message pump is not special. It's merely a loop that retrieves one message at a time, blocking the thread if none are available.
Now why are you getting all these dialogs? Dialog boxes, including MessageBox also have a message pump. As such, they will retrieve messages from the message queue (It doesn't matter much who is pumping messages, in the Windows model). This allows paints, mouse movement and keyboard input to work. It will also trigger additional timers and therefore dialog boxes.
So, the canonical Windows approach is to handle each message whenever it arrives. They are a fact of life and you deal with them.
In your situation, I would consider a slight variation. You really want to save the state of your stack at the point where the assert happened. That's a particularity of asserts that deserves to be respected. Therefore, spin off a thread for your dialog, and create it without a parent HWND. This gives the dialog an isolated message queue, independent of the original window. Since there's also a new thread for it, you can suspend the original thread, the one where WM_TIMER arrives.
Don't show a prompt - either log to a file/debug output, or just forcibly break the debugger (usually platform specific, eg. Microsoft's __debugbreak()). You have to do something more passive than show a dialog if there are threads involved which could fire lots of failures.
Create a worker thread for your debugging code. When an assert happens, send a message to the worker thread. The worker thread would call SuspendThread on each thread in the process (except itself) to stop it, and then display a message box.
To get the threads in a process - create a dll and monitor the DllMain for Thread Attach (and Detach) - each call will be done in the context of a thread being created (or destroyed) so you can get the current thread id and create a handle to use with SuspendThread.
Or, the toolhelp debug api will help you find out the threads to pause.
The reason I prefer this approach is, I don't like asserts that cause side effects. Too often Ive had asserts fire from asynchronous socket processing - or window message - processing code - then the assert Message box is created on that thread which either causes the state of the thread to be corrupted by a totally unexpected re-entrancy point - MessageBox also discards any messages sent to the thread, so it messes up any worker threads using thread message queues to queue jobs.
My own ASSERT implementation calls DebugBreak() or as alternative INT 3 (__asm int 3 in MS VC++). An ASSERT should break on the debugger.
Use the MessageBox function. This will block until the user clicks "ok". After this is done, you could choose to discard extra assertion failure messages or still display them as your choice.