[英]Closing a 'form' from another 'form'
我開發了一個應用程序,我使用Windows窗體作為啟動畫面。 顯示啟動畫面后,我創建了一個新線程來觸發新窗體。 現在我想在我的表單顯示后關閉啟動畫面。
我搜索了我的查詢,許多討論但找不到我想要的東西。
請指導一下。
謝謝。
只要您對第一個表單有一些引用,就可以在另一個表單上調用Close()
方法。 因此,當您創建第二個表單時,請為其指定啟動畫面。 然后將處理程序附加到Shown事件並在啟動屏幕上調用close。
為了解決跨線程問題,您需要創建一個名為ThreadSafeClose的方法,並按如下方式定義。 然后調用該方法而不是.Close()
public void ThreadSafeClose() {
if(this.InvokeRequired) {
this.Invoke(new MethodInvoker(this.Close));
}
}
要關閉表單,您需要有一個指向此表單的鏈接。 最簡單的方法是向Program
中的Program
對象添加一個新屬性,該屬性是靜態的,並且可以在任何地方使用。 只需修改Program.cs
文件以使Program
類公開並添加適當的引用:
public static class Program
{
///This is your splash screen
public static Form1 MySplashScreen = new Form1();
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
/// This is how you run your main form
Application.Run(MySplashScreen);
}
}
然后在表單中,您可以使用以下語法輕松關閉啟動畫面窗體:
Program.MySplashScreen.Close();
編輯:在WinForms中只有一個GUI線程,所以只要你從另一個表單中執行關閉它應該是安全的。 如果要從GUI生成的工作線程關閉表單,請使用以下代碼(這應該引用您的第二個表單):
this.Invoke((MethodInvoker)delegate {
Program.MySplashScreen.Close();
});
通常您不需要新線程。 但是一旦你擁有它,你可以通過在兩個線程之間共享bool值(將其命名為closeSplash)來實現。
在啟動窗體上放置一個計時器,每秒檢查closeSplash的值。 當closeSplash為true時,只需調用Splash表單的Close()方法即可。
如果您選擇關閉另一個線程的啟動,請看這個 。
我有一個hacky方法,我使用..雖然可能不是最好的事情。 在初始屏幕窗體中聲明一個自身的靜態實例。
public static SplashForm splashInstance;
然后在splashform的構造函數中,您可以賦值“this”。
SplashForm.splashInstance = this;
您現在可以從應用程序中的任何位置調用SplashForm.splashInstance.Close()。
你並不需要一個單獨的線程只是在一段時間內顯示“閃屏”。 實際上,有更好的方法可以設計您的類,使這樣做更容易完成。 在這里不使用計時器或使用單獨的線程不是正確的解決方案恕我直言。 我建議你嘗試這樣做:
public class SplashScreen : Form
{
// add a timer to your form with desired interval to show
protected override void OnShown(EventArgs e)
{
displayTimer.Start();
base.OnShown(e);
}
private void displayTimer_Tick(object sender, EventArgs e)
{
this.Close();
}
}
public class MainForm : Form
{
protected override void OnLoad(EventArgs e)
{
// splash screen will be shown before your main form tries to show itself
using (var splash = new SplashScreen())
splash.ShowDialog();
base.OnLoad(e);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.