【C#】一個Loading窗體載入與銷毀的方法


寫在前面

Minecraft Command Editor 2跳票了近兩年的時間(對不起!!)。2021年2月,我重啟了MCE項目,並正式命名為Minecraft Command Editor 2021,感謝大家三年來的支持,鞠躬!

在MCE項目中,Main窗體載入前,會進行數據庫和其他配置的加載,在這個階段,因此,在加載的空檔期載入一個Loading窗口,有效的解決了從視覺上程序加載慢的問題。今天我們來說一個比較好的Loading窗體載入與銷毀的方法。


一個Loading窗體載入與銷毀的方法

首先我們來定義一個Form類:

namespace Minecraft_Command_Editor
{
	partial class Loading{}		// Loading Form
	partial class Main{}		// Main Form
	partial class Settings{}	// Settings Form
	partial class About{}		// About Form
}

在Program類中Main函數中插入:

Loading loading = new Loading();	// Creates the Loading object.
loading.ShowDialog();			// Shows the Loading Form as a modal dialog box.
if (loading.Visible == false)
{
	Application.Run(new Main());	// Begins running a standard application message loop on the current thread, and makes the Main form visible.
}

最后Program類看起來長這樣:

static class Program
{
	[STAThread]
	static void Main()
	{
		Application.SetHighDpiMode(HighDpiMode.SystemAware);
		Application.EnableVisualStyles();
		Application.SetCompatibleTextRenderingDefault(false);

		Loading loading = new Loading();	// Creates the Loading object.
		loading.ShowDialog();			// Shows the Loading Form as a modal dialog box.
		if (loading.Visible == false)
		{
			Application.Run(new Main());	// Begins running a standard application message loop on the current thread, and makes the Main form visible.
		}
	}
}

這是一個單線程程序的Loading窗體載入方法,想要銷毀Loading進入到Main窗體,則需要在Loading類的適當位置加入銷毀代碼即可。
例如:

using System;
using System.Windows.Forms;
using Functions.System;		// Custom namespace
namespace Minecraft_Command_Editor
{
	public partial class Loading : Form
	{
		private void Loading_Shown(object sender, EventArgs e)
		{
			Process.ThreadDelay(512);	// Thread delay 512ms.
			this.Close();				// Close Form.
		}
	}
}

寫在最后

一年前,我在知乎也分享了一個Loading窗體載入的方法,方法不同但思路是一樣的。
實際上,關於Main窗體的前置載入方法有很多,大家選擇自己喜歡的即可。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM