C++カーネルオブジェクトパッケージ単一インスタンスイニシエータのクラス

2531 ワード

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