委托 在其他类中修改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); 
    }
}

 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);
            }
        }
    }

} 

 

转载于:https://www.cnblogs.com/beijing2020/p/4036391.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值