+ Reply to Thread
Results 1 to 2 of 2

Thread: Single running instance of application in WIN32

  1. #1

    Single running instance of application in WIN32

    Hi All,

    I want to have single running instance for my application in WIN32.

    How can I achieve this?

    Thanks in advance.

  2. #2
    Hi,

    You can use "Named" Mutex object.

    Named Mutex can be used across process boundaries. Mutex has ownership which is used to implement this behavior.

    Following is the code:

    Code:
    class CSingleAppInstance
    {
    private:
    	HANDLE m_hMutex ;
    public:
    	
    	CSingleAppInstance()
    	{
    		m_hMutex = NULL ;
    	}
    
    	~CSingleAppInstance()
    	{
    		CloseHandle(m_hMutex) ;
    	}
    
    	bool IsSingleInstance(char *pszApplicationName)
    	{
    		bool bIsSingleInstance = true ;
    		
    		if (NULL != pszApplicationName)
    		{
    			m_hMutex = CreateMutex(NULL, TRUE, pszApplicationName) ;
    
    			if (NULL != m_hMutex)
    			{
    				DWORD dwLastError = GetLastError() ;
    
    				if (ERROR_ALREADY_EXISTS == dwLastError)
    				{
    					bIsSingleInstance = false ;
    				}
    			}
    		}
    
    		return bIsSingleInstance ;
    	}
    } ;
    
    //Your Application code:
    class Yourclass
    {
          CSingleAppInstance m_objSingleAppInstance ;
    } ;
    
    void Yourclass::DoSomething()
    {
         bool bIsSingleInstance = m_objSingleAppInstance.IsSingleInstance("MyApplication") ;
    
         //bIsSingleInstance should return false if you start second instance of your application.
    }
    Regards.

+ Reply to Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts