2013-03-09 124 views
-4

我有这个类:如何在静态方法上使用invoke?

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using OpenHardwareMonitor.Hardware; 
using System.Diagnostics; 
using System.Management; 
using System.Windows.Forms; 
using DannyGeneral; 

namespace HardwareMonitoring 
{ 
    class Hardware 
    { 
     public static Form1 form1; 
     public static CpuTemperature settings; 
     public static ManagementObjectSearcher searcher; 

     public Hardware(Form1 f1) 
     { 
      form1 = f1; 

      settings = new CpuTemperature(new Dictionary<string, string> 
      { 
       { "/intelcpu/0/temperature/0/values", "H4sIAAAAAAAEAOy9B2AcSZYlJi9tynt/SvVK1+B0oQiAYBMk2JBAEOzBiM3mkuwdaUcjKasqgcplVmVdZhZAzO2dvPfee++999577733ujudTif33/8/XGZkAWz2zkrayZ4hgKrIHz9+fB8/Iu6//MH37x79i9/+NX6N3/TJm9/5f/01fw1+fosnv+A/+OlfS37/jZ/s/Lpv9fff6Ml/NTef/yZPnozc5679b+i193//TQZ+/w2Dd+P9/sZeX/67v/GTf/b3iP3u4/ObBL//73+i+f039+D8Zk/+xz/e/P6beu2TQZju8yH8f6OgzcvPv/U3/Rb8+z/0f/9b/+yfaOn8079X6fr6Cws7ln/iHzNwflPv99/wyS/+xY4+v/evcJ+733+jJ5//Cw7/4ndy9Im3+U2e/Fbnrk31C93vrt/fyPvdb+N//hsF7/4/AQAA//9NLZZ8WAIAAA==" }, 
       { "/intelcpu/0/load/0/values", "H4sIAAAAAAAEAOy9B2AcSZYlJi9tynt/SvVK1+B0oQiAYBMk2JBAEOzBiM3mkuwdaUcjKasqgcplVmVdZhZAzO2dvPfee++999577733ujudTif33/8/XGZkAWz2zkrayZ4hgKrIHz9+fB8/Iu6//MH37x79i9++mpwcv/md/9df89egZ/xX/ym/5y/4D37618Lv7ya//u+58+u+5d9/z7/5t/w9/6u5fP5bH/6av+eTkXyefXxp26ONaf/v/dG/sf39D/rvnv4e5vc/0IP56/waK/vuHzf5I38P8/tv+mv8Rbb9f0pwTF9/zr/1X9vP/8I//+/6Pf7Z30N+/zdf/HX29zd/859q4aCNP5b//U+U3/+7f+zXOjZwfqvDX/V7/o9/vPz+a1G/pv0f+fGlhfk7eZ//N3/0v28//5X0u/n8Cxq7+f1X/tHft20A5x8a/W5/02+BP36Nf+j/nv8XfzrT+c2//Ob4p3+vktvUhNs/+xcWikP6e/4T/5jS5M8/sL8vP/5ff49f/Ivl9//sHzv6PX/vXyG//9R/94/9HuZ34P/5vyC//3W/5e/1exa/k+Bw4bUBnU2bP4Xg/1bn0uafeTH6PatfKL//N3/0t2y/gG9+/8+IzqYNxmU+/+jwX7afY67/nwAAAP//GYSA31gCAAA=" }, 
      }); 
      searcher = new ManagementObjectSearcher("SELECT * FROM Win32_DisplayConfiguration"); 
      videoCardType("ati", "nvidia", f1.lb4()); 
     } 

     public static void cpuView(bool pauseContinue, List<string> myData, ListBox lb1, Button bt1, float? tempcpuv) 
     { 
      if (pauseContinue == true) 
      { 
      } 
      else 
      { 
       Computer myComputer = new Computer(); 
       myComputer = new Computer(settings) { CPUEnabled = true }; 

       myComputer.Open(); 
       Trace.WriteLine(""); 
       foreach (var hardwareItem in myComputer.Hardware) 
       { 
        if (hardwareItem.HardwareType == HardwareType.CPU) 
        { 
         hardwareItem.Update(); 
         foreach (IHardware subHardware in hardwareItem.SubHardware) 
          subHardware.Update(); 

         foreach (var sensor in hardwareItem.Sensors) 
         { 
          settings.SetValue("sensor", sensor.Value.ToString()); 
          if (sensor.SensorType == SensorType.Temperature) 
          { 
           sensor.Hardware.Update(); 
           settings.GetValue("sensor", sensor.Value.ToString()); 
           //label17.Text = sensor.Value.ToString() + "c";//String.Format("{0} Temperature = {1}c", sensor.Name, sensor.Value.HasValue ? sensor.Value.Value.ToString() : "no value"); 

           myData.Add("Cpu Temeprature --- " + sensor.Value.ToString()); 
           lb1.DataSource = null; 

           tempcpuv = sensor.Value; 
           if (sensor.Value > 60) 
           { 
            Logger.Write("The Current CPU Temperature Is ===> " + sensor.Value); 
            bt1.Enabled = true; 
           } 

           break; 
          } 
         } 
        } 
       } 
      } 
     } 

