Need help with getting the current memory on a program
I need to get the up to date memory useage of a program that is running. i googled it and found GetProcessMemoryInfo this looks like what i needed but i can't get it to work. It wont take the handle i find for the window and i am not really sure what they want.
#include <iostream>
#include <Windows.h>
#include <tchar.h>
#include <Psapi.h>
using namespace std;
int main()
{
HANDLE hwnd = FindWindow(NULL,TEXT("Calculator"));
PPROCESS_MEMORY_COUNTERS ppsmemCounters;
DWORD cb;
BOOL WINAPI GetProcessMemoryInfo(hwnd, ppsmemCounters, cb);
return 0开发者_StackOverflow社区;
}
I am just trying to find the window's calculator for now. One of the errors i get is Error:a value of type "HANDLE" cannot be used to initialize an entity type "BOOL". Another is "error C2078: too many initializers". I am using VC++ 2010, and my os is Windows 7.
GetProcessMemoryInfo
takes a process handle, not a window handle. After you find the window, you can call GetWindowThreadProcesId
to the process ID, then OpenProcess
to get a handle to the process. Then you can finally call GetProcessMemoryInfo
for that handle.
When you do call it, you don't need the BOOL WINAPI
at the beginning. You normally want to assign the return value so you can check whether it succeeded, something like:
bool succeded = GetProcessMemoryInfo(process, /* ... */);
Edit: here's a really simplistic demo:
#include <windows.h>
#include <psapi.h>
#include <iostream>
int main(int argc, char **argv) {
HWND window = FindWindow(NULL, argv[1]);
DWORD id;
GetWindowThreadProcessId(window, &id);
HANDLE process = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, false, id);
PROCESS_MEMORY_COUNTERS info = {0};
info.cb = sizeof(info);
GetProcessMemoryInfo(process, &info, sizeof(info));
std::cout << info.WorkingSetSize;
return 0;
}
精彩评论