本篇文章將從多個方面對C#關(guān)閉窗口代碼進行詳細闡述,并給出對應(yīng)完整的代碼示例。

一、關(guān)閉當前窗口
1、如果您需要在Winform應(yīng)用程序中關(guān)閉當前窗口,可以使用以下代碼:
this.Close();
2、如果您需要在WPF應(yīng)用程序中關(guān)閉當前窗口,可以使用以下代碼:
Application.Current.MainWindow.Close();
二、關(guān)閉其它窗口
1、如果您需要在Winform應(yīng)用程序中關(guān)閉其它窗口,可以使用以下代碼:
Form[] forms = Application.OpenForms;
foreach (Form form in forms)
{
if (form.Name == "Form2")
{
form.Close();
break;
}
}
其中,"Form2"是您需要關(guān)閉的窗口的名稱。
2、如果您需要在WPF應(yīng)用程序中關(guān)閉其它窗口,可以使用以下代碼:
foreach (Window window in Application.Current.Windows)
{
if (window != Application.Current.MainWindow)
{
window.Close();
}
}
三、定時關(guān)閉窗口
1、如果您需要在Winform應(yīng)用程序中定時關(guān)閉當前窗口,可以使用以下代碼:
Timer timer = new Timer();
timer.Interval = 5000; //5秒鐘后關(guān)閉窗口
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
private void timer_Tick(object sender, EventArgs e)
{
this.Close();
}
2、如果您需要在WPF應(yīng)用程序中定時關(guān)閉當前窗口,可以使用以下代碼:
DispatcherTimer timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(5); //5秒鐘后關(guān)閉窗口
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
private void timer_Tick(object sender, EventArgs e)
{
Application.Current.Shutdown();
}
其中,Application.Current.Shutdown()表示關(guān)閉整個應(yīng)用程序。
四、通過按鈕關(guān)閉窗口
您可以在Winform或WPF應(yīng)用程序中添加一個按鈕,并在該按鈕的Click事件中添加以下代碼來關(guān)閉當前窗口:
this.Close();
五、總結(jié)
通過本文的介紹,您已經(jīng)了解了如何通過C#關(guān)閉窗口,包括關(guān)閉當前窗口、關(guān)閉其它窗口、定時關(guān)閉窗口和通過按鈕關(guān)閉窗口,希望對您的開發(fā)有所幫助。

京公網(wǎng)安備 11010802030320號