Reputation: 1990
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!
Upvotes: 0
Views: 1795
Reputation: 14084
EnumWindows
is useful when you don't know an exact window name (partial match).
I'm not sure what do you mean by 'a name from the taskmanager', but the second parameter of the FindWindow
function should match with your window's title.
An example using EnumWindows
:
BOOL CALLBACK WorkerProc(HWND hwnd, LPARAM lParam) {
static TCHAR buffer[50];
GetWindowText(hwnd, buffer, 50);
if(_tcsstr(buffer, "window name goes here")) {
// do something with hwnd here
return FALSE;
}
return TRUE;
}
And then call it like this:
EnumWindows(WorkerProc, NULL);
Upvotes: 1
Reputation: 46794
What you need is a Singleton Application. There are many examples of this around. A friend of mine wrote an article on another site many years ago. There is probably a better way to do it now, but here is his article
Upvotes: 1
Reputation: 29339
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++.
Upvotes: 1