C++, Get handle to open process

0

I'm trying to get a handle to my open processes, this is what I've got:

#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- I am constanly getting error "87".

2- _Proccess isn't being assigned anything either. On every itertaion its being set at "0x00000000".

3- EnumProcess is working correctly because pBytesReturned returns a number.

Any Ideas?

c++
winapi
handle
asked on Stack Overflow Feb 14, 2015 by Pedrumj

1 Answer

0

Make sure you run as administrator

for (int i = 0;i<=1000; i++) is wrong because you are missing the last iteration, change <= to <

DWORD *pBytesReturned= new DWORD[1000]; This can just be DWORD bytesToReturn instead of this dynamic array because you only need an integer return.

EnumProcesses(pProcessIds, 1000,pBytesReturned); Instead of hardcoding 1000, use sizeof(array)

MSDN has a tutorial on how to do this properly.

I modified the code to do what you want it to do and tested it working:

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;
}
answered on Stack Overflow Mar 29, 2020 by GuidedHacking

User contributions licensed under CC BY-SA 3.0