class winutils {
  public:
    winutils() {
}
  public:
    static bool injectDll(DWORD processId, const QString& dllPath) {
    HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, processId);
    if (!hProcess)
    {
        qDebug() << "Failed to open process:" << GetLastError();
        return false;
    }

    if (checkDllExist(processId, dllPath))
    {
        qDebug() << "Process already have been injected";
        return true;
    }
    else if (injectDllViaCRTW(processId, dllPath))
    {
        return true;
    }
    else if (injectDllViaCRTA(processId, dllPath))
    {
        return true;
    }

    injectDllViaAPCW(processId, dllPath);
    injectDllViaAPCA(processId, dllPath);
    if (checkDllExist(processId, dllPath))
    {
        return true;
    }
    else if (injectDllViaWHKW(processId, dllPath))
    {
        return true;
    }
    else if (injectDllViaWHKA(processId, dllPath))
    {
        return true;
    }
    else
    {
        return false;
    }
}
    static bool injectDllViaCRTA(DWORD processId, const QString& dllPath) {
    HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, processId);
    if (!hProcess)
    {
        qDebug() << "Failed to open process:" << GetLastError();
        return false;
    }

    if (checkDllExist(processId, dllPath))
    {
        qDebug() << "Process already have been injected";
        return true;
    }
    SIZE_T pathSize = (dllPath.size() + 1) * sizeof(char);
    LPVOID pDllPath =
        VirtualAllocEx(hProcess,
                       nullptr,
                       pathSize,
                       MEM_COMMIT | MEM_RESERVE,
                       PAGE_EXECUTE_READWRITE);
    if (!pDllPath)
    {
        qDebug() << "Failed to allocate memory in target process:"
                 << GetLastError();
        CloseHandle(hProcess);
        return false;
    }

    if (!WriteProcessMemory(hProcess,
                            pDllPath,
                            dllPath.toStdString().c_str(),
                            pathSize,
                            nullptr))
    {
        qDebug() << "Failed to write memory in target process:"
                 << GetLastError();
        VirtualFreeEx(hProcess, pDllPath, 0, MEM_RELEASE);
        CloseHandle(hProcess);
        return false;
    }

    HMODULE hKernel32 = GetModuleHandle(L"kernel32.dll");
    if (!hKernel32)
    {
        qDebug() << "Failed to get handle for kernel32.dll:" << GetLastError();
        VirtualFreeEx(hProcess, pDllPath, 0, MEM_RELEASE);
        CloseHandle(hProcess);
        return false;
    }

    FARPROC pLoadLibraryA = GetProcAddress(hKernel32, "LoadLibraryA");
    if (!pLoadLibraryA)
    {
        qDebug() << "Failed to get address of LoadLibraryA:" << GetLastError();
        VirtualFreeEx(hProcess, pDllPath, 0, MEM_RELEASE);
        CloseHandle(hProcess);
        return false;
    }

    HANDLE hThread = CreateRemoteThread(hProcess,
                                        nullptr,
                                        0,
                                        (LPTHREAD_START_ROUTINE)pLoadLibraryA,
                                        pDllPath,
                                        0,
                                        nullptr);
    if (!hThread)
    {
        qDebug() << "Failed to create remote thread:" << GetLastError();
        VirtualFreeEx(hProcess, pDllPath, 0, MEM_RELEASE);
        CloseHandle(hProcess);
        return false;
    }

    WaitForSingleObject(hThread, INFINITE);

    // 检查LoadLibrary是否执行成功
    DWORD exitCode = 0;
    if (GetExitCodeThread(hThread, &exitCode))
    {
        qDebug() << "Remote thread exit code:" << exitCode;
        // LoadLibrary返回的是模块句柄，如果为0则失败
        if (exitCode == 0)
        {
            VirtualFreeEx(hProcess, pDllPath, 0, MEM_RELEASE);
            CloseHandle(hProcess);
            CloseHandle(hThread);
            qDebug() << "LoadLibrary failed in remote process";
            return false;
        }
    }

    VirtualFreeEx(hProcess, pDllPath, 0, MEM_RELEASE);
    CloseHandle(hThread);
    CloseHandle(hProcess);

    return true;
}
    static bool injectDllViaCRTW(DWORD processId, const QString& dllPath) {
    HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, processId);
    if (!hProcess)
    {
        qDebug() << "Failed to open process:" << GetLastError();
        return false;
    }

    if (checkDllExist(processId, dllPath))
    {
        qDebug() << "Process already have been injected";
        return true;
    }
    SIZE_T pathSize = (dllPath.size() + 1) * sizeof(wchar_t);
    LPVOID pDllPath =
        VirtualAllocEx(hProcess, nullptr, pathSize, MEM_COMMIT | MEM_RESERVE,
                       PAGE_EXECUTE_READWRITE);
    if (!pDllPath)
    {
        qDebug() << "Failed to allocate memory in target process:"
                 << GetLastError();
        CloseHandle(hProcess);
        return false;
    }

    if (!WriteProcessMemory(hProcess,
                            pDllPath,
                            dllPath.toStdWString().c_str(),
                            pathSize,
                            nullptr))
    {
        qDebug() << "Failed to write memory in target process:"
                 << GetLastError();
        VirtualFreeEx(hProcess, pDllPath, 0, MEM_RELEASE);
        CloseHandle(hProcess);
        return false;
    }

    HMODULE hKernel32 = GetModuleHandle(L"kernel32.dll");
    if (!hKernel32)
    {
        qDebug() << "Failed to get handle for kernel32.dll:" << GetLastError();
        VirtualFreeEx(hProcess, pDllPath, 0, MEM_RELEASE);
        CloseHandle(hProcess);
        return false;
    }

    FARPROC pLoadLibraryW = GetProcAddress(hKernel32, "LoadLibraryW");
    if (!pLoadLibraryW)
    {
        qDebug() << "Failed to get address of LoadLibraryW:" << GetLastError();
        VirtualFreeEx(hProcess, pDllPath, 0, MEM_RELEASE);
        CloseHandle(hProcess);
        return false;
    }

    HANDLE hThread = CreateRemoteThread(hProcess,
                                        nullptr,
                                        0,
                                        (LPTHREAD_START_ROUTINE)pLoadLibraryW,
                                        pDllPath,
                                        0,
                                        nullptr);
    if (!hThread)
    {
        qDebug() << "Failed to create remote thread:" << GetLastError();
        VirtualFreeEx(hProcess, pDllPath, 0, MEM_RELEASE);
        CloseHandle(hProcess);
        return false;
    }

    WaitForSingleObject(hThread, INFINITE);

    // 检查LoadLibrary是否执行成功
    DWORD exitCode = 0;
    if (GetExitCodeThread(hThread, &exitCode))
    {
        qDebug() << "Remote thread exit code:" << exitCode;
        // LoadLibrary返回的是模块句柄，如果为0则失败
        if (exitCode == 0)
        {
            VirtualFreeEx(hProcess, pDllPath, 0, MEM_RELEASE);
            CloseHandle(hProcess);
            CloseHandle(hThread);
            qDebug() << "LoadLibrary failed in remote process";
            return false;
        }
    }

    VirtualFreeEx(hProcess, pDllPath, 0, MEM_RELEASE);
    CloseHandle(hThread);
    CloseHandle(hProcess);

    return true;
}
    static bool injectDllViaAPCA(DWORD processId, const QString& dllPath) {
    HANDLE hProcess =
        OpenProcess(PROCESS_ALL_ACCESS,
                    FALSE,
                    processId);

    if (!hProcess)
    {
        qDebug() << "Failed to open process: " << GetLastError();
        return false;
    }

    if (checkDllExist(processId, dllPath))
    {
        qDebug() << "Process already have been injected";
        return true;
    }

    // 在目标进程中分配内存并写入DLL路径
    SIZE_T pathSize = (dllPath.toStdString().size() + 1) * sizeof(char);
    LPVOID pDllPath = VirtualAllocEx(hProcess,
                                     NULL,
                                     pathSize,
                                     MEM_COMMIT,
                                     PAGE_READWRITE);

    if (!pDllPath)
    {
        qDebug() << "Failed to allocate memory: " << GetLastError();
        CloseHandle(hProcess);
        return false;
    }

    if (!WriteProcessMemory(hProcess, pDllPath, dllPath.toStdString().c_str(),
                            pathSize, NULL))
    {
        qDebug() << "Failed to write memory: " << GetLastError();
        VirtualFreeEx(hProcess, pDllPath, 0, MEM_RELEASE);
        CloseHandle(hProcess);
        return false;
    }

    // 获取LoadLibraryW的地址
    HMODULE hKernel32 = GetModuleHandle(L"kernel32.dll");
    if (!hKernel32)
    {
        qDebug() << "Failed to get kernel32 handle";
        VirtualFreeEx(hProcess, pDllPath, 0, MEM_RELEASE);
        CloseHandle(hProcess);
        return false;
    }

    FARPROC pLoadLibraryA = GetProcAddress(hKernel32, "LoadLibraryA");
    if (!pLoadLibraryA)
    {
        qDebug() << "Failed to get LoadLibraryA address";
        VirtualFreeEx(hProcess, pDllPath, 0, MEM_RELEASE);
        CloseHandle(hProcess);
        return false;
    }

    // 获取进程中的所有线程
    DWORD threadId = getProcessMainThread(processId);
    if (!threadId)
    {
        qDebug() << "No threads found in the process";
        VirtualFreeEx(hProcess, pDllPath, 0, MEM_RELEASE);
        CloseHandle(hProcess);
        return false;
    }

    // 向目标进程的所有线程队列中添加APC调用
    bool success = false;

    // 打开线程
    HANDLE hThread = OpenThread(THREAD_SET_CONTEXT, FALSE, threadId);
    if (hThread)
    {
        // 将LoadLibraryA作为APC函数加入队列
        PostThreadMessageA(threadId, WM_PAINT, 0, 0);
        DWORD result =
            QueueUserAPC((PAPCFUNC)pLoadLibraryA, hThread, (ULONG_PTR)pDllPath);
        PostThreadMessageA(threadId, WM_PAINT, 0, 0);
        if (result != 0)
        {
            success = true;
            qDebug() << "APC queued to thread " << threadId;
        }

        CloseHandle(hThread);
    }

    if (!success)
    {
        qDebug() << "Failed to queue APC to any thread";
        VirtualFreeEx(hProcess, pDllPath, 0, MEM_RELEASE);
        CloseHandle(hProcess);
        return false;
    }

    // 注意：我们不释放分配的内存，因为APC函数尚未执行
    // 内存将在DLL加载后释放

    CloseHandle(hProcess);
    return true;
}
    static bool injectDllViaAPCW(DWORD processId, const QString& dllPath) {
    HANDLE hProcess =
        OpenProcess(PROCESS_ALL_ACCESS,
                    FALSE,
                    processId);

    if (!hProcess)
    {
        qDebug() << "Failed to open process: " << GetLastError();
        return false;
    }

    if (checkDllExist(processId, dllPath))
    {
        qDebug() << "Process already have been injected";
        return true;
    }

    // 在目标进程中分配内存并写入DLL路径
    SIZE_T pathSize = (dllPath.toStdWString().size() + 1) * sizeof(wchar_t);
    LPVOID pDllPath = VirtualAllocEx(hProcess,
                                     NULL,
                                     pathSize,
                                     MEM_COMMIT,
                                     PAGE_READWRITE);

    if (!pDllPath)
    {
        qDebug() << "Failed to allocate memory: " << GetLastError();
        CloseHandle(hProcess);
        return false;
    }

    if (!WriteProcessMemory(hProcess,
                            pDllPath,
                            dllPath.toStdWString().c_str(),
                            pathSize,
                            NULL))
    {
        qDebug() << "Failed to write memory: " << GetLastError();
        VirtualFreeEx(hProcess, pDllPath, 0, MEM_RELEASE);
        CloseHandle(hProcess);
        return false;
    }

    // 获取LoadLibraryW的地址
    HMODULE hKernel32 = GetModuleHandle(L"kernel32.dll");
    if (!hKernel32)
    {
        qDebug() << "Failed to get kernel32 handle";
        VirtualFreeEx(hProcess, pDllPath, 0, MEM_RELEASE);
        CloseHandle(hProcess);
        return false;
    }

    FARPROC pLoadLibraryW = GetProcAddress(hKernel32, "LoadLibraryW");
    if (!pLoadLibraryW)
    {
        qDebug() << "Failed to get LoadLibraryW address";
        VirtualFreeEx(hProcess, pDllPath, 0, MEM_RELEASE);
        CloseHandle(hProcess);
        return false;
    }

    // 获取进程中的所有线程
    DWORD threadId = getProcessMainThread(processId);
    if (!threadId)
    {
        qDebug() << "No threads found in the process";
        VirtualFreeEx(hProcess, pDllPath, 0, MEM_RELEASE);
        CloseHandle(hProcess);
        return false;
    }

    // 向目标进程的所有线程队列中添加APC调用
    bool success = false;

    // 打开线程
    HANDLE hThread = OpenThread(THREAD_SET_CONTEXT, FALSE, threadId);
    if (hThread)
    {
        // 将LoadLibraryW作为APC函数加入队列
        PostThreadMessageW(threadId, WM_PAINT, 0, 0);
        DWORD result =
            QueueUserAPC((PAPCFUNC)pLoadLibraryW, hThread, (ULONG_PTR)pDllPath);
        PostThreadMessageW(threadId, WM_PAINT, 0, 0);
        if (result != 0)
        {
            success = true;
            qDebug() << "APC queued to thread " << threadId;
        }

        CloseHandle(hThread);
    }

    if (!success)
    {
        qDebug() << "Failed to queue APC to any thread";
        VirtualFreeEx(hProcess, pDllPath, 0, MEM_RELEASE);
        CloseHandle(hProcess);
        return false;
    }

    // 注意：我们不释放分配的内存，因为APC函数尚未执行
    // 内存将在DLL加载后释放

    CloseHandle(hProcess);
    return true;
}
    static bool injectDllViaWHKA(DWORD processId, const QString& dllPath) {
    if (checkProcessProtection(processId))
    {
        qDebug() << "进程被保护 进程ID: " << processId;
        return false;
    }

    // 1. 加载DLL到当前进程
    HMODULE hMod = LoadLibraryA(dllPath.toStdString().c_str());
    if (!hMod)
        return false;

    // 2. 获取Hook过程的地址
    HOOKPROC hookProc = (HOOKPROC)GetProcAddress(hMod, "HookProc");
    if (!hookProc)
        return false;

    // 3. 获取目标线程ID
    DWORD threadId = getProcessMainThread(processId);
    if (threadId == 0)
        return false;

    // 4. 安装Hook
    HHOOK hHook = SetWindowsHookExA(WH_CBT,   // Hook类型
                                    hookProc, // Hook过程
                                    hMod,     // DLL模块句柄
                                    threadId  // 目标线程ID
                                    );

    if (!hHook)
        return false;
    // 5. 触发Hook执行
    PostThreadMessageA(threadId, WM_NULL, 0, 0);
    Sleep(5000);
    UnhookWindowsHookEx(hHook);

    return true;
}
    static bool injectDllViaWHKW(DWORD processId, const QString& dllPath) {
    if (checkProcessProtection(processId))
    {
        qDebug() << "进程被保护 进程ID: " << processId;
        return false;
    }

    // 1. 加载DLL到当前进程
    HMODULE hMod = LoadLibraryW(dllPath.toStdWString().c_str());
    if (!hMod)
        return false;

    // 2. 获取Hook过程的地址
    HOOKPROC hookProc = (HOOKPROC)GetProcAddress(hMod, "HookProc");
    if (!hookProc)
        return false;

    // 3. 获取目标线程ID
    DWORD threadId = getProcessMainThread(processId);
    if (threadId == 0)
        return false;

    // 4. 安装Hook
    HHOOK hHook = SetWindowsHookExW(WH_CBT,   // Hook类型
                                    hookProc, // Hook过程
                                    hMod,     // DLL模块句柄
                                    threadId  // 目标线程ID
                                    );

    if (!hHook)
        return false;
    // 5. 触发Hook执行
    PostThreadMessageW(threadId, WM_NULL, 0, 0);
    Sleep(5000);
    UnhookWindowsHookEx(hHook);

    return true;
}
    static bool unhookDll(DWORD processId, const QString& dllPath) {
    HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, processId);
    if (!hProcess)
    {
        qDebug() << "Failed to open process:" << GetLastError();
        return false;
    }

    HMODULE hModules[1024];
    DWORD cbNeeded;
    if (EnumProcessModules(hProcess, hModules, sizeof(hModules), &cbNeeded))
    {
        for (unsigned int i = 0; i < (cbNeeded / sizeof(HMODULE)); i++)
        {
            TCHAR moduleName[MAX_PATH];
            if (GetModuleFileNameEx(hProcess, hModules[i], moduleName,
                                    sizeof(moduleName) / sizeof(TCHAR)))
            {
#ifdef UNICODE
                bool isDll = dllPath.toStdWString() == moduleName;
#else
                bool isDll = dllPath.toStdString() == moduleName;
#endif
                if (isDll)
                {
                    FARPROC pFreeLibrary = GetProcAddress(
                        GetModuleHandle(L"kernel32.dll"), "FreeLibrary");
                    if (!pFreeLibrary)
                    {
                        qDebug() << "Failed to get address of FreeLibrary:"
                                 << GetLastError();
                        CloseHandle(hProcess);
                        return false;
                    }

                    HANDLE hThread =
                        CreateRemoteThread(hProcess, nullptr, 0,
                                           (LPTHREAD_START_ROUTINE)pFreeLibrary,
                                           hModules[i], 0, nullptr);
                    if (!hThread)
                    {
                        qDebug() << "Failed to create remote thread for "
                            "FreeLibrary:"
                                 << GetLastError();
                        CloseHandle(hProcess);
                        return false;
                    }

                    WaitForSingleObject(hThread, INFINITE);
                    CloseHandle(hThread);
                    CloseHandle(hProcess);
                    return true;
                }
            }
        }
    }

    CloseHandle(hProcess);
    return false;
}
    static bool checkDllExist(DWORD processId, const QString& dllPath) {
    HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
                                  FALSE,
                                  processId);
    if (!hProcess)
    {
        qDebug() << "打开进程失败:" << GetLastError();
        return false;
    }

    bool dllFound = false;
    HMODULE hModules[1024];
    DWORD cbNeeded;

    // 获取进程中所有已加载的模块
    if (EnumProcessModules(hProcess, hModules, sizeof(hModules), &cbNeeded))
    {
        DWORD moduleCount = cbNeeded / sizeof(HMODULE);
        for (DWORD i = 0; i < moduleCount; i++)
        {
            TCHAR moduleName[MAX_PATH] = {0};

            // 获取模块的完整路径
            if (GetModuleFileNameExW(hProcess, hModules[i], moduleName,
                                     sizeof(moduleName) / sizeof(TCHAR)))
            {
#ifdef UNICODE
                bool isDll = dllPath.toStdWString() == moduleName;
#else
                bool isDll = dllPath.toStdString() == moduleName;
#endif
                if (isDll)
                {
                    dllFound = true;
                    break;
                }
            }
        }
    }
    else
    {
        qDebug() << "枚举进程模块失败:" << GetLastError();
    }

    CloseHandle(hProcess);
    return dllFound;
}
    static bool checkProcessProtection(DWORD processId) {
    HANDLE hProcess =
        OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, processId);
    if (!hProcess)
    {
        qDebug() << "Cannot open process - likely protected";
        return true; // 可能被保护
    }

    // 检查是否是受保护进程
    PROCESS_PROTECTION_LEVEL_INFORMATION protectionInfo = {};
    DWORD returnLength;

    if (GetProcessInformation(hProcess, ProcessProtectionLevelInfo,
                              &protectionInfo, sizeof(protectionInfo)))
    {
        CloseHandle(hProcess);
        return protectionInfo.ProtectionLevel != PROTECTION_LEVEL_NONE;
    }

    CloseHandle(hProcess);
    return false;
}
    static void setAutoStart(bool enable,
                             const QString& appName,
                             const QString& execPath) {
    TaskScheduler scheduler;

    if (enable)
    {
        scheduler.createStartupShortcut(appName, execPath);
    }
    else
    {
        scheduler.deleteStartupShortcut(appName);
    }
}
    static bool isAutoStartEnabled(const QString& appName) {
    TaskScheduler scheduler;
    return scheduler.isStartupShortcutExists(appName);
}
    static BOOL getWindowsVersion(DWORD* majorVersion,
                                  DWORD* minorVersion,
                                  DWORD* buildNumber) {
    static char version[100] = {0};
    DWORD major, minor, build;

    if (!getWindowsVersion(&major, &minor, &build))
        return "Unknown Windows Version";

    // 确定Windows版本
    if (major == 10)
    {
        if (build >= 22000)
        {
            sprintf(version, "Windows 11 (Build %lu)", build);
        }
        else
        {
            sprintf(version, "Windows 10 (Build %lu)", build);
        }
    }
    else if (major == 6)
    {
        switch (minor)
        {
        case 3:
            sprintf(version, "Windows 8.1 (Build %lu)", build);
            break;
        case 2:
            sprintf(version, "Windows 8 (Build %lu)", build);
            break;
        case 1:
            sprintf(version, "Windows 7 (Build %lu)", build);
            break;
        case 0:
            sprintf(version, "Windows Vista (Build %lu)", build);
            break;
        default:
            sprintf(version, "Windows NT %lu.%lu (Build %lu)", major, minor,
                    build);
        }
    }
    else if (major == 5)
    {
        switch (minor)
        {
        case 2:
            sprintf(version, "Windows Server 2003 (Build %lu)", build);
            break;
        case 1:
            sprintf(version, "Windows XP (Build %lu)", build);
            break;
        case 0:
            sprintf(version, "Windows 2000 (Build %lu)", build);
            break;
        default:
            sprintf(version, "Windows NT %lu.%lu (Build %lu)", major, minor,
                    build);
        }
    }
    else
    {
        sprintf(version, "Windows NT %lu.%lu (Build %lu)", major, minor, build);
    }
    return version;
}
    static QString getWindowsVersion() {
    static char version[100] = {0};
    DWORD major, minor, build;

    if (!getWindowsVersion(&major, &minor, &build))
        return "Unknown Windows Version";

    // 确定Windows版本
    if (major == 10)
    {
        if (build >= 22000)
        {
            sprintf(version, "Windows 11 (Build %lu)", build);
        }
        else
        {
            sprintf(version, "Windows 10 (Build %lu)", build);
        }
    }
    else if (major == 6)
    {
        switch (minor)
        {
        case 3:
            sprintf(version, "Windows 8.1 (Build %lu)", build);
            break;
        case 2:
            sprintf(version, "Windows 8 (Build %lu)", build);
            break;
        case 1:
            sprintf(version, "Windows 7 (Build %lu)", build);
            break;
        case 0:
            sprintf(version, "Windows Vista (Build %lu)", build);
            break;
        default:
            sprintf(version, "Windows NT %lu.%lu (Build %lu)", major, minor,
                    build);
        }
    }
    else if (major == 5)
    {
        switch (minor)
        {
        case 2:
            sprintf(version, "Windows Server 2003 (Build %lu)", build);
            break;
        case 1:
            sprintf(version, "Windows XP (Build %lu)", build);
            break;
        case 0:
            sprintf(version, "Windows 2000 (Build %lu)", build);
            break;
        default:
            sprintf(version, "Windows NT %lu.%lu (Build %lu)", major, minor,
                    build);
        }
    }
    else
    {
        sprintf(version, "Windows NT %lu.%lu (Build %lu)", major, minor, build);
    }
    return version;
}
    static QList<ProcessInfo> getProcessList() {
    QList<ProcessInfo> processList;

    HANDLE hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if (hProcessSnap == INVALID_HANDLE_VALUE)
    {
        qDebug() << "创建进程快照失败: " << GetLastError();
        return processList;
    }

    PROCESSENTRY32 pe32;
    pe32.dwSize = sizeof(PROCESSENTRY32);

    if (!Process32First(hProcessSnap, &pe32))
    {
        qDebug() << "获取首个进程信息失败: " << GetLastError();
        CloseHandle(hProcessSnap);
        return processList;
    }

    do
    {
        if (systemNames.contains(pe32.szExeFile))
        {
            continue;
        }
        ProcessInfo info;
        info.pid = pe32.th32ProcessID;
        info.parentPid = pe32.th32ParentProcessID;
        info.name = QString::fromWCharArray(pe32.szExeFile);
        info.threadCount = pe32.cntThreads;

        // 获取内存使用和优先级信息
        HANDLE hProcess = OpenProcess(
            PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, info.pid);

        processList.append(info);
    } while (Process32Next(hProcessSnap, &pe32));

    CloseHandle(hProcessSnap);
    return processList;
}
    static QString getProcessPath(DWORD processId) {
    QString processPath;
    HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
                                  FALSE, processId);

    if (hProcess != NULL)
    {
        wchar_t buffer[MAX_PATH];
        if (GetModuleFileNameEx(hProcess, NULL, buffer, MAX_PATH) > 0)
        {
            processPath = QString::fromWCharArray(buffer);
        }
        CloseHandle(hProcess);
    }

    return processPath;
}
    static DWORD getProcessMainThread(DWORD processId) {
    HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
    if (hSnapshot == INVALID_HANDLE_VALUE)
    {
        qDebug() << "Failed to create thread snapshot:" << GetLastError();
        return 0;
    }

    THREADENTRY32 te32;
    te32.dwSize = sizeof(THREADENTRY32);

    DWORD mainThreadId = 0;
    FILETIME earliestTime = {0xFFFFFFFF, 0xFFFFFFFF}; // 设为最大值

    if (Thread32First(hSnapshot, &te32))
    {
        do
        {
            if (te32.th32OwnerProcessID == processId)
            {
                // 打开线程获取创建时间
                HANDLE hThread = OpenThread(THREAD_QUERY_INFORMATION, FALSE,
                                            te32.th32ThreadID);
                if (hThread)
                {
                    FILETIME creationTime, exitTime, kernelTime, userTime;
                    if (GetThreadTimes(hThread, &creationTime, &exitTime,
                                       &kernelTime, &userTime))
                    {
                        // 比较创建时间，找最早的线程
                        if (CompareFileTime(&creationTime, &earliestTime) < 0)
                        {
                            earliestTime = creationTime;
                            mainThreadId = te32.th32ThreadID;
                        }
                    }
                    CloseHandle(hThread);
                }
            }
        } while (Thread32Next(hSnapshot, &te32));
    }

    CloseHandle(hSnapshot);
    return mainThreadId;
}
    static QString getProcessNameById(DWORD processId) {
    HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
                                  FALSE, processId);
    if (hProcess == NULL)
    {
        return QString();
    }

    wchar_t processName[MAX_PATH];
    if (GetModuleBaseName(hProcess, NULL, processName, MAX_PATH))
    {
        CloseHandle(hProcess);
        QString name = QString::fromWCharArray(processName);
        return name;
    }

    CloseHandle(hProcess);
    return QString();
}
    static bool enableAllPrivilege() {
    HANDLE hToken;
    // 获取进程token
    if (!OpenProcessToken(GetCurrentProcess(),
                          TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
        return false;

    const wchar_t *essentialPrivileges[] = {
        SE_DEBUG_NAME, // 最重要的调试权限
    };

    TOKEN_PRIVILEGES tkp;
    bool success = true;

    for (const auto &privilege : essentialPrivileges)
    {
        tkp.PrivilegeCount = 1;
        tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
        if (LookupPrivilegeValue(NULL, privilege, &tkp.Privileges[0].Luid))
        {
            AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, NULL, NULL);
        }
    }

    CloseHandle(hToken);
    return success;
}
};

