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