允许单一实例运行的方法

王朝vc·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

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);

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航