如何将变量发送回Form1?

时间:2013-06-10 21:46:32

标签: c# winforms

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

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。

2 个答案:

答案 0 :(得分: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. 返回包含这些值的结构或类的实例(clean,必须定义类,struct)
  2. 返回Int32s(简单,不干净)
  3. 的数组

答案 1 :(得分:0)

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

DisplayTotalRam(ref String one, ref String two)

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

DisplayTotalRam(ref label1.Text, ref label2.Text);