首页 > 代码库 > 委托 在其他类中修改form中的控件属性
委托 在其他类中修改form中的控件属性
通常情况下,我们需要在其他业务类中将提示信息时时显示到主界面上,可以通过以下方式
Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
TestDelegate td = new TestDelegate();
td.cb = SafeSetText;
Thread th = new Thread(new ThreadStart(td.Test));
th.Start();
}
public void SafeSetText(string text)
{
if (this.InvokeRequired)
{
_SafeSetTextCall call = delegate(string s)
{
this.label1.Text = s;
};
this.Invoke(call, text);
}
else
this.label1.Text = text;
}
public delegate void _SafeSetTextCall(string text);
}
}
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
TestDelegate td = new TestDelegate();
td.cb = SafeSetText;
Thread th = new Thread(new ThreadStart(td.Test));
th.Start();
}
public void SafeSetText(string text)
{
if (this.InvokeRequired)
{
_SafeSetTextCall call = delegate(string s)
{
this.label1.Text = s;
};
this.Invoke(call, text);
}
else
this.label1.Text = text;
}
public delegate void _SafeSetTextCall(string text);
}
}
TestDelegate.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace WindowsFormsApplication2
{
public delegate void CallBack(string msg);
public class TestDelegate
{
public CallBack cb;
public TestDelegate()
{
}
public void Test()
{
for (int i = 0; i < 100; i++) {
cb(i.ToString());
Console.WriteLine(i.ToString());
Thread.Sleep(1000);
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace WindowsFormsApplication2
{
public delegate void CallBack(string msg);
public class TestDelegate
{
public CallBack cb;
public TestDelegate()
{
}
public void Test()
{
for (int i = 0; i < 100; i++) {
cb(i.ToString());
Console.WriteLine(i.ToString());
Thread.Sleep(1000);
}
}
}
}
委托 在其他类中修改form中的控件属性
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。