C++ 运行单个实例,防止程序多次启动
利用内核对象 封装的类,使用运行单个实例,防止多次启动Demo
例子下载地址:http://pan.baidu.com/share/link?shareid=3202369154&uk=3037189616
//File Name: Singleton.h #pragma once class Singleton { private: CString strGUID; CString strMapFileGUID; HANDLE m_hSingleton; public: Singleton(); ~Singleton(); public: void AppStart (const HWND & hWnd) const; };
//File Name: Singleton.cpp #include "stdafx.h" #include "Singleton.h" Singleton::Singleton() { strGUID = _T("{D727BDB5-F86A-405b-910D-11AD2A4CA76E}"); strMapFileGUID = strGUID + _T("_MapFile"); m_hSingleton = NULL; } Singleton::~Singleton() { if (m_hSingleton) { CloseHandle(m_hSingleton); m_hSingleton = NULL; } } void Singleton::AppStart(const HWND & hWnd) const { HANDLE m_hSingleton = NULL; m_hSingleton = CreateMutex(NULL, TRUE, strGUID); RECT rect; ZeroMemory(&rect, sizeof(rect)); ::GetWindowRect(hWnd, &rect); if (GetLastError() == ERROR_ALREADY_EXISTS) { // 打开共享文件 HANDLE hHandle = ::OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, strMapFileGUID); if (hHandle) { LPTSTR lpMapAddr = (LPTSTR)::MapViewOfFile(hHandle, FILE_MAP_ALL_ACCESS, 0, 0, 0); CString strBuffer(lpMapAddr); HWND hOldWnd = (HWND)_tcstoul(strBuffer, NULL, 10); ::SetForegroundWindow(hOldWnd); // 取消内核对象的映射 UnmapViewOfFile(hHandle); CloseHandle(hHandle); exit(0); } } else // 第一运行程序 { int nNum = sizeof(HANDLE); // 创建文件映射内核对象 HANDLE hHandle = ::CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, sizeof(HANDLE), strMapFileGUID); if (hHandle) { // 拷贝数据到共享文件里 LPTSTR lpMapAddr = (LPTSTR)::MapViewOfFile(hHandle, FILE_MAP_ALL_ACCESS, 0, 0, 0); CString strBuffer; strBuffer.Format(_T("%d"), hWnd); _tcscpy(lpMapAddr, strBuffer); // 讲写入文件映射缓冲区的所有数据刷新到磁盘; ::FlushViewOfFile(lpMapAddr, strBuffer.GetLength()+1); } } }