首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C# 獲取已打開窗體實例:Application.OpenForms 遍歷與類型轉換

     編輯:程式設計綜合問答

標準方法

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 引用,或通過事件/消息總線通信,避免全局查找。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved