C++内核对象封装单实例启动程序的类

时间:2022-06-13 05:19:07
复制代码 代码如下:

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