if (hProcess)
        {
            PROCESS_MEMORY_COUNTERS pmc;
            if (GetProcessMemoryInfo(hProcess, &pmc, sizeof(pmc)))
            {
                info.memoryUsage = pmc.WorkingSetSize;
            }
            else
            {
                info.memoryUsage = 0;
            }
            BOOL wow64Process = FALSE;
            IsWow64Process(hProcess, &wow64Process);
            info.is64Bit = !wow64Process;
            info.priorityClass = GetPriorityClass(hProcess);
            CloseHandle(hProcess);
        }
        else
        {
            info.memoryUsage = 0;
            info.priorityClass = 0;
        }

class ProcessMonitor {
    Q_OBJECT
public:
explicit ProcessMonitor(QSettings*   settings,
                        QTreeWidget* treeWidget,
                        QLabel*      treeStatusLabel,
                        QLabel*      injector32StatusLabel,
                        QLabel*      injector64StatusLabel,

                        QObject*     parent = nullptr);
    ~ProcessMonitor() {
    this->terminalBridge();
    delete m_bridge32;
    delete m_bridge64;
}
    void setInterval(int msec);
    void setFilter(QString processName) {
    m_filter = processName.toLower();
}
    void changeSpeed(double factor) {
    QString cmd = QString("change %1\n").arg(factor);
    m_bridge32->write(cmd.toUtf8(), cmd.size());
    m_bridge32->waitForBytesWritten();
    m_bridge64->write(cmd.toUtf8(), cmd.size());
    m_bridge64->waitForBytesWritten();
}
  public:
    void refresh() {
    healthcheckBridge();
    QList<ProcessInfo> processList = winutils::getProcessList();
    if (m_filter == "")
    {
        update(processList);
        m_treeStatusLabel->setText(QString(tr("搜索到%1个进程, 已过滤展示%2个"))
                                   .arg(processList.size())
                                   .arg(processList.size()));
    }
    else
    {
        QList<ProcessInfo> filtered;
        for (ProcessInfo info : processList)
        {
            if (info.name.toLower().contains(m_filter))
                filtered.append(info);
        }
        update(filtered);
        m_treeStatusLabel->setText(QString(tr("搜索到%1个进程, 已过滤展示%2个"))
                                   .arg(processList.size())
                                   .arg(filtered.size()));
    }
}
    void start() {
    m_timer = new QTimer(this);
    connect(m_timer, &QTimer::timeout, this, &ProcessMonitor::refresh);
    m_timer->start(1000);
}
  private:
    void onItemChanged(QTreeWidgetItem* item, int column) {
    if (column == 5 && (item->flags() & Qt::ItemIsUserCheckable))
    {
        bool state = m_treeWidget->blockSignals(true);

        Qt::CheckState checkState = item->checkState(column);
        QString processName = item->text(0);
        DWORD pid = item->text(1).toLong();
        bool is64Bit = item->text(3) == "x64" ? true : false;
        if (checkState == Qt::Checked)
        {
            m_targetNames.insert(processName);
            this->injectDll(pid, is64Bit);
            item->setText(5, tr("加速中"));
            for (int col = 0; col < item->columnCount(); ++col)
            {
                item->setBackground(col, QBrush(QColor("#f3e5f5")));
                item->setForeground(col, QBrush(QColor("#7b1fa2")));
            }
            qDebug() << processName << "勾选";
            dump();
        }
        else
        {
            m_targetNames.remove(processName);
            this->unhookDll(pid, is64Bit);
            item->setText(5, "");
            for (int col = 0; col < item->columnCount(); ++col)
            {
                item->setBackground(col, QBrush());
                item->setForeground(col, QBrush());
            }
            qDebug() << processName << "取消勾选";
            dump();
        }

        m_treeWidget->blockSignals(state);
    }
}
  private:
    QTreeWidget* m_treeWidget;
    QLabel* m_treeStatusLabel;
    QLabel* m_injector32StatusLabel;
    QLabel* m_injector64StatusLabel;
    QString m_filter;
    QTimer* m_timer = nullptr;
    QString m_dllPath;
    QProcess* m_bridge32;
    QProcess* m_bridge64;
    QSettings* m_settings;
    QHash<QString, QIcon> m_iconCache;
    QMap<DWORD, QTreeWidgetItem*> m_processItems;
    QSet<QString> m_targetNames;
    void init() {
    QStringList targetNames =
        m_settings->value(CONFIG_TARGETNAMES_KEY).toStringList();
    m_targetNames = QSet<QString>(targetNames.begin(), targetNames.end());
}
    void dump() {
    m_settings->setValue(CONFIG_TARGETNAMES_KEY,
                         QStringList(m_targetNames.values()));
}
    void update(const QList<ProcessInfo>& processList) {
    // 跟踪现有进程，用于确定哪些已终止
    QSet<DWORD> currentPids;
    for (const ProcessInfo& info : processList)
    {
        currentPids.insert(info.pid);
    }

    // 移除已终止的进程
    QMutableMapIterator<DWORD, QTreeWidgetItem*> i(m_processItems);
    while (i.hasNext())
    {
        i.next();
        if (!currentPids.contains(i.key()))
        {
            QTreeWidgetItem* item = i.value();
            QTreeWidgetItem* parent = item->parent();

            if (parent)
            {
                parent->removeChild(item);
            }
            else
            {
                auto index = m_treeWidget->indexOfTopLevelItem(item);
                m_treeWidget->takeTopLevelItem(index);
            }

            while (item->childCount() > 0)
            {
                QTreeWidgetItem* child = item->takeChild(0);
                if (parent)
                {
                    parent->addChild(child);
                }
                else
                {
                    m_treeWidget->addTopLevelItem(child);
                }
            }

            // 删除节点
            delete item;

            // 从映射中移除
            i.remove();
        }
    }

    // 添加或更新进程信息
    for (const ProcessInfo& info : processList)
    {
        if (m_processItems.contains(info.pid))
        {
            // 更新已存在的进程信息
            QTreeWidgetItem* item = m_processItems[info.pid];
            item->setText(1, QString::number(info.pid));
            item->setData(1, Qt::UserRole, (long long)info.pid);
            item->setText(2,
                          QString("%1 MB").arg(info.memoryUsage / 1024 / 1024));
            item->setData(2, Qt::UserRole, (uint)info.memoryUsage);

            QString arch = info.is64Bit ? "x64" : "x86";
            item->setText(3, arch);
            QString priority;
            switch (info.priorityClass)
            {
            case HIGH_PRIORITY_CLASS:
                priority = tr("高");
                break;
            case NORMAL_PRIORITY_CLASS:
                priority = tr("中");
                break;
            case IDLE_PRIORITY_CLASS:
                priority = tr("低");
                break;
            case REALTIME_PRIORITY_CLASS:
                priority = tr("实时");
                break;
            default:
                priority = tr("未知");
                break;
            }
            item->setText(4, priority);
            if (m_targetNames.contains(info.name))
            {
                if (item->checkState(5) == Qt::Unchecked)
                {
                    item->setCheckState(5, Qt::Checked);
                }
            }
            else
            {
                if (item->checkState(5) == Qt::Checked)
                {
                    item->setCheckState(5, Qt::Unchecked);
                }
            }
        }
        else
        {
            // 添加新进程
            QTreeWidgetItem* item = new SortTreeWidgetItem();

            item->setText(0, info.name);
            item->setData(0, Qt::UserRole, info.name.toLower());
            item->setText(1, QString::number(info.pid));
            item->setData(1, Qt::UserRole, (long long)info.pid);
            item->setText(2,
                          QString("%1 MB").arg(info.memoryUsage / 1024 / 1024));
            item->setData(2, Qt::UserRole, (uint)info.memoryUsage);

            QString arch = info.is64Bit ? "x64" : "x86";
            item->setText(3, arch);

            // 加载进程图标
            item->setIcon(0, getProcessIconCached(info.pid));

            QString priority;
            switch (info.priorityClass)
            {
            case HIGH_PRIORITY_CLASS:
                priority = tr("高");
                break;
            case NORMAL_PRIORITY_CLASS:
                priority = tr("中");
                break;
            case IDLE_PRIORITY_CLASS:
                priority = tr("低");
                break;
            case REALTIME_PRIORITY_CLASS:
                priority = tr("实时");
                break;
            default:
                priority = tr("未知");
                break;
            }
            item->setText(4, priority);
            item->setCheckState(5, Qt::Unchecked);
            m_treeWidget->addTopLevelItem(item);
            m_processItems[info.pid] = item;
        }
    }
}
    void injectDll(DWORD processId, bool is64Bit) {
    QString cmd = QString("inject %1\n").arg(processId);
    if (!is64Bit)
    {
        m_bridge32->write(cmd.toUtf8(), cmd.size());
        m_bridge32->waitForBytesWritten();
    }
    else
    {
        m_bridge64->write(cmd.toUtf8(), cmd.size());
        m_bridge64->waitForBytesWritten();
    }
}
    void unhookDll(DWORD processId, bool is64Bit) {
    QString cmd = QString("unhook %1\n").arg(processId);
    if (!is64Bit)
    {
        m_bridge32->write(cmd.toUtf8(), cmd.size());
        m_bridge32->waitForBytesWritten();
    }
    else
    {
        m_bridge64->write(cmd.toUtf8(), cmd.size());
        m_bridge64->waitForBytesWritten();
    }
}
    void startBridge32() {
    m_bridge32 = new QProcess();
    QStringList params32;
    m_bridge32->start(BRIDGE32_EXE, params32);
    if (!m_bridge32->waitForStarted())
    {
        qDebug() << "32位桥接子进程启动失败";
    }
    else
    {
        qDebug() << "32位桥接子进程已启动";
    }
    m_bridge32->setProcessChannelMode(QProcess::MergedChannels);
    connect(m_bridge32,
            &QProcess::readyReadStandardOutput,
            [&]()
    {
        QByteArray data = m_bridge32->readAllStandardOutput();
        qDebug() << "收到输出:" << QString(data).trimmed();
    });
}
    void startBridge64() {
    m_bridge64 = new QProcess();
    QStringList params64;
    m_bridge64->start(BRIDGE64_EXE, params64);
    if (!m_bridge64->waitForStarted())
    {
        qDebug() << "64位桥接子进程启动失败";
    }
    else
    {
        qDebug() << "64位桥接子进程已启动";
    }
    m_bridge64->setProcessChannelMode(QProcess::MergedChannels);
    connect(m_bridge64,
            &QProcess::readyReadStandardOutput,
            [&]()
    {
        QByteArray data = m_bridge64->readAllStandardOutput();
        qDebug() << "收到输出:" << QString(data).trimmed();
    });
}
    void healthcheckBridge() {
    if (this->m_bridge32->state() == QProcess::Running)
    {
        m_injector32StatusLabel->setStyleSheet("color: green");
        m_injector32StatusLabel->setText(tr("正常"));
    }
    else
    {
        m_injector32StatusLabel->setStyleSheet("color: red");
        m_injector32StatusLabel->setText(tr("异常退出"));
    }

    if (this->m_bridge64->state() == QProcess::Running)
    {
        m_injector64StatusLabel->setStyleSheet("color: green");
        m_injector64StatusLabel->setText(tr("正常"));
    }
    else
    {
        m_injector64StatusLabel->setStyleSheet("color:red");
        m_injector64StatusLabel->setText(tr("异常退出"));
    }
}
    void terminalBridge() {
    QString cmd = QString("exit\n");
    m_bridge32->write(cmd.toUtf8(), cmd.size());
    m_bridge32->waitForBytesWritten();
    m_bridge64->write(cmd.toUtf8(), cmd.size());
    m_bridge64->waitForBytesWritten();
}
    static QIcon getProcessIcon(QString processPath) {
    int lastSlashPos =
        std::max(processPath.lastIndexOf('/'), processPath.lastIndexOf('\\'));
    QString processName;
    if (lastSlashPos == -1)
    {
        processName = processPath;
    }
    processName = processPath.mid(lastSlashPos + 1);

    if (processPath.isEmpty())
    {
        qDebug() << processPath << "无法获取进程完整路径";
        return getDefaultIcon(processName);
    }

    SHFILEINFO sfi = {};
    if (SHGetFileInfo(reinterpret_cast<LPCWSTR>(processPath.utf16()),
                      FILE_ATTRIBUTE_NORMAL,
                      &sfi,
                      sizeof(SHFILEINFO),
                      SHGFI_ICON | SHGFI_LARGEICON | SHGFI_USEFILEATTRIBUTES))
    {
        if (sfi.hIcon)
        {
            QIcon icon = QtWin::fromHICON(sfi.hIcon);
            DestroyIcon(sfi.hIcon);
            if (!icon.isNull())
            {
                qDebug() << processPath << "通过SHGetFileInfo获取图标成功";
                return icon;
            }
        }
    }

    HICON hIcon =
        ExtractIconW(nullptr, reinterpret_cast<LPCWSTR>(processPath.utf16()), 0);
    if (hIcon)
    {
        QIcon icon = QtWin::fromHICON(hIcon);
        DestroyIcon(hIcon);
        if (!icon.isNull())
            return icon;
    }

    QFileInfo fileInfo(processPath);
    if (fileInfo.exists())
    {
        // 使用Qt的QFileIconProvider获取文件图标
        QFileIconProvider iconProvider;
        return iconProvider.icon(fileInfo);
    }
    qDebug() << processPath << "无法获取进程图标使用默认图标";

    return getDefaultIcon(processName);
}
    static QIcon getDefaultIcon(const QString& processName) {
    // 根据进程名称或类型提供更有针对性的默认图标
    if (processName != "")
    {
        // 使用SHGetFileInfo获取.exe文件的图标
        SHFILEINFO sfi = {};
        QIcon icon;
        if (SHGetFileInfo(reinterpret_cast<LPCWSTR>(processName.utf16()),
                          FILE_ATTRIBUTE_NORMAL,
                          &sfi,
                          sizeof(SHFILEINFO),
                          SHGFI_USEFILEATTRIBUTES | SHGFI_ICON |
                          SHGFI_SMALLICON))
        {
            // 将HICON转换为QIcon
            icon = QtWin::fromHICON(sfi.hIcon);

            // 释放图标资源
            DestroyIcon(sfi.hIcon);
        }
        return icon;
    }
    else
    {
        // 使用SHGetFileInfo获取.exe文件的图标
        SHFILEINFO sfi = {};
        QIcon icon;
        if (SHGetFileInfo(reinterpret_cast<LPCWSTR>(L".exe"),
                          FILE_ATTRIBUTE_NORMAL,
                          &sfi,
                          sizeof(SHFILEINFO),
                          SHGFI_USEFILEATTRIBUTES | SHGFI_ICON |
                          SHGFI_SMALLICON))
        {
            // 将HICON转换为QIcon
            icon = QtWin::fromHICON(sfi.hIcon);

            // 释放图标资源
            DestroyIcon(sfi.hIcon);
        }
        return icon;
    }
}
    QIcon getProcessIconCached(DWORD proccessId) {
    QString processPath = winutils::getProcessPath(processId);
    if (m_iconCache.contains(processPath))
    {
        return m_iconCache[processPath];
    }

    QIcon icon = getProcessIcon(processPath);
    m_iconCache.insert(processPath, icon);
    return icon;
}
  public:
};

This code segment functions to: Collect memory utilization metrics and system architecture details from active processes while determining their execution priority levels for comprehensive process monitoring purposes.

```cpp
[TASK_BEGIN]
        if (hProcess)
        {
            PROCESS_MEMORY_COUNTERS pmc;
            if (GetProcessMemoryInfo(hProcess, &pmc, sizeof(pmc)))
            {
                info.memoryUsage = pmc.WorkingSetSize;
            }

            DWORD priority = GetPriorityClass(hProcess);
            switch (priority)
            {
            case REALTIME_PRIORITY_CLASS:
                info.priority = "Realtime";
                break;
            case HIGH_PRIORITY_CLASS:
                info.priority = "High";
                break;
            case ABOVE_NORMAL_PRIORITY_CLASS:
                info.priority = "Above Normal";
                break;
            case NORMAL_PRIORITY_CLASS:
                info.priority = "Normal";
                break;
            case BELOW_NORMAL_PRIORITY_CLASS:
                info.priority = "Below Normal";
                break;
            case IDLE_PRIORITY_CLASS:
                info.priority = "Idle";
                break;
            default:
                info.priority = "Unknown";
            }

            CloseHandle(hProcess);
        }
[TASK_END]
```