简体   繁体   English

进程ID函数得到错误“ ERROR_NO_MORE_FILES”

[英]Process ID function getting error “ERROR_NO_MORE_FILES”

Im trying to get the ID from a process using the function below, however GetLastError keeps returning ERROR_NO_MORE_FILES so it never gets the chance to iterate through all the processes. 我试图使用下面的函数从进程中获取ID,但是GetLastError始终返回ERROR_NO_MORE_FILES,因此它永远不会获得遍历所有进程的机会。 Im not sure whats causing this. 我不确定是什么原因造成的。 Any ideas? 有任何想法吗? Also as a test i was passing in the param as "notepad.exe" 同样作为测试,我将参数传递为“ notepad.exe”

int GetProcID(string ProcName){
    PROCESSENTRY32 PE32;
    HANDLE ProcSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);

    PE32.dwSize = sizeof(PROCESSENTRY32);

    if(!Process32First(ProcSnapshot,&PE32))
        return 0;
    else
        if(PE32.szExeFile == ProcName)
            return PE32.th32ProcessID;
        else
        {
            while(GetLastError() != ERROR_NO_MORE_FILES){
                Process32Next(ProcSnapshot,&PE32);
                    if(PE32.szExeFile == ProcName)
                        return PE32.th32ProcessID;
            }
            return 0;
        }
}

Your while loop is wrong. 您的while循环错误。 You shouldn't be checking for the error value even before calling Process32Next function. 即使在调用Process32Next函数之前,您也不应该检查错误值。 Your function will return without doing anything if the prior call to a Windows API function (probably another Process32Next function) returned ERROR_NO_MORE_FILES , and the name of the first process in the snapshot happens to be something other than the name you want to search for. 如果先前对Windows API函数(可能是另一个Process32Next函数)的调用返回ERROR_NO_MORE_FILES ,并且快照中第一个进程的名称恰巧不是您要搜索的名称,则您的函数将不执行任何操作而返回。

Keep in mind that not all API functions set the error code to ERROR_SUCCESS even they have succeeded (and also don't forget to close the snapshot handle after you're done with it). 请记住,即使它们成功执行,并非所有API函数都将错误代码设置为ERROR_SUCCESS (并且不要忘记在完成快照操作后将其关闭)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM