標準方法
Form1 existing = null;
foreach (Form frm in Application.OpenForms) {
if (frm is Form1) { existing = (Form1)frm; break; }
}
if (existing != null) {
existing.Text = "來自 Form2 的修改";
existing.somePublicMethod();
}
泛型封裝
public static T GetOpenForm() where T : Form {
return Application.OpenForms.OfType().FirstOrDefault();
}
// 使用
var form1 = GetOpenForm();
form1?.UpdateUI();
注意事項
Application.OpenForms 僅包含當前線程創建的窗體;跨線程 UI 需 Invoke。
- 若 Form1 為多實例 (new Form1().Show()),上述取第一個;需區分時可用
Tag 屬性或單例模式。
- 更優雅的解耦:Form2 構造函數注入
Form1 引用,或通過事件/消息總線通信,避免全局查找。