MFC一个程序同一时间只执行一个

我们在编写程序的时候,有的时候要保证同一个应用程序同一时间只能运行一个。这里我们可以通过互斥来实现。现在我就以MFC下基于Dialog的项目为例。

我们可以在App类的InitInstance()函数中的主对话框的DoModule()操作前插入如下代码:

 HANDLE hMutex;
 HWND hWnd;
 hMutex=CreateMutex(NULL,TRUE,"OneApp");
 if(GetLastError()==ERROR_ALREADY_EXISTS)
 {
  if(hWnd=FindWindow(NULL,"HELLO"))
  {
   // Bring it to the top of Z order and active it.
   BringWindowToTop (hWnd);
   // Bring key input into this window.
   SetForegroundWindow (hWnd);
   // Display as normal window
   ShowWindow (hWnd, SW_SHOW);
  }
  return FALSE;
 }

这样就可以保证当前只有一个名为OneApp的应用程序在执行。

作者:Aillo,转载本文时,必须以超链接的形式标明文章的原始出处!
网址:
 | 0 Comments | EDIT
相关日志

Advertisements

  • 史蒂夫•乔布斯传(精装珍藏版,附印作者签章)
  • 黑客:计算机革命的英雄
  • HTML5揭秘
  • 卓越购书,满一百返20。
  • 留言