龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > 软件开发 > VC开发 >

用VC++实现控制程序运行唯一实例(2)

时间:2009-12-30 15:42来源:未知 作者:admin 点击:
分享到:
二、 编程步骤 1、 启动Visual C++6.0,生成一个基于对话框的应用程序,程序命名为"Instance"; 2、 修改程序的InitInstance()函数; 3、 添加代码,编译运行程

  二、 编程步骤

  1、 启动Visual C++6.0,生成一个基于对话框的应用程序,程序命名为"Instance";

  2、 修改程序的InitInstance()函数;

  3、 添加代码,编译运行程序;

  三、 程序代码

/////////////////////////////////////////////////////////////////////////////
// CInstanceApp initialization
BOOL CInstanceApp::InitInstance()
{
 if (!FirstInstance())
  return FALSE;
 AfxEnableControlContainer();
 #ifdef _AFXDLL
  Enable3dControls(); // Call this when using MFC in a shared DLL
 #else
  Enable3dControlsStatic(); // Call this when linking to MFC statically
 #endif
 CInstanceDlg dlg;
 m_pMainWnd = &dlg;
 int nResponse = dlg.DoModal();
 if (nResponse == IDOK)
 {
  // TODO: Place code here to handle when the dialog is
  // dismissed with OK
 }
 else if (nResponse == IDCANCEL)
 {
  // TODO: Place code here to handle when the dialog is
  // dismissed with Cancel
 }
 // Since the dialog has been closed, return FALSE so that we exit the
 // application, rather than start the application's message pump.
 return FALSE;
}

BOOL CInstanceApp::FirstInstance()
{
 CWnd *pWndPrev, *pWndChild;

 // Determine if another window with our class name and Window title exists...
 // The title "Instance " is set up latter, in the InitDialog function.
 if (pWndPrev = CWnd::FindWindow(NULL,"Instance "))
 {
  pWndChild = pWndPrev->GetLastActivePopup();
  // if so, does it have any popups?
  if (pWndPrev->IsIconic())
   pWndPrev->ShowWindow(SW_RESTORE);
   // If iconic, restore the main window
   pWndChild->SetForegroundWindow();
   // Bring the window to the foreground
  return FALSE;
 }
 else
  return TRUE; // First instance. Proceed as normal.
}

  四、 小结

  上述方法虽然实现起来很简单,但是它对于无窗口的应用程序却无能为力。为了解决这个问题,可以通过动态连接库DLL实现更通用的控制程序运行的方法。在DLL中使用#pragma data_seg指令实现共享数据段,在该数据段中定义一个变量long m_nRun,并设置其初始值为-1,同时还要在DLL的入口点函数DllMain返回成功值的语句前添加语句m_nRun++,意思是在应用程序启动连接DLL成功时对已经运行的实例进行计数,然后在DLL中导出一个函数来返回该变量的值。最后将应用程序的工程设置为依赖于该DLL的工程,在应用程序根据DLL中的m_nRun变量的值来判断是否程序已经运行了。

精彩图集

赞助商链接