(C#,WMI)托盘应用程序显示CPU Temp仅在SpeedFan App运行时更新值

时间:2016-04-22 07:13:04

标签: c# timer wmi temp trayicon

我制作了一个简单的托盘应用程序,显示CPU温度,并使用计时器每秒更新。

托盘图标显示从ManagementObjectSearcher查询中检索到的“CurrentTemperature”参数,该参数随后用于创建显示温度值的位图。

它似乎工作得很好,除了始终检索完全相同的温度值这一事实。但是,如果我在后台运行SpeedFan,则温度会相应更新

有人能否让我深入了解应用程序无法自行检索更新的温度值的原因?

注意:我已经检查了我的机器的BIOS并且没有温度读数

我正在为任何有兴趣/愿意提供建议的人附上代码

class Program
{
    private static System.Timers.Timer tmr;
    private static ContextMenu CMenu;
    private static NotifyIcon trayIcon;
    private static Color c;
    private static int Temp;
    private static int _Temp;

    private static void Main(string[] args)
    {
        tmr = new System.Timers.Timer();
        trayIcon = new NotifyIcon();
        CMenu = new ContextMenu();

        //ContextMenu
        CMenu.MenuItems.Add("Exit", Exit_Application);

        //trayIcon
        trayIcon.ContextMenu = CMenu;
        trayIcon.Visible = true;

        //Timer
        tmr.Interval = 1000;
        tmr.Elapsed += new ElapsedEventHandler(onTimerTick);
        tmr.Enabled = true;

        Temp = 0;
        Application.Run();
    }
    private static void Exit_Application(object Sender, EventArgs e) { trayIcon.Icon = null; Application.Exit(); }

    private static void onTimerTick(object Sender, ElapsedEventArgs e)
    {
        using (ManagementObjectSearcher mos = new ManagementObjectSearcher("root\\WMI", "SELECT * FROM MSAcpi_ThermalZoneTemperature"))
        {
            using (ManagementObject mo = mos.Get().OfType<ManagementObject>().First())
            {
                _Temp = int.Parse(mo["CurrentTemperature"].ToString()) / 10 - 273; //Convert To Celsius
                if (_Temp != Temp)
                {
                    Temp = _Temp;
                    trayIcon.Icon = CreateIcon(Temp);
                }
                if (Temp >= 85) { Console.Beep(); }
            }
        }  
    }
    private static Icon CreateIcon(int value)
    {
        if (value < 50) { c = Color.FromArgb(0, 255, 0); }
        else if (value >= 80){ c = Color.OrangeRed; }
        else { c = Color.Yellow; }

        using (Bitmap bm = new Bitmap(16, 16))
        {
            using (Graphics g = Graphics.FromImage(bm))
            {
                using (Brush b = new SolidBrush(c))
                {
                    g.DrawString(value.ToString(), SystemFonts.DefaultFont, b, 0, 0);
                    return Icon.FromHandle(bm.GetHicon());
                } 
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

经过进一步研究后,看来WMI无法读取CPU温度,我找到了解释Here