Get process memory usage

Submitted by:Jhon Smith

Date added:02 March, 2014

Category:Delphi

Delphi code example to get process memory usage

Tags: get memory , process memory

Code Snippet:

    function GetProcessMemorySize(sProcessName: string; var nMemSize: Cardinal): Boolean;
var
l_nWndHandle, l_nProcID, l_nTmpHandle: HWND;
l_pPMC: PPROCESS_MEMORY_COUNTERS;
l_pPMCSize: Cardinal;
begin
l_nWndHandle := FindWindow(nil, PChar(sProcessName));
if l_nWndHandle = 0 then
begin
Result := False;
Exit;
end;
l_pPMCSize := SizeOf(PROCESS_MEMORY_COUNTERS);
GetMem(l_pPMC, l_pPMCSize);
l_pPMC^.cb := l_pPMCSize;
GetWindowThreadProcessId(l_nWndHandle, @l_nProcID);
l_nTmpHandle := OpenProcess(PROCESS_ALL_ACCESS, False, l_nProcID);
if (GetProcessMemoryInfo(l_nTmpHandle, l_pPMC, l_pPMCSize)) then
nMemSize := l_pPMC^.WorkingSetSize
else
nMemSize := 0;
FreeMem(l_pPMC);
CloseHandle(l_nTmpHandle);
Result := True;
end;

function GetCurrentProcessMemorySize(var nMemSize: Cardinal): Boolean;
var
nWndHandle, nProcID, nTmpHandle: HWND;
pPMC: PPROCESS_MEMORY_COUNTERS;
pPMCSize: Cardinal;
begin
nWndHandle := Application.Handle;
if nWndHandle = 0 then
begin
Result := False;
Exit;
end;
pPMCSize := SizeOf(PROCESS_MEMORY_COUNTERS);
GetMem(pPMC, pPMCSize);
pPMC^.cb := pPMCSize;
GetWindowThreadProcessId(nWndHandle, @nProcID);
nTmpHandle := OpenProcess(PROCESS_ALL_ACCESS, False, nProcID);
if (GetProcessMemoryInfo(nTmpHandle, pPMC, pPMCSize)) then
nMemSize := pPMC^.WorkingSetSize
else
nMemSize := 0;
FreeMem(pPMC);
CloseHandle(nTmpHandle);
Result := True;
end;
 
 

Comments