     public static void gpuView(bool pauseContinue, List<string> myData, ListBox lb1, Button bt1, float? tempgpuv, Label lb4) 
     { 

      if (pauseContinue == true) 
      { 
      } 
      else 
      { 
       Computer computer = new Computer(); 
       computer.Open(); 
       computer.GPUEnabled = true; 

       foreach (var hardwareItem in computer.Hardware) 
       { 
        if (videoCardType("ati", "nvidia",lb4) == true) 
        { 
         HardwareType htype = HardwareType.GpuNvidia; 

         if (hardwareItem.HardwareType == htype) 
         { 

          foreach (var sensor in hardwareItem.Sensors) 
          { 

           if (sensor.SensorType == SensorType.Temperature) 
           { 

            sensor.Hardware.Update(); 
            if (sensor.Value.ToString().Length > 0) 
            { 

             /* else if (UpdatingLabel(sensor.Value.ToString(), label16.Text.Substring(0, label16.Text.Length - 1))) 
             { 
              // Label8 = GpuText; 
             }*/ 
             //myData = new List<string>(); 
             this.Invoke(new Action(() => myData.Add("Gpu Temeprature --- " + sensor.Value.ToString()))); 
             lb1.DataSource = null; 
             //sensor.Value.ToString() + "c"; 
             tempgpuv = sensor.Value; 
             //label8.Visible = true; 
            } 
            if (sensor.Value > 60) 
            { 
             Logger.Write("The Current Nvidia GPU Temperature Is ===> " + sensor.Value); 
             bt1.Enabled = true; 
            } 
            //form1.Select(); 
           } 
          } 
         } 
        } 
        else 
        { 
         HardwareType htype = HardwareType.GpuAti; 

         if (hardwareItem.HardwareType == htype) 
         { 

          foreach (var sensor in hardwareItem.Sensors) 
          { 

           if (sensor.SensorType == SensorType.Temperature) 
           { 

            sensor.Hardware.Update(); 
            if (sensor.Value.ToString().Length > 0) 
            { 

             tempgpuv = sensor.Value; 
             //label8.Visible = true; 
            } 
            if (sensor.Value > 60) 
            { 
             Logger.Write("The Current Ati GPU Temperature Is ===> " + sensor.Value); // to check when writing to the log each second its writing the snesor value a lot of time in gpu and cpu 
             // to check why to make that it will write every second or every n times once. and not a lot of times maybe to change the logger write place not in loop ? 
             bt1.Enabled = true; 
            } 
            form1.Select(); 
           } 
          } 
         } 
        } 
       } 
      } 
     } 

     public static bool videoCardType(string ati , string nvidia, Label lb4) 
     { 
      bool atiNvidia = false; 
      string graphicsCard = string.Empty; 
      foreach (ManagementObject mo in searcher.Get()) 
      { 
       foreach (PropertyData property in mo.Properties) 
       { 
        if (property.Name == "Description") 
        { 
         graphicsCard = property.Value.ToString(); 
        } 
       } 
      } 

      if (graphicsCard.Contains("NVIDIA") || graphicsCard.Contains("nvidia")) 
      { 
       atiNvidia = true; 
       string toPrintNvidia = nvidia; 
       if (graphicsCard.ToUpper().Contains(toPrintNvidia.ToUpper())) 
       { 
        int startingIndex = graphicsCard.ToUpper().IndexOf(toPrintNvidia.ToUpper()); 
        graphicsCard = graphicsCard.Substring(startingIndex, toPrintNvidia.Length); 
       } 

       lb4.Text = graphicsCard; 
       return atiNvidia; 
      } 
      if (graphicsCard.Contains("ATI") || graphicsCard.Contains("ati")) 
      { 
       atiNvidia = false; 
       string toPrintAti = ati; 
       if (graphicsCard.ToUpper().Contains(toPrintAti.ToUpper())) 
       { 
        int startingIndex = graphicsCard.ToUpper().IndexOf(toPrintAti.ToUpper()); 
        graphicsCard = graphicsCard.Substring(startingIndex, toPrintAti.Length); 
       } 

       lb4.Text = graphicsCard; 
       return atiNvidia; 
      } 

      return atiNvidia; 
     } 
    } 
} 

类的,我有这个方法/函数内部:

公共静态无效gpuView

而且在这个方法中,我有这行至极我想要调用:

this.Invoke(new Action(() => myData.Add("Gpu Temeprature --- " + sensor.Value.ToString()))); 

