这里只是简单的建立一个MFC 程序来演示 只运行一个实例。
// 在头文件中添加类似如下代码
#define SCANSETTINGS_CLASSNAME _T("ScanSettingsWindowClass")
#define APPMUTEX _T("Global\\ScanSettings")
virtual int ExitInstance();
private:
HANDLE m_hMutex;
// Implementation
BOOL RestrictOneInstance();
// 在源文件中添加如下代码
BOOL CXXXApp::InitInstance()
{
// Begin. 把这段代码加在最前面即可
if (!RestrictOneInstance())
{
return FALSE;
}
WNDCLASS wc;
::GetClassInfo(AfxGetInstanceHandle(), _T("#32770"), &wc);
wc.lpszClassName = SCANSETTINGS_CLASSNAME;
AfxRegisterClass(&wc);
// End
//...........................
}
BOOL CXXXApp::RestrictOneInstance()
{
SECURITY_DESCRIPTOR secutityDese;
::InitializeSecurityDescriptor(&secutityDese, SECURITY_DESCRIPTOR_REVISION);
::SetSecurityDescriptorDacl(&secutityDese, TRUE, NULL, FALSE);
SECURITY_ATTRIBUTES securityAttr;
securityAttr.nLength = sizeof SECURITY_ATTRIBUTES;
securityAttr.bInheritHandle = FALSE;
securityAttr.lpSecurityDescriptor = &secutityDese;
m_hMutex = ::CreateMutex(&securityAttr, FALSE, APPMUTEX);
BOOL bLaunched = (m_hMutex != NULL && ERROR_ALREADY_EXISTS == GetLastError());
CWnd *pWndPrev = NULL;
CWnd *pWndChild = NULL;
if (pWndPrev == NULL)
{
pWndPrev = CWnd::FindWindow(SCANSETTINGS_CLASSNAME, NULL);
}
if (pWndPrev != 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();
return FALSE;
}
return TRUE;
}
int CXXXApp::ExitInstance()
{
// TODO: Add your specialized code here and/or call the base class
if (m_hMutex != NULL)
{
CloseHandle(m_hMutex);
m_hMutex = NULL;
}
return CWinApp::ExitInstance();
}
//在资源脚本中也应修改
IDD_XXX_DIALOG DIALOGEX 0, 0, 331, 151
STYLE DS_SETFONT | DS_FIXEDSYS | WS_POPUP | WS_VISIBLE | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME
EXSTYLE WS_EX_APPWINDOW
CAPTION "XXXXXXXXXX"
CLASS "ScanSettingsWindowClass" //添加这句
FONT 8, "MS Shell Dlg", 0, 0, 0x1
BEGIN
LTEXT "",IDC_STATIC1,0,0,330,129,0,WS_EX_TRANSPARENT
PUSHBUTTON "重签",IDC_BUTTON1,71,132,62,19
PUSHBUTTON "确定",IDC_BUTTON2,175,132,62,19
END