MFC 对话框只允许一个实例运行

来源:互联网 发布:linux 物理内存 编辑:程序博客网 时间:2024/05/17 00:57

参考网址:http://blog.sina.com.cn/s/blog_4b44e1c00100bh69.html

给CXXApp增加1个变量 HANDLE m_hMutex;

在CXXApp::InitInstance()中增加代码:

m_hMutex=CreateMutex(NULL,TRUE,_T("PowerTest"));


if(NULL==m_hMutex)
{
   return FALSE;
}


if(GetLastError()==ERROR_ALREADY_EXISTS)
{
   HWND hProgramWnd=::FindWindow(NULL,_T("PowerTest"));
   if(hProgramWnd)
   {
      WINDOWPLACEMENT* pWndpl=NULL;
      WINDOWPLACEMENT wpm;
      pWndpl=&wpm;
      GetWindowPlacement(hProgramWnd,&wpm);
      if(pWndpl)
      {
          //将运行的程序窗口还原成正常状态
          pWndpl->showCmd=SW_SHOWNORMAL;
          ::SetWindowPlacement(hProgramWnd,pWndpl);
          SetWindowPos(hProgram,HWND_NOTOPMOST,0,0,0,0,SWP_NOSIZE|SWP_NOMOVE);
      }  
   }
   CloseHandle(m_hMutex);
   m_hMutex=NULL;
   return FALSE;
}

添加ExitInstance虚函数 ,

CXXApp::ExitInstance

{

if(NULL!=m_hMutex)
CloseHandle(m_hMutex);
  m_hMutex=NULL;
return CWinApp::ExitInstance();

}


0 0