2023年8月25日 星期五

[C#] 透過設定Owner在子視窗中取得父視窗的參考

在 C# 的視窗應用程式開發中,有時候我們需要在子視窗中取得父視窗的參考,以實現不同視窗之間的資訊交換或操作。這篇教學將會示範如何使用 Owner 屬性來在子視窗中取得父視窗的參考,以及如何進行相關操作。


建立父視窗和子視窗 

首先,我們需要建立一個父視窗和一個子視窗。這裡我們使用 Windows Form 進行示範,你可以根據自己的項目需求進行調整。 建立父視窗 在 Visual Studio 中,創建新的 Windows Form 專案。然後,設計一個包含按鈕的父視窗,按鈕用於打開子視窗。

using System;
using System.Windows.Forms;

namespace ParentChildFormExample
{
 public partial class ParentForm : Form
 {
 public ParentForm()
 {
 InitializeComponent();
 }

 private void openChildButton_Click(object sender, EventArgs e)
 {
 ChildForm childForm = new ChildForm();
 childForm.Owner = this; // 設定子視窗的 Owner 爲父視窗
 childForm.ShowDialog();
 }
 }
}

建立子視窗 

在專案中,創建一個新的 Windows Form,作為子視窗。

using System;
using System.Windows.Forms;

namespace ParentChildFormExample
{
 public partial class ChildForm : Form
 {
 public ChildForm()
 {
 InitializeComponent();
 }

 private void getInfoButton_Click(object sender, EventArgs e)
 {
 if (this.Owner is ParentForm parentForm)
 {
 MessageBox.Show($"父視窗的標題為: {parentForm.Text}", "父視窗資訊");
 }
 else
 {
 MessageBox.Show("找不到父視窗。");
 }
 }
 }
}

處理資訊交換或操作 在子視窗中,你可以使用 Owner 屬性來取得父視窗的參考。這樣一來,你就可以根據需求進行資訊交換或操作。 

 在上述的範例中,當在子視窗的按鈕點擊事件中檢查 Owner 屬性是否為 ParentForm 的實例後,我們使用 MessageBox 顯示了父視窗的標題。

你可以根據項目需求,在子視窗中執行其他操作,並使用父視窗的參考來實現更多功能。 透過 Owner 屬性,我們可以在 C# 中輕鬆地在子視窗中取得父視窗的參考,從而實現視窗之間的資訊交換和操作。這種機制在開發多視窗應用程式時特別有用,可以提升用戶體驗並實現更多功能。

沒有留言:

張貼留言