Alex Rivera | Logout

How to Run Only One Instance of Application

Asked 2010-11-16T05:32:39.190
15

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.

Edit
Report

1 Answer

10

/* 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!!

*/

bool CheckOneInstance()
{

    HANDLE  m_hStartEvent = CreateEventW( NULL, FALSE, FALSE, L"Global\\CSAPP" );

    if(m_hStartEvent == NULL)
    {
    CloseHandle( m_hStartEvent ); 
        return false;
    }


    if ( GetLastError() == ERROR_ALREADY_EXISTS ) {

        CloseHandle( m_hStartEvent ); 
        m_hStartEvent = NULL;
        // already exist
        // send message from here to existing copy of the application
        return false;
    }
    // the only instance, start in a usual way
    return true;
}

/* 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. */

answered 2013-06-07T19:41:17.287

Your Answer