但在这个即时得到错误:

Error 1 Keyword 'this' is not valid in a static property, static method, or static field initializer

如果我删除静态只能使则函数公共IM才能上调用错误:

Error 1 'HardwareMonitoring.Hardware' does not contain a definition for 'Invoke' and no extension method 'Invoke' accepting a first argument of type 'HardwareMonitoring.Hardware' could be found (are you missing a using directive or an assembly reference?)

而且

Error 2 An object reference is required for the non-static field, method, or property 'HardwareMonitoring.Hardware.gpuView(bool, System.Collections.Generic.List, System.Windows.Forms.ListBox, System.Windows.Forms.Button, float?, System.Windows.Forms.Label)'

DoWork的事件:

私人无效backgroundWorker1_DoWork(对象发送者,DoWorkEventArgs e) {BackgroundWorker worker = sender作为BackgroundWorker; ((worker.CancellationPending == true)) while(true) { e.Cancel = true; 休息; } 别的 { 如果(tempCpuValue> =(浮动)nud1.Value || tempGpuValue> =(浮动)nud1.Value?) { soundPlay = TRUE; blinking_label(); NudgeMe(); } else { soundPlay = false; stop_alarm = true;

   } 
       data = new List<string>(); 
       Hardware.cpuView(pauseContinueDoWork, data, listBox1, button1, tempCpuValue); 
       Hardware.gpuView(pauseContinueDoWork, data, listBox1, button1, tempGpuValue, label4); 
       listBox1.DataSource = data; 
       listBox1.Invalidate(); 

      } 

     } 
    } 

而且,这两个列表框事件:

private void listBox1_MeasureItem(object sender, MeasureItemEventArgs e) 
     { 
      e.ItemHeight = 21; 
     } 

     private void listBox1_DrawItem(object sender, DrawItemEventArgs e) 
     { 
      if (e.Index == -1) 
      { 
      } 
      else 
      { 

       ColorText.ColorListBox(data, e); 

      } 
     } 

而且ColorText类:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Drawing; 
using System.Windows.Forms; 

namespace GatherLinks 
{ 
    class ColorText 
    { 


     public static void Texts(RichTextBox box, string text, Color color) 
     { 
      box.SelectionStart = box.TextLength; 
      box.SelectionLength = 0; 

      box.SelectionColor = color; 
      box.AppendText(text); 
      box.SelectionColor = box.ForeColor; 
     } 

     public static void ColorListBox(List<string> data, DrawItemEventArgs e) 
     { 
      string strLeft = null; 
      string strMid = "---"; 
      string strRight = null; 
      if (data[e.Index].Contains(strMid)) 
      { 
       int index = data[e.Index].IndexOf(strMid); 
       strLeft = data[e.Index].Substring(0, index); 
       strRight = data[e.Index].Substring(index + strMid.Length); 
      } 

      using (Font f = new Font(FontFamily.GenericSansSerif, 16, FontStyle.Regular)) 
      { 
       float startPos; 
       e.Graphics.DrawString(strLeft, f, Brushes.Red, e.Bounds.X, e.Bounds.Y); 
       startPos = e.Graphics.MeasureString(strLeft, f).Width; 
       e.Graphics.DrawString(strMid, f, Brushes.Black, e.Bounds.X + startPos, e.Bounds.Y); 
       startPos = e.Graphics.MeasureString(strLeft + strMid, f).Width; 
       e.Graphics.DrawString(strRight, f, Brushes.Green, e.Bounds.X + startPos, e.Bounds.Y); 
      } 
     } 
    } 
} 

而且在Form1的加载事件我所做的:

h = new Hardware(this); 
backgroundWorker1.RunWorkerAsync(); 
+0

你打算调用什么'Invoke()'函数? – bmm6o 2013-03-09 20:00:26

+0

'this.Invoke'看起来像用于切换到UI线程的winforms-API;你想做什么?为什么你需要切换到UI线程?由于你有一些控制实例,你可以使用它们...'lb1.Invoke(...)' – 2013-03-09 20:01:09

+0

我试图更新Form1中的listBox1。 https://www.dropbox.com/s/dtdqnpemwistz5n/HardwareMonitoring.rar这是我的项目,也许有人可以看看我在Form1中的背景工作的一部分,我尝试了很多次,不能使它工作。我在Form1中使用backgroundworker,并在这里调用这个类的函数来更新Form1中的listBox1,我想每秒更新一次listBox。但我无法弄清楚如何使用MSDN文档中的示例尝试使用backgroundworker到目前为止没有什么效果。 – user2065612 2013-03-09 20:03:52

回答

0

从MSDN文档

Executes the specified delegate on the thread that owns the control's underlying window handle. 

为了使用Invoke,您需要一个控件。为什么不使用lbl1.Invoke或传入的其他控件之一?

相关问题