C++与Object-c互相调用

此例主要包含以下功能:
1、程序开机自启设置
2、系统锁定状态获取
3、系统关机监听(MacOS)

SystemCtrl.h

#pragma once
#include <string>
#include <map>
#include <mutex>
#include "Utils/Singleton.h"


class SystemCtrl : public Utils::Singleton<SystemCtrl>
{
public:
    void Init();
    void NotifyShutdownTriggered();
    bool IsSystemLocked();
    bool StartupWithSystem(const std::string& strProgramName);
    bool RemoveStartupWithSystem(const std::string& strProgramName);
    void UpdateLockState(bool bLocked);

private:
    void* m_pObject;
    bool m_bSystemLocked;
};

WindowsSystemCtrl.cpp

#ifdef WIN32
#include "SystemCtrl.h"
#include <Windows.h>
#include <WtsApi32.h>
#include "Utils/Logger.h"
#include "Utils/StringUtil.h"


std::wstring g_wstrExePath;
HKEY hkey;
std::string get_programe_path()
{
    TCHAR szBuffer[512] = { 0 };
    GetModuleFileName(nullptr, szBuffer, sizeof(szBuffer));
    // reference: https://www.cnblogs.com/staring-hxs/archive/2013/01/24/2874690.html
    UINT len = wcslen(szBuffer) * 2;
    char* buf = (char*)malloc(len);
    UINT i = wcstombs(buf, szBuffer, len);
    std::string full_path = buf;
    return full_path;
}

