C++ – Switch Focus between Cmd windows, Force focus (keep 1 instant of program running)

ccmdmutexwinapi

i am creating a simple windows cmd program, and i am trying to make sure it only runs once (if u double click the exe file, only one instance will show..
so in my code.. i added a named mutex(the name is a GUID) .. if a 2nd instance of the program was started, it would show the message telling you, that you already got an instance running..

what i want to do is to upgrade the code. so instead of showing you a message, it would automatically, find the already running process (window) , switch focus to it, and then close itself.

now i am trying to use

 FindWindow(NULL,window_name);
 SetForegroundWindow(window);

however, when i pass the window name (from the task manager) it doesn't find it !!!
Error says : Unused :S
which is weird,
i even tried to use the task manager name instead ..and it still couldnt find it!

so can some1 point out to me,where did i go wrong ? 🙂
also, if you can think of any other ways of doing such a task , please tell me..

note: some friend at work told me to use enumwindows, is it a good choice (i am currently reading about it )…
thx alot!

Best Answer

Here is an excellent article http://delphi.about.com/od/windowsshellapi/l/aa100703c.htm on this subject.

Controling the number of application instances

by Zarko Gajic - About.com Guide to Delphi Programming

In this article you'll learn how to "run-once enable" a Delphi application that can check for its previous (running) instance. Along the process, several techniques of implementing such a check will be discussed; as well as how to bring your already running application to the foreground, if a user tries to run it "one more time". By the end of the article you'll have a copy-to-go code to control the behavior of your application's multiple instances: with the option to limit the number of running instances.

The solutions presented are programmed in Delphi, but the code is pretty understandable and should be easily translated to C++.

Related Topic