欢迎访问:常州市武进区嘉泽中心小学网站 !今天是:
栏目列表
您现在的位置是:首页>>教师>>计算机技术>>程序设计>>杂项>>文章内容
允许单一实例运行的方法
发布时间:2008-11-20   点击:   来源:本站原创   录入者:佚名
 
1.基于对话框运行的情况,即只允许单一对话框运行的情况.
使用互斥变量.
在CWinApp::InitInstance()的重载函数中,加入如下语句.
 HANDLE hMutex = ::CreateMutex( NULL, TRUE, m_pszAppName );
 if ( ::GetLastError() == ERROR_ALREADY_EXISTS )
  return FALSE;
如果已经有实例运行,则会返回 ERRO_ALREADY_EXISTS 值.
2.基于SDI, MDI的程序运行的情况!
   上述利用互斥量的方法仍然适用于只允许SDI/MDI的单一实例运行.
   但可以使用注册窗口方法来实际单一的SDI/MDI的实例运行!
   这个程序的单一实例运行比较困难,MFC4.0之前的版本是注册窗口方法与MFC4.0后的
版本是不同的,所以这个方法只能在MFC4.0后的版本运行.
首先要重载CWinApp::InitInstance()的方法.在这里会搜索已经运行的实例,并激活
这个实例!
// 首先标识一个全局BOOL变量,以便在退出实例时使用它.
static BOOL bClassRegistered = FALSE; BOOL COneSampleApp::InitInstance()
{
         // 检测是否已有实例运行,如果已运行,
         // 则激活已存在实例,否则注册这个实例的窗口类 if(!FirstInstance()) return FALSE;          WNDCLASS wndcls;
         memset(&wndcls, 0, sizeof(WNDCLASS));
         wndcls.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW;
         wndcls.lpfnWndProc = ::DefWindowProc;
         wndcls.hInstance = AfxGetInstanceHandle();
         wndcls.hIcon = LoadIcon(IDR_MAINFRAME); 
         wndcls.hCursor = LoadCursor( IDC_ARROW );
         wndcls.hbrBackground = (HBRUSH) (COLOR_WINDOW + 1);
         wndcls.lpszMenuName = NULL;          wndcls.lpszClassName = _T("MyNewClass"); if(!AfxRegisterClass(&wndcls)) { TRACE("Class Registration Failed\n"); return FALSE; } bClassRegistered = TRUE; // Rest of InitInstance goes here ... ... ...
}
FirstInstance()的方法如下.
 BOOL COneSampleApp::FirstInstance()
 {
 CWnd *pWndPrev, *pWndChild;
 
 // Determine if another window with your class name exists...
 
 if (pWndPrev = CWnd::FindWindow(_T("MyNewClass"),NULL))
 
 {
 
 // If so, does it have any popups?
 
 pWndChild = pWndPrev->GetLastActivePopup();
 
 // If iconic, restore the main window
 
 if (pWndPrev->IsIconic())
 
 pWndPrev->ShowWindow(SW_RESTORE);
 
 // Bring the main window or its popup to
 
 // the foreground
 
 pWndChild->SetForegroundWindow();
 // and you are done activating the previous one.
 
 return FALSE;
 
 }
 
 // First instance. Proceed as normal.
 
 else
 
 return TRUE;
 
 }
 
 
重载CWinApp::ExitInstance()的方法,如果是新注册的窗口类,则unregister()
 
 int COneSampleApp::ExitInstance()
 {
 if(bClassRegistered)
 ::UnregisterClass(_T("MyNewClass"),AfxGetInstanceHandle());
 return CWinApp::ExitInstance();
 }
跟着重载CFrameWnd::PreCreateWindow()方法,在这儿使用你自已注册时的窗口类,
 
从而避免使用MFC使用的窗口类,
 
 BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)
 {
 // Use the specific class name you established earlier.
 cs.lpszClass = _T("MyNewClass");
 // Change the following line to call.
 // CFrameWnd::PreCreateWindow(cs) 假如为SDI则使用这个,切记!!
 return CMDIFrameWnd::PreCreateWindow(cs);
 }

附件:
    关闭窗口
    打印文档
    账号登录
    保持登录 忘记密码?
    账号与武进教师培训平台同步