在子线程里不能直接使用控件,需要建立委托,新建一个winform程序,拖拽一个label控件,id默认就好,代码如下
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace 子线程控制UI
{
/// <summary>
/// 开发者:it小金
/// 时间:2010-12-15
/// 功能:子线程控制窗体中的控件
/// </summary>
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private delegate void MoveLabel(int val);//声明代理
void SetOffset(int val)
{
label1.Text = "从子线程里传入的值是:" + val.ToString();
}
private void ThreadFun()
{
if (this.InvokeRequired)
{
MoveLabel d = new MoveLabel(SetOffset);
object[] arg = new object[] { 1 };//要传入的参数值
this.Invoke(d, arg);
}
}
//窗体载入时执行的函数
private void Form1_Load_1(object sender, EventArgs e)
{
Thread td = new Thread(new ThreadStart(ThreadFun));
td.Start();
}
}
}
c#多线程-子线程控制UI的例子
最新推荐文章于 2022-07-28 20:27:44 发布
