只容许程序运行1个实例

.

只容许程序运行1个实例

 

关键点

.

CreateMutex

The CreateMutex function creates or opens a named or unnamed mutex object.

HANDLE CreateMutex(

  LPSECURITY_ATTRIBUTES lpMutexAttributes,  // SD

  BOOL bInitialOwner,                      // initial owner

  LPCTSTR lpName                            // object name

);

 

实现过程

.

//CProject02Dlg::OnInitDialog()
//JustRunOnce(TRUE);
void CProject02Dlg::JustRunOnce(BOOL bValue)
{
    if (!bValue) return;
    CString AppTitle;
    AppTitle.Format("ABC");
    HANDLE m_hMutex = CreateMutex(NULL,TRUE,AppTitle);
    if( GetLastError() == ERROR_ALREADY_EXISTS )
    {
        MessageBox("程序已经运行...","提示",MB_ICONINFORMATION);
        exit(0); //让新开的程序不运行
    }
}

.

.

   

.

备注

.在MessageBox下面

//增加1个功能当这个程序已经运行时,就最前端激活原程序,并显示
//被最小化的程序 让其正常显示
 
//使窗口正常显示
ShowWindow(SW_RESTORE);
//当一个程序已经最小化时,此方法有效
void CMfc03Dlg::OnButton1()
{
// TODO: Add your control notification handler code here
HWND hWnd=::FindWindow(NULL,"mfc02");
::ShowWindow(hWnd,SW_RESTORE);
}
 

相关链接

相关链接    相关链接

 

.




附件列表

    原文地址:https://www.cnblogs.com/xe2011/p/3762065.html