服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C/C++ - C++内核对象封装单实例启动程序的类

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

2021-01-09 15:19C++教程网 C/C++

这篇文章主要介绍了利用C++内核对象封装的类,程序只能运行单个实例,可防止多次启动,大家参考使用吧

复制代码 代码如下:

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

延伸 · 阅读

精彩推荐