在C#中,可以使用Windows Forms或WPF(Windows Presentation Foundation)來創建子窗口并實現動態加載和卸載。這里我將分別為這兩種技術提供一個示例。
首先,創建一個名為MainForm的主窗口,然后創建一個名為ChildForm的子窗口。在MainForm中添加一個按鈕,用于加載和卸載子窗口。
using System;
using System.Windows.Forms;
namespace DynamicSubWindow
{
public partial class MainForm : Form
{
private ChildForm _childForm;
public MainForm()
{
InitializeComponent();
}
private void btnLoadUnload_Click(object sender, EventArgs e)
{
if (_childForm == null)
{
_childForm = new ChildForm();
_childForm.TopLevel = false;
_childForm.Parent = this;
_childForm.Visible = true;
_childForm.Location = new System.Drawing.Point(50, 50);
}
else
{
_childForm.Dispose();
_childForm = null;
}
}
}
}
首先,創建一個名為MainWindow的主窗口,然后創建一個名為ChildWindow的子窗口。在MainWindow中添加一個按鈕,用于加載和卸載子窗口。
using System.Windows;
namespace DynamicSubWindowWPF
{
public partial class MainWindow : Window
{
private ChildWindow _childWindow;
public MainWindow()
{
InitializeComponent();
}
private void btnLoadUnload_Click(object sender, RoutedEventArgs e)
{
if (_childWindow == null)
{
_childWindow = new ChildWindow();
_childWindow.Owner = this;
_childWindow.Show();
}
else
{
_childWindow.Close();
_childWindow = null;
}
}
}
}
在這兩個示例中,我們都使用了一個按鈕來加載和卸載子窗口。當點擊按鈕時,如果子窗口不存在,則創建一個新的子窗口并顯示它;如果子窗口已經存在,則關閉它并釋放資源。這樣就實現了子窗口的動態加載和卸載。