1. 程式人生 > >讓MFC程式只執行單個例項 的簡單示例

讓MFC程式只執行單個例項 的簡單示例

這裡只是簡單的建立一個MFC 程式來演示 只執行一個例項。

// 在標頭檔案中新增類似如下程式碼

#define SCANSETTINGS_CLASSNAME		_T("ScanSettingsWindowClass")
#define APPMUTEX					_T("Global\\ScanSettings")

class C**App : public CWinAppEx
{
public:
	C**App();

	// Overrides
public:
	virtual BOOL InitInstance();
	virtual int ExitInstance();

private:	
	HANDLE m_hMutex;

	// Implementation
	BOOL RestrictOneInstance();

public:
	DECLARE_MESSAGE_MAP()	
};

// 在原始檔中新增如下程式碼
BOOL C**App::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;
}

BOOL C**App::InitInstance()
{
	// Begin.  把這段程式碼加在最前面即可
	if (!RestrictOneInstance())
	{
		return FALSE;
	}

	WNDCLASS wc;
	::GetClassInfo(AfxGetInstanceHandle(), _T("#32770"), &wc);
	wc.lpszClassName = SCANSETTINGS_CLASSNAME;
	AfxRegisterClass(&wc);
	// End 

	// 其他程式碼
}

int C**App::ExitInstance()
{
	// TODO: Add your specialized code here and/or call the base class
	if (m_hMutex != NULL)
	{
		CloseHandle(m_hMutex);
		m_hMutex = NULL;
	}

	return CWinAppEx::ExitInstance();
}


最後注意在資源指令碼中也應修改

IDD_CONNECT_SETUP DIALOGEX 0, 0, 313, 220
STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "Scan Settings Tool"
CLASS "ScanSettingsWindowClass" (注意新增這一句)
FONT 8, "MS Shell Dlg", 400, 0, 0x1
BEGIN
END
大致示例也就這樣了。至於那個 32770就是標準對話方塊的,可以用SPY++ 檢視下就明白了。

MFC 可以這樣做,其他的也類似了。