The better mousetrap with a built-in trap

C

Chris Botha

If one wants to assure that there is only one instance of an app running,
then the popular solution is to use a Mutex and a message box, telling the
user there is already one running. I decided to go one further, bring the
1st instance to the foreground, no message boxes. Impressive, I thought. So
the first instance stores the main window handle in shared memory (win32
calls), second instance gets the window handle from shared memory if it
exists, and do a win32 "SetForegroundWindow" call. It works great if the
window is not minimized. Next step, when minimized, do a win32 "ShowWindow"
call. Also works great, BUT this is the trap in my mousetrap. If the main
form opened a dialog (ShowDialog), and the user minimizes the dialog, then
of course the main form minimizes too. Now start the second instance, it
finds the handle in shared memory and does a "ShowWindow" call, showing the
main window beautifully, however, the modal dialog stays minimized.
Naturally, the main form is dead, and the user has to click the dialog's
icon in the task bar to bring it up.
I don't really expect a solution, I thought I'd share my experience, and
revert back to the mutex and the message box.
 
C

Chris Botha

Bob, there is a subtle bug in your single instance app code. The 2 lines
minimizing and restoring the form, use
ShowWindowAsync(RunningProcesses(0).MainWindowHandle ...
Nine out of ten times it work, but then every now and then the original
instance occurs in
RunningProcesses(1) and not RunningProcesses(0), and testing for a null
handle and if so, use the second process in the array, fixes it.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top