三、 程序代码
///////////////////////////////////////////////////////////////////////////// // 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变量的值来判断是否程序已经运行了。 
说明:本教程来源互联网或网友上传或出版商,仅为学习研究或媒体推广,wanshiok.com不保证资料的完整性。
2/2 首页 上一页 1 2 |