如何修复调用 Process32First() 时"The program issued a command but the command length is incorrect."错误?

How do I fix "The program issued a command but the command length is incorrect." error when calling Process32First()?

本文关键字:command the but length is 错误 incorrect program Process32First 调用 何修复      更新时间:2023-10-16

GetLastError 告诉我在调用 Process32First() 时收到"程序发出命令但命令长度不正确"错误(请参阅下面的代码)。 我发现了一个看起来很有帮助的帖子(http://social.msdn.microsoft.com/Forums/is/vcgeneral/thread/6f43716f-fdd3-4c92-bfba-6a23178c32bf),但我不确定这是否是我的问题。

我尝试构建一个只包含"stdafx.h"<iostream><Windows.h><TlHelp32.h>的程序来测试__alignof(PROCESSENTRY32),但我仍然得到一个值4。 不确定这是否正确。

以下是失败的代码:

HANDLE hProcess;
PROCESSENTRY32 pe32;
cout << "Size of PROCESSENTRY32 is: " << sizeof(PROCESSENTRY32) << "rn"; // 556
cout << "Align of PROCESSENTRY32 is: " << __alignof(PROCESSENTRY32) << "rn"; // 4
if ( !(hProcess = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)) ) {
    cout << "CreateToolhelp32Snapshot() failed: " << GetLastError() << "rn";
    return (HANDLE)NULL;
} else {
    cout << "CreateToolhelp32Snapshot() succeeded.rn";
}
if (Process32First(hProcess, &pe32)) {
    do {
        cout << pe32.th32ModuleID;
    } while (Process32Next(hProcess, &pe32));
} else {
    cout << "Process32First() failed: " << GetLastError() << "rn";
}

来自 Process32First 上的文档:

调用应用程序必须将 PROCESSENTRY32 的 dwSize 成员设置为结构的大小(以字节为单位)。

我没有看到你在代码中这样做,我怀疑这是问题所在。修复它:

pe32.dwSize = sizeof pe32;
if (Process32First(...))

对于许多 winapi 结构,此强制操作背后的原因是,以后可以灵活地向结构中添加更多内容,但通过检查以前版本的已知大小,让函数知道正在使用哪个版本。

相关文章: