IsProcessRunning函数始终返回false

时间:2016-04-20 16:21:42

标签: c++ windows

IsProcessRunning总是返回false,为什么?记事本是100%运行!我甚至尝试了内置版本但仍然没有工作......奇怪的是,我无法通过Google找到解决方案:/

    #include <iostream>
    #include <cstdio>
    #include <windows.h>
    #include <tlhelp32.h>

    using namespace std;

    bool IsProcessRunning(const wchar_t *processName)
    {
        bool exists = false;
        PROCESSENTRY32 entry;
        entry.dwSize = sizeof(PROCESSENTRY32);

        HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);

        if (Process32First(snapshot, &entry))
            while (Process32Next(snapshot, &entry))
                if (!wcsicmp(entry.szExeFile, processName))
                    exists = true;

        CloseHandle(snapshot);
        return exists;
    }

    int main()
    {
        if(IsProcessRunning(L"notepad"))
        {
            cout << "Notepad running!";
        }
        else
        {
        cout << "Notepad not running!";
        }
        cin.get();
        return 0;
    }

1 个答案:

答案 0 :(得分:1)

应为“Notepad.exe”

#include <iostream>
#include <cstdio>
#include <windows.h>
#include <tlhelp32.h>

using namespace std;

bool IsProcessRunning(const wchar_t* processName) {
    bool exists = false;
    PROCESSENTRY32 entry;
    entry.dwSize = sizeof(PROCESSENTRY32);

    HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);

    if (Process32First(snapshot, &entry))
        while (Process32Next(snapshot, &entry)) {

            wcout << entry.szExeFile << endl;

            if (!wcsicmp(entry.szExeFile, processName))
                exists = true;
        }

    CloseHandle(snapshot);
    return exists;
}

int main() {
    if (IsProcessRunning(L"notepad.exe")) {
        cout << "Notepad running!";
    } else {
        cout << "Notepad not running!";
    }
    cin.get();
    return 0;
}