1. 程式人生 > >C# 委托 父窗口與子窗口間傳值

C# 委托 父窗口與子窗口間傳值

message orm await for 解釋 ech har component str

1)目標

父窗口與子窗口都有1個Button和1個Label。

目標1:單擊父窗口的Button,子窗口的Label將顯示父窗口傳來的值。

目標2:單擊子窗口的Button,父窗口的Label將顯示子窗口傳來的值。

2)父窗口代碼

using System;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp5
{
    public delegate void ShowMessageService(string msg);
    public partial class FormMain : Form
    {
        private FormChild childForm = new FormChild();
        public FormMain()
        {
            InitializeComponent();
        }

        private void FormMain_Load(object sender, EventArgs e)
        {
            childForm.showMessageChild = new ShowMessageService(UpdateLabel);
            childForm.Show();
        }

        public async void UpdateLabel(string msg)
        {
            await Task.Delay(2000);
            this.label1.Text = msg;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ShowMessageService sms = new ShowMessageService(childForm.UpdateLabel);
            this.BeginInvoke(sms, "Message from FormMain");
        }

    }
}

3)子窗口代碼

using System;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp5
{
    public partial class FormChild : Form
    {
        public ShowMessageService showMessageChild;
        public FormChild()
        {
            InitializeComponent();
        }

        public async void UpdateLabel(string msg)
        {
            await Task.Delay(2000);
            this.label1.Text = msg;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.BeginInvoke(showMessageChild, "Message from FormChild");
        }
    }
}

4)解釋

4.1)定義委托

public delegate void ShowMessageService(string msg);

4.2)父窗口向子窗口傳遞消息

①由於父窗口擁有子窗口對象,所以直接利用子窗口的方法來創建委托對象,然後用this.BeginInvoke進行異步調用。

private void button1_Click(object sender, EventArgs e)
{
ShowMessageService sms = new ShowMessageService(childForm.UpdateLabel);//定義委托對象,指向子窗口的UpdateLabel方法。
this.BeginInvoke(sms, "Message from FormMain"); //執行的是子窗口的UpdateLabel方法
}

4.3)子窗口向父窗口傳遞消息

①子窗口聲明委托對象

public partial class FormChild : Form
{

public ShowMessageService showMessageChild;//聲明

}

②在主窗口給委托對象賦值。

public partial class FormMain : Form
{
private FormChild childForm = new FormChild();
private void FormMain_Load(object sender, EventArgs e)
{
childForm.showMessageChild = new ShowMessageService(UpdateLabel); //子窗口的委托對象指向父窗口的UpdateLabel方法。
childForm.Show();
}

}

③子窗口用this.BeginInvoke進行異步調用。

private void button1_Click(object sender, EventArgs e)
{
this.BeginInvoke(showMessageChild, "Message from FormChild");
}

C# 委托 父窗口與子窗口間傳值