C# 下使用委托跨窗体调用函数和控件的实现

form1

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 button1_Click(object sender, EventArgs e)
        {
            Form2 f = new Form2();
            f.ChangeColor += new Form2.ChangeFormColor(f_ChangeColor);
            f.Show();  
        }
        void f_ChangeColor(bool topmost)
        {
            this.BackColor = Color.LightBlue;
            this.Text = "改变成功";
        }  
    }
}



form2

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 Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }
        public delegate void ChangeFormColor(bool topmost);  
        private void Form2_Load(object sender, EventArgs e)
        {

        }
        public event ChangeFormColor ChangeColor;
        private void button1_Click(object sender, EventArgs e)
        {
            ChangeColor(true);//执行委托实例  
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            ChangeColor(true);
        }  
    }
}


已标记关键词 清除标记
Form1类里的代码 public Class1 cla; private void button1_Click(object sender, EventArgs e) { Form2 f2 = new Form2(); f2.Show(); cla.run1(); } private void Form1_Load(object sender, EventArgs e) { cla = new Class1(this,LK); } void LK() { button1.Text = "abc"; } Form2类里的代码 public Class1 cla; void ds() { this.button1.Text = "def"; } private void button1_Click(object sender, EventArgs e) { cla = new Class1(this, ds); cla.run2(); } Class1类里的代码 public delegate void Del1(); public Del1 _del1; public Class1(Form1 f1, Del1 del) { this._del1 = del; } public delegate void Del2(); public Del2 _del2; public Class1(Form2 f2, Del2 del) { this._del2 = del; } public void run1() { Thread th = new Thread(a); th.Start(); } public void run2() { Thread th = new Thread(b); th.Start(); } public void a() { try { _del1();//不为空,可以执行 } catch (Exception e) { MessageBox.Show("a中的方法:\n"+e.ToString ()); } } public void b() { try { _del1();//问题在这,这里委托的方法为空,为什么,上面的怎么不为空? _del2(); } catch (Exception e) { MessageBox.Show("b中的方法:\n" + e.ToString()); } } 问题:在Class1 类里(有注释)。很急,求各位大神帮帮忙。 问题的要义就是在自定义的类里新起一条线程来调用窗体控件,我是通过委托的方法执行,但在传这个方法(需要委托的方法)的参数时,在Class1的构造方法中检验是可以传进来的,但调用的时候就为空了。 再次求各位大神帮帮忙。
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页