Skip to content

Instantly share code, notes, and snippets.

@overing
Last active July 1, 2020 03:46
Show Gist options
  • Save overing/4af37c55aa38bf29cfbeeb39dd097a86 to your computer and use it in GitHub Desktop.
Save overing/4af37c55aa38bf29cfbeeb39dd097a86 to your computer and use it in GitHub Desktop.
WinForms 跨窗傳動事件範例
using System;
using System.Windows.Forms;
namespace CrossFromsDemo
{
static class Program
{
[STAThread]
static void Main()
{
Application.SetHighDpiMode(HighDpiMode.SystemAware);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
}
public class MainForm : Form
{
Button Open2ndFormButton;
public MainForm()
{
Text = GetType().Name;
Open2ndFormButton = new Button { Text = "Open 2nd Form", Dock = DockStyle.Fill };
Open2ndFormButton.Click += OnClick_OpenSecondFormButton;
Controls.Add(Open2ndFormButton);
}
void OnClick_OpenSecondFormButton(object sender, EventArgs e)
{
Open2ndFormButton.Enabled = false;
var secondForm = new SecondForm();
// 註冊第二窗開放出來的按鈕事件
secondForm.ActionButtonClick += OnClick_SecondFormAction;
secondForm.Show(this);
}
void OnClick_SecondFormAction(object sender, EventArgs e)
{
// 第二窗的的按鈕事件發生就復原按鈕
Open2ndFormButton.Enabled = true;
}
}
public class SecondForm : Form
{
Button ActionButton;
// 開事件出去給其他人
public event EventHandler ActionButtonClick;
public SecondForm()
{
Text = GetType().Name;
ActionButton = new Button { Text = "Action", Dock = DockStyle.Fill };
ActionButton.Click += OnClick_ActionButton;
Controls.Add(ActionButton);
}
void OnClick_ActionButton(object sender, EventArgs e)
{
// 觸發開放出去的事件通知其他人
ActionButtonClick?.Invoke(sender, e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment