02-使用委托与多线程实现窗体间传值

1、主窗体代码:

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 _08委托与多线程实现窗体间传值
{
    public delegate void SetTextDel(string text);//声明

    public partial class MainFrm : Form
    {
        public MainFrm()
        {
            InitializeComponent();
            this.Text = Thread.CurrentThread.ManagedThreadId.ToString();//当前线程ID
            //线程间空间不能相互访问,允许其他线程来访问当前线程创建的 控件:Control
            //Control.CheckForIllegalCrossThreadCalls = false;//掩耳盗铃的方式
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //ChildFrm child = new ChildFrm();
            //child.setTextDel = SetText;//实例化
            //child.Show();

            //方法二:多线程
            Thread thread = new Thread(() =>
            {
                ChildFrm child = new ChildFrm();
                child.setTextDel = SetText;//实例化
                child.ShowDialog();
            });
            thread.Start();//要开启,告诉操作系统已经准备就绪,随时可以调用
        }

        private void SetText(string text)
        {
            //InvokeRequired 当线程执行到此的时候,校验一下txtMessage控件是哪个线程创建的。
            //如果是自己创建的InvokeRequired:fasle反之则为true
            if (this.txtMessage.InvokeRequired)//不是自己创建的
            {
                SetTextDel setTextDel = SetTextForOtherThread;
                this.Invoke(setTextDel,text);//Invoke(委托名,参数)
            }
            else
            {
                this.txtMessage.Text = text;
            }
        }

        private void SetTextForOtherThread(string text)
        {
            this.txtMessage.Text = text;
        }
    }
}
View Code

2、子窗体代码:

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 _08委托与多线程实现窗体间传值
{
    public partial class ChildFrm : Form
    {
        public ChildFrm()
        {
            InitializeComponent();
            this.Text = Thread.CurrentThread.ManagedThreadId.ToString();
        }

        public SetTextDel setTextDel = null;//初始化

        private void btnSetMainTxt_Click(object sender, EventArgs e)
        {
            if (setTextDel != null)
            {
                setTextDel(this.txtSource.Text);//调用
            }
        }
    }
}
View Code

3、运行截图:

转载于:https://www.cnblogs.com/zy-style/p/4335630.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值