`FrmMain` 按鈕點擊獲取信息,需實時顯示在已打開的 `FrmShow` 窗體中。
// FrmShow.cs
public partial class FrmShow : Form {
public void UpdateInfo(string message) {
if (this.InvokeRequired) {
this.BeginInvoke(new Action(UpdateInfo), message);
return;
}
txtDisplay.AppendText(message + Environment.NewLine); // 線程安全更新 UI
}
}
// FrmMain.cs
private FrmShow showForm;
private void FrmMain_Load(object sender, EventArgs e) {
showForm = new FrmShow();
showForm.Show(); // 非模態顯示
}
private void btnGetData_Click(object sender, EventArgs e) {
string data = GetDataFromSomewhere();
showForm?.UpdateInfo(data); // 直接調用公共方法
}
// 共享事件參數類
public class DataEventArgs : EventArgs { public string Message { get; set; } }
// FrmMain 發布事件
public event EventHandler DataReceived;
private void OnDataReceived(string msg) {
DataReceived?.Invoke(this, new DataEventArgs { Message = msg });
}
// FrmShow 訂閱
public FrmShow(FrmMain main) {
InitializeComponent();
main.DataReceived += (s, e) => UpdateInfo(e.Message);
// 關閉時取消訂閱防內存洩漏
this.FormClosed += (s, e) => main.DataReceived -= ...;
}