Search code examples
mfcshellexecute

Launching external exe in MFC, how can I bring exe to front if already opened?


I have to open up a external program in my MFC application, which works but if I have already clicked button, I don't want it to open another instance but just bring it to front. The docs say the SW_SHOWNORMAL parameter does this, but it is not working for me. Does the called program have to setup for this also?

ShellExecute(NULL, "open", "C:\Test\blahblah.exe", NULL, NULL, SW_SHOWNORMAL);

Thanks, CP


Solution

  • The documentation is a bit unclear, which might have been what confused you. When targetting an executable program, ShellExecute() will always launch a new process. What the documentation is referring to when it mentions restoring a minimized window is if you are targetting a document (like a Word doc), and the application registered to display the document is already running.

    Your best bet is to either:

    • Modify the external program to support the Singleton pattern, and to bring itself front and center if you try to launch a second copy, or
    • Use FindWindow() in your MFC application to try to locate the external application, and then only run ShellExecute() if it doesn't already exist, otherwise activating the existing window.