C#下类中 访问窗体控件的问题
一般来讲我们都已经习惯了把单一的功能块都写到类里边了,然后在软件的主线程中调用一下类中的函数所有功能就都实现了,但是有些系统,比如说某一些监控类的系统,需要我们在类中进行操作的同事呢把一些实时数据展示出来,这个时候就需要在类中调用主线程中的控件了。从网上找了找没有找到很好的办法,就自己写了一个。可以用的。我把代码粘出来,有问题的请留言!using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace 类访问窗体控件 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { } private void Btn_Do_Click(object sender, EventArgs e) { class1 c1 =new class1(); System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(c1.SetLableText)); t.IsBackground = true; t.Start(); } } public class class1 { public delegate void DelegateSetLableText(Label lable, string Str_Text); public void FunctionSetLableText(Label lable, string Str_Text) { lable.Text = Str_Text; } public void SetLableText() { object[] myArray = new object[2]; myArray[0] = (Application.OpenForms["Form1"].Controls["label1"] as Label); for (int i = 0; i < 10000; i++) { myArray[1] = DateTime.Now.ToString(); (Application.OpenForms["Form1"].Controls["label1"] as Label).BeginInvoke(new DelegateSetLableText(FunctionSetLableText), myArray); System.Threading.Thread.Sleep(1000); } } } }
补充:软件开发 , C# ,