【问题标题】:How do i compare a given process name to a process name found from a snap shot?如何将给定的进程名称与从快照中找到的进程名称进行比较?
【发布时间】:2021-09-16 14:46:21
【问题描述】:
if ((WCHAR*)procName == procEntry32.szExeFile)

这就是我所拥有的,我被告知要使用“strcmp”,但它似乎从来没有工作过。有人可以解释为什么吗?或者给我另一个解决方案?

bool attachProc(char* procName)
{
    PROCESSENTRY32 procEntry32;
    //_bstr_t procEntry32Char(procEntry32);

    // defining the size for populating it
    procEntry32.dwSize = sizeof(PROCESSENTRY32);

    //getting the list of all the processes 
    auto hProcSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);

    std::cout << procEntry32.szExeFile;

    if (hProcSnap == INVALID_HANDLE_VALUE)
    {
        std::cout << "Failed To Take Snapshot Of Processes!" << std::endl;
        return false;
    }

    Process32First(hProcSnap, &procEntry32);

    while (Process32Next(hProcSnap, &procEntry32))
    {

        std::wcout << "Proc: " << procEntry32.szExeFile << std::endl;

        int correct = (procEntry32.szExeFile == (WCHAR*)procName);

        if (correct == 1)
        {
            //std::cout << "\nThe Program Was Found!\n";
        }
        else {
            //std::cout << "\nThe Program Was Not Found!\n";
        }

        std::cout << ((WCHAR*)procName == procEntry32.szExeFile);
        std::cout << "\nBoth:\n" << (WCHAR*)procName << "\n" << procEntry32.szExeFile << "\n\n";
        if ((WCHAR*)procName == procEntry32.szExeFile)
        {
            std::cout << "Found Process " << procEntry32.szExeFile << " with process ID: " << procEntry32.th32ProcessID << std::endl;

            hProc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, procEntry32.th32ProcessID);

            pID = procEntry32.th32ProcessID;

            if (hProc == NULL)
            {
                std::cout << "Failed getting handle to process." << std::endl;
            }

            CloseHandle(hProcSnap);

            return true;
        }

    }

    std::cout << procEntry32.szExeFile;

    std::cout << "Couldn't find " << procName << " in the process snapshot!" << std::endl;
    CloseHandle(hProcSnap);

    return false;
}

这里是剩下的功能,我是初学者,很抱歉有不好的做法!

【问题讨论】:

  • 首先你不能通过强制转换将窄字符串转换为宽字符串。其次,== 比较两个 指针 而不是它们可能指向的字符串。我建议你退后几步,get a couple of decent C++ books,首先学习基础知识(比如为什么== 在这里不起作用)。

标签: c++ process strcmp wchar


【解决方案1】:

您似乎正在使用 Win32 API 函数的宽字符串 Unicode 版本(否则,为什么要将 procName 转换为 WCHAR*?),但您的 procName 是窄 ANSI 字符串。因此,您需要:

  1. 更改您的代码以使用窄字符串 ANSI API 函数,然后您可以使用 strcmp() 进行比较。

  2. 将您的procName 参数更改为(const) wchar_t* 而不是char*,然后您可以使用wcscmp()(或等效项)进行比较。

  3. 与 #2 相同,除非您无法在编译时更改 procName 的类型,然后在运行时使用 MultiByteToWideChar()(或等效项)将您的 procName 转换为 wchar_t*

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-14
    • 1970-01-01
    相关资源
    最近更新 更多