bool startup_with_system(const std::string& name, const std::string& strExePath)
{
    std::wstring wstrProgramName = Utils::StringUtil::StringToWString(name);
    g_wstrExePath = Utils::StringUtil::StringToWString(strExePath);

    // open startup handle
    if (RegOpenKeyEx(HKEY_CURRENT_USER, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", 0, KEY_ALL_ACCESS, &hkey) == ERROR_SUCCESS) {
        // check key
        TCHAR strDir[MAX_PATH] = {};
        DWORD nLength = MAX_PATH;
        // If the function succeeds, the return value is ERROR_SUCCESS.
        // reference��https://docs.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-reggetvaluea
        long result = RegGetValue(hkey, nullptr, wstrProgramName.c_str(), RRF_RT_REG_SZ, 0, strDir, &nLength);

        // key already exist
        if (result != ERROR_SUCCESS) {
            // add register key
            RegSetValueEx(hkey, wstrProgramName.c_str(), 0, REG_SZ, (LPBYTE)g_wstrExePath.c_str(),
                (g_wstrExePath.length() + 1) * sizeof(TCHAR));
            // close register
            RegCloseKey(hkey);
            return true;
        }
        else
        {
            LOG(INFO) << "StartWithSystem: Have been created!";
            return false;
        }
    }
    else
    {
        LOG(LERROR) << "StartWithSystem: Can`t open the Reg!";
        return false;
    }
}

void SystemCtrl::Init()
{
    m_bSystemLocked = false;
}

void SystemCtrl::NotifyShutdownTriggered()
{

}

bool SystemCtrl::IsSystemLocked()
{
    typedef BOOL(PASCAL* WTSQuerySessionInformation)(HANDLE hServer, DWORD SessionId, WTS_INFO_CLASS WTSInfoClass, LPTSTR* ppBuffer, DWORD* pBytesReturned);
    typedef void (PASCAL* WTSFreeMemory)(PVOID pMemory);

    WTSINFOEXW* pInfo = NULL;
    WTS_INFO_CLASS wtsic = WTSSessionInfoEx;
    bool bRet = false;
    LPTSTR ppBuffer = NULL;
    DWORD dwBytesReturned = 0;
    LONG dwFlags = 0;
    WTSQuerySessionInformation pWTSQuerySessionInformation = NULL;
    WTSFreeMemory pWTSFreeMemory = NULL;

    HMODULE hLib = LoadLibrary(L"wtsapi32.dll");
    if (!hLib) {
        return false;
    }
    pWTSQuerySessionInformation = (WTSQuerySessionInformation)GetProcAddress(hLib, "WTSQuerySessionInformationW");
    if (pWTSQuerySessionInformation)
    {
        pWTSFreeMemory = (WTSFreeMemory)GetProcAddress(hLib, "WTSFreeMemory");
        if (pWTSFreeMemory != NULL)
        {
            DWORD dwSessionID = WTSGetActiveConsoleSessionId();
            if (pWTSQuerySessionInformation(WTS_CURRENT_SERVER_HANDLE, dwSessionID, wtsic, &ppBuffer, &dwBytesReturned))
            {
                if (dwBytesReturned > 0)
                {
                    pInfo = (WTSINFOEXW*)ppBuffer;
                    if (pInfo->Level == 1)
                    {
                        dwFlags = pInfo->Data.WTSInfoExLevel1.SessionFlags;
                    }
                    if (dwFlags == WTS_SESSIONSTATE_LOCK)
                    {
                        bRet = true;
                    }
                }
                pWTSFreeMemory(ppBuffer);
                ppBuffer = NULL;
            }
        }
    }
    if (hLib != NULL)
    {
        FreeLibrary(hLib);
    }
    return bRet;
}

bool SystemCtrl::StartupWithSystem(const std::string& strProgramName)
{
    std::string strModulePath = get_programe_path();
    return startup_with_system(strProgramName, strModulePath);
}

bool SystemCtrl::RemoveStartupWithSystem(const std::string& strProgramName)
{
    std::wstring wstrProgramName = Utils::StringUtil::StringToWString(strProgramName);

    auto nCode = RegOpenKeyEx(HKEY_CURRENT_USER, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", 0, KEY_ALL_ACCESS, &hkey);
    if (ERROR_SUCCESS == nCode)
    {
        RegDeleteValue(hkey, wstrProgramName.c_str());
        RegCloseKey(hkey);
        return true;
    }

    LOG(LERROR) << "Remove startup failed: " << nCode;
    return false;
}

void SystemCtrl::UpdateLockState(bool bLocked)
{

}

#endif

MacSystemCtrl.mm

#include "SystemCtrl.h"
#include <QDebug>
#include <QApplication>
#include "Utils/QFile.h"
#import <Foundation/Foundation.h>
#import <Cocoa/Cocoa.h>


NS_ASSUME_NONNULL_BEGIN
@interface MacSystemCtrlImpl : NSObject {}
  // api
- (bool)  OpenVideoUrl:(const std::string&) strUrl;
- (void) RegisterMacSystemCtrlCallback:(const std::string&) strUrl;
NS_ASSUME_NONNULL_END
@end

@implementation MacSystemCtrlImpl{   }


// register shutdown callback
- (void) RegisterMacSystemCtrlCallback:(const std::string&) strInfo;
{
    //NSWorkspace.sharedWorkspace.notificationCenter.addObserver(self, selector: #selector(methodWillPowerOffNotification), name: NSWorkspace.willPowerOffNotification, object: nil)
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    NSNotificationCenter *nc = [[NSWorkspace sharedWorkspace] notificationCenter];
    MacSystemCtrlImpl *mainController = [[MacSystemCtrlImpl alloc] init];
    //register for shutdown notications
    [nc addObserver:mainController
    selector:@selector(computerWillShutDownNotification:)
          name:NSWorkspaceWillPowerOffNotification object:nil];
    //[[NSRunLoop currentRunLoop] run];
    //[pool release];
    // reference: https://juejin.cn/post/6975118322576654373
    // lock notications
    [[NSDistributedNotificationCenter defaultCenter] addObserver:mainController
    selector:@selector(computerLockedNotification:)
          name: @"com.apple.screenIsLocked" object:nil];

    // unlock notications
    [[NSDistributedNotificationCenter defaultCenter] addObserver:mainController
    selector:@selector(computerUnlockedNotification:)
          name: @"com.apple.screenIsUnlocked" object:nil];
}
// callback shutdown
- (void) computerWillShutDownNotification:(NSNotification *)notification {
    NSLog(@"Received Shutdown Notification");
    SystemCtrl::Instance().NotifyShutdownTriggered();
}
// callback lock
- (void) computerLockedNotification:(NSNotification *)notification {
    NSLog(@"Received lock Notification");
    SystemCtrl::Instance().UpdateLockState(true);
}
// callback unlock
- (void) computerUnlockedNotification:(NSNotification *)notification {
    NSLog(@"Received unlock Notification");
    SystemCtrl::Instance().UpdateLockState(false);
}
@end

// To convert a QString into NSString *
#define QStringToNSString(s) [NSString stringWithUTF8String:s.toUtf8().data()]
void startup_with_system(const std::string& strAppName, bool bEnable)
{
    // NSString* pNString = [NSString stringWithCString:strUrl.c_str()];
    QString qstrAppPath = Utils::QFileManager::MakeEndWithSplash(Utils::QFileManager::GetModulePath()) + strAppName.c_str();
    //qDebug() << "App path: " << qstrAppPath;
    LSSharedFileListRef loginItems = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL);
    if(bEnable)
    {
        CFURLRef url = (CFURLRef)[NSURL fileURLWithPath:QStringToNSString(qstrAppPath)];
        LSSharedFileListItemRef item = LSSharedFileListInsertItemURL(loginItems, kLSSharedFileListItemLast, NULL, NULL, url, NULL, NULL);

        CFRelease(item);

        CFRelease(loginItems);
    }
    else
    {
        UInt32 seedValue;

        CFURLRef thePath;

        CFArrayRef loginItemsArray = LSSharedFileListCopySnapshot(loginItems, &seedValue);
        //qDebug() << "Delete startup item: " << qstrAppPath;
        for (id item in (NSArray *)loginItemsArray) {

            LSSharedFileListItemRef itemRef = (LSSharedFileListItemRef)item;
            auto nCode = LSSharedFileListItemResolve(itemRef, 0, (CFURLRef*) &thePath, NULL);
            if (noErr == nCode) {
                if ([[(NSURL *)thePath path] hasPrefix:QStringToNSString(qstrAppPath)])
                {
                    // delete startup app
                    LSSharedFileListItemRemove(loginItems, itemRef);
                }
                CFRelease(thePath);
            }
            else {
                //qDebug() << "Remove startup app failed: " << nCode;
            }

        }

        CFRelease(loginItemsArray);

        CFRelease(loginItems);
    }
}


void SystemCtrl::Init()
{
    std::string strInfo;
    MacSystemCtrlImpl *pObject = [[MacSystemCtrlImpl alloc] init];
    m_pObject = (__bridge void *)pObject;
    // shutdown handle
    [(__bridge id)m_pObject RegisterMacSystemCtrlCallback:strInfo];
}

void SystemCtrl::NotifyShutdownTriggered()
{
    qDebug() << "Shutdown triggered";
    qApp->exit(0);
}

bool SystemCtrl::IsSystemLocked()
{
    return m_bSystemLocked;
}

bool SystemCtrl::StartupWithSystem(const std::string& strProgramName)
{
    startup_with_system(strProgramName, true);
    return true;
}

bool SystemCtrl::RemoveStartupWithSystem(const std::string& strProgramName)
{
    startup_with_system(strProgramName, false);
    return true;
}

void SystemCtrl::UpdateLockState(bool bLocked)
{
    m_bSystemLocked = bLocked;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值