Findwindows
互斥量
Atom

解决方案 »

  1.   

    关于此问题的一个讨论:
    http://www.codeproject.com/cpp/avoidmultinstance.asp
      

  2.   

    给你这个:
    class CSingleInstance{public:    CSingleInstance();    ~CSingleInstance();    BOOL    Create(LPCSTR pszClass);    CString    GetClassName( void ) const;protected:    HANDLE    m_hMutex;    CString    m_strClassName;};CSingleInstance::CSingleInstance(){    // Set our default values    m_hMutex = NULL;}CSingleInstance::~CSingleInstance(){    if ( m_hMutex != NULL ) {        ReleaseMutex( m_hMutex );    }}BOOL CSingleInstance::Create(LPCSTR pszClassName){    // Add the word 'Class' to the end    m_strClassName = pszClassName;    // Create the mutex    m_hMutex = CreateMutex( NULL, FALSE, m_strClassName );    // Check for errors    if ( GetLastError() == ERROR_ALREADY_EXISTS ) {        // Reset our mutext handle (just in case)        m_hMutex = NULL;        // The mutex already exists, which means an instance is already        // running. Find the app and pop it up        HWND hWnd = FindWindowEx( NULL, NULL, m_strClassName, NULL );        if ( hWnd != NULL ) {            ShowWindow(hWnd,SW_SHOW);            ShowWindow( hWnd, SW_RESTORE );            BringWindowToTop( hWnd );            SetForegroundWindow( hWnd );        }        // Return failure        return FALSE;    }    // Return success    return TRUE;}CString CSingleInstance::GetClassName( void ) const{    return m_strClassName;}
    在Create中我使用了FindWindow来找出已经存在的窗口句柄,当然这不是必要的。你可以根据自己的需要去掉这写代码。使用说明:BOOL CXXXApp::InitInstance(....){//m_ss 为成员变量    if(!m_ss.Create("my class name"))       return FALSE;
    ........
    }
      

  3.   

    BOOL CPwdSpyApp::InitInstance()
    {
    bool bSuccess = false;
    try
    {
    // First get the handle to the mutex
    m_hMutex = CreateMutex(NULL, FALSE, szMutexName);
    if(m_hMutex != NULL)
    {
    // Test the state of the mutex
    // If the state is signaled, we successfully opened the mutex
    if(WaitForSingleObject(m_hMutex, 0) == WAIT_OBJECT_0)
    bSuccess = true;
    }
    }
    catch(...) {}
    }