0

我用这个函数创建了一个新类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Management;

namespace ScreenVideoRecorder
{
    class GetMemory
    {
        private static void DisplayTotalRam()
        {
            string Query = "SELECT MaxCapacity FROM Win32_PhysicalMemoryArray";
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(Query);
            foreach (ManagementObject WniPART in searcher.Get())
            {
                UInt32 SizeinKB = Convert.ToUInt32(WniPART.Properties["MaxCapacity"].Value);
                UInt32 SizeinMB = SizeinKB / 1024;
                UInt32 SizeinGB = SizeinMB / 1024;
                //Console.WriteLine("Size in KB: {0}, Size in MB: {1}, Size in GB: {2}", SizeinKB, SizeinMB, SizeinGB);
            }
        }
    }
}

我想在 Form1 中在标签上显示 SizeinKB MB 和 GB。

4

2 回答 2

3

编辑

由于从 KB 到 MB / GB 的转换是标准的,因此可以将其移出此函数,因此我只返回 UInt32 列表,因为您没有显示任何其他信息来区分数字:

private static void DisplayTotalRam()
{
    string Query = "SELECT MaxCapacity FROM Win32_PhysicalMemoryArray";

    List<Uint32> sizes = new List<UInt32>();

    ManagementObjectSearcher searcher = new ManagementObjectSearcher(Query);
    foreach (ManagementObject WniPART in searcher.Get())
    {
        UInt32 SizeinKB = Convert.ToUInt32(WniPART.Properties["MaxCapacity"].Value);
        sizes.Add(SizeinKB);
    }
    return sizes;
}

然后只需按以下表格进行计算:

List<UInt32> sizes = GetMeMory.DisplayTotalRam();
foreach(UInt32 sizeInKB in sizes)
{
   // show sizeInKB on label

   UInt32 sizeInMB = sizeInKB / 1024;
   // show sizeInMB on label

   // ..etc.
}

做这件事有很多种方法; 两种更简单的方法是:

  1. 返回包含这些值的结构或类的实例(干净,必须定义类,结构)
  2. 返回一个数组Int32s(简单,不干净)
于 2013-06-10T21:51:04.967 回答
0

您可以将字符串参数添加到方法中:

DisplayTotalRam(ref String one, ref String two)

并在方法中使用它们。因此,如果您有 2 个要设置文本的标签,请编写:

DisplayTotalRam(ref label1.Text, ref label2.Text);
于 2013-06-10T21:53:00.373 回答