how to dispay total memory usage in percentage most work on windows XP and 7 (.net2)
I have tried the following solutions without succes (crashes or freezes)
http://www.pinvoke.net/default.aspx/kernel32/GlobalMemoryStatusEx.html
and using
System.GC.GetTotalMemory(true);
working sample thank to Darin,
[System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
public class MEMORYSTATUSEX
{
public uint dwLength = (uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(MEMORYSTATUSEX));
public uint dwMemoryLoad;
public ulong ullTotalPhys;
public ulong ullAvailPhys;
public ulong ullTotalPageFile;
public ulong ullAvailPageFile;
public ulong ullTotalVirtual;
public ulong ullAvailVirtual;
public ulong ullAvailExtendedVirtual;
}
[System.Runtime.InteropServices.DllImport("kernel32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto, SetLastError = true)]
static extern bool GlobalMemoryStatusEx(MEMORYSTATUSEX lpBuffer);
private void timer1_Tick(object sender, EventArgs e)
{
var result = new MEMORYSTATUSEX();
if (GlobalMemoryStatusEx(result))
getpercentage(((double)result.ullTotalPhys - result.ullAvailPhys) / result.ullTotalPhys);
}
static void getpercentage(double ratio)
{
string usage = string.Format("usage {0:0%}", ratio);
Console.WriteLine(usage);
}
If you want to use the
GlobalMemoryStatusExmethod, here’s an example:Another possibility if you don’t like Interop is to use the ComputerInfo class (you just need to add reference to the
Microsoft.VisualBasicassembly):And yet another possibility is to query the performance counters to find out the available memory: