I have a application which uses socket connection to send and receive data from another application. While creating socket it uses the port 4998 .
That is where my problem lie. Once I start my application the socket starts using port 4998. So if I want to execute the application again then I get socket binding error.
So I want to limit my application instance to one. That means if the application is already running and some one tries to run the application again by clicking the exe or shortcut icon it shouldn't run the program, instead it should bring the existing application to the Top.
When your application initializes, create a mutex. If it already exists, find the existing application and bring it to the foreground. If the application has a fixed title for its main window, it is easy to find with
FindWindow
./* I have found the necessary editing to be done. Added some extra code and edits that are needed. The present one is working perfectly for me. Thank you, Kirill V. Lyadvinsky and Remy Lebeau for the help!!
*/
/* The above code works even when one tries to open up second instance FROM A DIFFERENT LOGIN LEAVING THE FIRST LOGIN OPEN with ITS INSTANCE RUNNING. */
Don't you already have a way to check if your application is running? Who needs a Mutex, if the port is already taken, you know that the app is running!
Create named event on the start and check the result. Close application if the event is already exist.
Close
m_hStartEvent
on the app exit.You may used named mutex.
Code sample from the article: