Speicherauslastung (MEMORYSTATUSEX) auslesen

// Aufruf:
//
// MemInfo.MEMORYSTATUSEX ms = MemInfo.CurrentMemoryStatus;
//
// uint uiMemoryLoad = ms.dwMemoryLoad;
// ulong ulTotalPhys = ms.ulTotalPhysical;
// ulong ulAvailPhys = ms.ulAvailPhysical;
// ulong ulTotalPageFile = ms.ulTotalPageFile;
// ulong ulAvailPageFile = ms.ulAvailPageFile;
// ulong ulTotalVirtual = ms.ulTotalVirtual;
// ulong ulAvailVirtual = ms.ulAvailVirtual;
// ulong ulAvailExtendedVirtual = ms.ulAvailExtendedVirtual;

using System.Runtime.InteropServices;

/// <summary>
/// freeware helper class for getting memory info
/// (W) 2011 by admin of codezentrale.de
/// http://pinvoke.net/default.aspx/kernel32/GlobalMemoryStatusEx.html
/// http://msdn.microsoft.com/en-us/library/aa366589%28v=vs.85%29.aspx
/// </summary>
public static class MemInfo
{
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
    public struct MEMORYSTATUSEX
    {
        public uint dwLength;
        public uint dwMemoryLoad;
        public ulong ulTotalPhysical;
        public ulong ulAvailPhysical;
        public ulong ulTotalPageFile;
        public ulong ulAvailPageFile;
        public ulong ulTotalVirtual;
        public ulong ulAvailVirtual;
        public ulong ulAvailExtendedVirtual;
    }

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool GlobalMemoryStatusEx(ref MEMORYSTATUSEX lpBuffer);

    /// <summary>
    /// get current memory status struct
    /// </summary>
    public static MEMORYSTATUSEX CurrentMemoryStatus
    {
        get
        {
            MEMORYSTATUSEX ms = new MEMORYSTATUSEX();
            ms.dwLength = (uint)Marshal.SizeOf(typeof(MEMORYSTATUSEX));

            GlobalMemoryStatusEx(ref ms);

            return ms;
        }
    }
}