获取WinXP及以上版本的总内存量

本文关键字:内存 版本 WinXP 获取 | 更新日期: 2023-09-27 18:15:05

关于这个话题已经有很多答案,但是是否有一种方法可以获得XP及以上windows系统(包括windows Server 2003)的总内存量?

我发现了什么:

Win32_LogicalMemoryConfiguration(弃用)

Win32_ComputerSystem(最低支持客户端:Vista)

Microsoft.VisualBasic.Devices。ComputerInfo(根据平台不支持XP)

thx

获取WinXP及以上版本的总内存量

Microsoft.VisualBasic

添加引用
  var info = new Microsoft.VisualBasic.Devices.ComputerInfo();
  Debug.WriteLine(info.TotalPhysicalMemory);
  Debug.WriteLine(info.AvailablePhysicalMemory);
  Debug.WriteLine(info.TotalVirtualMemory);
  Debug.WriteLine(info.AvailableVirtualMemory);

编辑:我如何在c#中获得总物理内存?


您可以使用GlobalMemoryStatusEx:示例这里

private void DisplayMemory()
{
    // Consumer of the NativeMethods class shown below
    long tm = System.GC.GetTotalMemory(true);
    NativeMethods oMemoryInfo = new NativeMethods();
    this.lblMemoryLoadNumber.Text = oMemoryInfo.MemoryLoad.ToString();
    this.lblIsMemoryTight.Text = oMemoryInfo.isMemoryTight().ToString();
    if (oMemoryInfo.isMemoryTight())
        this.lblIsMemoryTight.Text.Font.Bold = true;
    else
        this.lblIsMemoryTight.Text.Font.Bold = false;
}

本机类包装器。

[CLSCompliant(false)]
public class NativeMethods {
     private     MEMORYSTATUSEX msex;
     private uint _MemoryLoad;
     const int MEMORY_TIGHT_CONST = 80;
     public bool isMemoryTight()
      {
         if (_MemoryLoad > MEMORY_TIGHT_CONST )
            return true;
          else
             return false;
     }
          public uint MemoryLoad
     {
        get { return _MemoryLoad; }
         internal set { _MemoryLoad = value; }
      }
       public NativeMethods() {
        msex = new MEMORYSTATUSEX();
        if (GlobalMemoryStatusEx(msex)) {
                  _MemoryLoad = msex.dwMemoryLoad;
             //etc.. Repeat for other structure members        
        }
            else
             // Use a more appropriate Exception Type. 'Exception' should almost never be thrown
             throw new Exception("Unable to initalize the GlobalMemoryStatusEx API");
    }
    [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
    private class MEMORYSTATUSEX
    {
              public uint dwLength;
        public uint dwMemoryLoad;
              public ulong ullTotalPhys;
              public ulong ullAvailPhys;
              public ulong ullTotalPageFile;
              public ulong ullAvailPageFile;
              public ulong ullTotalVirtual;
              public ulong ullAvailVirtual;
              public ulong ullAvailExtendedVirtual;
              public MEMORYSTATUSEX()
        {
                  this.dwLength = (uint) Marshal.SizeOf(typeof( MEMORYSTATUSEX ));
        }
    }

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