c++程序单实例运行

1、使用互斥信号量

	HANDLE hObject = CreateMutex(NULL,FALSE,"LengFeng");

	if(GetLastError() == ERROR_ALREADY_EXISTS)
	{
		CloseHandle(hObject);
		MessageBox(NULL,"程序已经运行!",NULL,NULL);
		return FALSE;
	}
	MessageBox(NULL,"ok",NULL,NULL);

2、使用data_seg和linker

#include <windows.h>
#pragma data_seg("Singleton")
HWND hwnd=NULL;
#pragma data_seg()
#pragma comment(linker,"/section:Singleton,RWS")

BOOL CSingletonProgramDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
	if(hwnd==NULL)
	{
		hwnd=m_hWnd;
		
	}else{
		::SetForegroundWindow(hwnd);
		ExitProcess(0);
	}
	
	return TRUE;  
}
3、

#include <windows.h>

#pragma  data_seg("Shared")
int volatile g_lAppInstance =0;
#pragma  data_seg()
#pragma comment(linker,"/section:Shared,RWS")

int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow)
{
	if(++g_lAppInstance>1)
	{
		MessageBox(NULL,"该程序已经有一实例运行!",NULL,NULL);
		ExitProcess(0);
	}
	MessageBox(NULL,"ok","tips",MB_OK);
	return 0;
}



你可能感兴趣的:(c++程序单实例运行)