使用命名对象防止运行一个程序的多个实例【转】
1.要点
- 在程序的入口处调用CreateXXX函数创建一个命名对象(如Mutex,Event等均可),然后调用GetLastError()函数检查返回值,看此对象是否已存在,如果已存在则说明已存在此程序的实例
- 在程序的出口点调用CloseHandle()关闭在入口处创建的命名对象
2.实现代码
1: //At the entry point, such aa the beginning of WinMain in Win32 app,
2: //or CWinApp::InitInstance() in MFC app
3: LPCTSTR instanceName =4: _T("AD83912A-43F2-4BF6-B0CF-02BF6589FFF7"); //Generated with GuidGen tool5: HANDLE h = ::CreateMutex(NULL,FALSE,instanceName);6: DWORD error = GetLastError();7: if (error == ERROR_ALREADY_EXISTS)
8: {9: ::CloseHandle(h);10: return FALSE; //Exist11: }12:13: //.......
14:15: //At the exist point, close the named object and then exist
16: ::CloseHandle(h);17: return FALSE; //Exist18:
相关热门文章
给主人留下些什么吧!~~
评论热议