//MFC program :
#include <windows.h> #pragma data_seg("Shared") HWND hwnd=NULL; #pragma data_seg() #pragma comment(linker,"/section:Shared,RWS") if(hwnd==NULL) { hwnd=m_hWnd; }else { ::SetForegroundWindow(hwnd); ExitProcess(0); }//console program: create a section
#include <windows.h> #pragma data_seg("Shared") int volatile g_lAppInstance =0; #pragma data_seg() #pragma comment(linker,"/section:Shared,RWS") if(++g_lAppInstance>1) { MessageBox(NULL,"该程序已经有一实例运行!",NULL,NULL); ExitProcess(0); }
//Mutex program:
HANDLE hObject = CreateMutex(NULL,FALSE,"LengFeng"); if(GetLastError() == ERROR_ALREADY_EXISTS) { CloseHandle(hObject); MessageBox(NULL,"程序已经运行!",NULL,NULL); return FALSE; }