我開發了一個應用程序,我在其中使用Windows窗體作爲啓動畫面。在顯示啓動畫面後,我創建了一個新線程來觸發新窗體。現在我想在我的表單顯示後關閉啓動畫面。從另一個'表單'關閉'表單'
我GOOGLE了我的查詢,許多討論,但無法找到我想要的。
請引導我一點。
謝謝。
我開發了一個應用程序,我在其中使用Windows窗體作爲啓動畫面。在顯示啓動畫面後,我創建了一個新線程來觸發新窗體。現在我想在我的表單顯示後關閉啓動畫面。從另一個'表單'關閉'表單'
我GOOGLE了我的查詢,許多討論,但無法找到我想要的。
請引導我一點。
謝謝。
只要您對第一種形式有一些參考,就可以在另一種形式上調用Close()
方法。所以當你創建第二個表單時,請給它啓動畫面的引用。然後將一個處理程序附加到顯示事件並在啓動屏幕上調用close。
爲了解決交叉線程問題,您需要創建一個名爲ThreadSafeClose的方法,並將其定義如下。然後調用該方法,而不是.Close()
public void ThreadSafeClose() {
if(this.InvokeRequired) {
this.Invoke(new MethodInvoker(this.Close));
}
}
表單處於不同的線程。你不能從另一個線程調用一個控件的方法。您需要使用Invoke()從spash的線程運行Close()。 – Adi
我有一個哈克方法我用..也許不是,雖然做的最好的事情。在閃屏形式中的 聲明自己的靜態實例。
public static SplashForm splashInstance;
然後在splashform的構造函數中,您可以指定一個值「this」。
SplashForm.splashInstance = this;
您現在可以從應用程序中的任何位置調用SplashForm.splashInstance.Close()。
爲了關閉表單,您需要鏈接到此表單。最簡單的方法是將程序中的新屬性添加到程序中的靜態且可用的對象中。只需修改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();
});
你做不是需要一個單獨的線程來顯示一段時間內的「閃屏」。事實上,有更好的方法可以設計你的課程,使得這一切都變得容易完成。這裏沒有使用計時器或使用單獨的線程這不是正確的解決方案恕我直言。我建議你嘗試做這樣的事情:
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);
}
}
使用計時器是不適合我的。 –
爲什麼不同線程上的窗體? – CodesInChaos
在.NET中使用內置支持啓動屏幕,獲得線程權限是非常平凡的:http://stackoverflow.com/questions/392864/c-splash-screen-problem/393870#393870 –