C ++,获取打开进程的句柄

时间:2015-02-14 06:22:04

标签: c++ winapi handle

我试图了解我的开放流程,这就是我所拥有的:

#include "stdafx.h"
#include <Psapi.h>

using namespace std;

BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam);

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pCmdLine, int iCmdShow)
{
    bool _result;
    DWORD *pProcessIds = new DWORD[1000];
    DWORD cb;
    DWORD *pBytesReturned= new DWORD[1000];
    _result =  EnumProcesses(pProcessIds, 1000,pBytesReturned);

    HANDLE _Proccess = new HANDLE;

    for (int i = 0;i<=1000; i++)
    {
        _Proccess =   OpenProcess(READ_CONTROL,  false, *pProcessIds);
        DWORD error;
        error = GetLastError(); 
        CloseHandle(_Proccess);
        pProcessIds ++;
    }
    return 0;
}

1-我一直在犯错误&#34; 87&#34;。

2- _Proccess也未被分配任何内容。在每次迭代时,它被设置为&#34; 0x00000000&#34;。

3- EnumProcess正常运行,因为pBytesReturned会返回一个数字。

任何想法?

1 个答案:

答案 0 :(得分:0)

确保您以管理员身份运行

for (int i = 0;i<=1000; i++) 是错误的,因为您缺少最后一次迭代,请将<=更改为<

DWORD *pBytesReturned= new DWORD[1000]; 只能是DWORD bytesToReturn而不是此动态数组,因为您只需要整数返回即可。

EnumProcesses(pProcessIds, 1000,pBytesReturned); 而不是硬编码1000,请使用sizeof(array)

MSDN上有tutorial,说明如何正确执行此操作。

我修改了代码以执行您想要的操作并对其进行了测试:

int main(void)
{
    DWORD aProcesses[1024], cbNeeded, cProcesses;
    unsigned int i;

    if (!EnumProcesses(aProcesses, sizeof(aProcesses), &cbNeeded))
    {
        return 1;
    }

    // Calculate how many process identifiers were returned.
    cProcesses = cbNeeded / sizeof(DWORD);

    // Print the name and process identifier for each process.
    for (i = 0; i < cProcesses; i++)
    {
        if (aProcesses[i] != 0)
        {
            HANDLE hProc = OpenProcess(PROCESS_ALL_ACCESS, false, aProcesses[i]);
            CloseHandle(hProc);
        }
    }

    return 0;
}