C#程序启动欢迎窗体实现

当程序在启动过程中需要花一些时间去加载资源时,我们希望程序能显示一个欢迎界面,能简单介绍软件功能的同时还能告知用户该程序还在加载中,使得用户体验更友好。
实现如下:

1. 添加欢迎界面的窗体(比如SlpashForm),做以下调整:
将FormBorderStyle属性设成None,即没有窗体边框
将StartPosition属性设成CenterScreen,即总是居中
将TopMost属性设成True,即总是在顶部
将UseWaitCursor属性设成Ture,即显示等待光标,让人感觉后台还在运行
增加一个PictureBox控件,与欢迎图片大小一致,窗体的大小也设成一致
增加一个ProgressBar控件,将Style设成Marquee,将MarqueeAnimationSpeed设成50

2. 主界面的构造函数改成以下代码:
// Create thread to show splash window
Thread showSplashThread = new Thread(new ThreadStart(ShowSplash));
showSplashThread.Start();

// Time consumed here
InitializeFrame(); // 把原来构造函数中的所有代码移到该函数中

// Abort show splash thread
showSplashThread.Abort();
showSplashThread.Join(); // Wait until the thread aborted
showSplashThread = null;

3. 显示SplashForm的线程函数
///

/// Thread to show the splash.
///

private void ShowSplash()
{
SplashForm sForm = null;
try
{
sForm = new SplashForm();
sForm.ShowDialog();
}
catch (ThreadAbortException e)
{
// Thread was aborted normally
if (_log.IsDebugEnabled)
{
_log.Debug("Splash window was aborted normally: " + e.Message);
}
}
finally
{
sForm = null;
}
}

4. 在主窗体的Load事件加激活自己的代码
SetForegroundWindow(Process.GetCurrentProcess().MainWindowHandle);

在使用SetForegroundWindow之前先声明一下
// Uses to active the exist window
[DllImport("User32.dll")]
public static extern void SetForegroundWindow(IntPtr hwnd);

实例图:

Tags:

6 Responses to “C#程序启动欢迎窗体实现”

  1. yuanlor说道:

    看不懂,什么东东啊,什么时候写点我能看懂的不啊

  2. lordong说道:

    这是技术问题,你当然看不懂了,哈哈

  3. 王伟晔说道:

    我看到另外一种实现方式,纯C#.net的:
    static class Program
    {
    internal static ApplicationContext _Context;

    [STAThread]
    static void Main()
    {
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    _Context = new ApplicationContext();
    Application.Idle += new EventHandler(Application_Idle);
    Skapac.WinUI.FrmFlash.Instance.Show();
    Application.Run(_Context);
    }
    private static void Application_Idle(object sender, EventArgs e)
    {
    if (_Context.MainForm == null)
    {
    Application.Idle -= new EventHandler(Application_Idle);
    _Context.MainForm = Skapac.WinUI.FrmMain.Instance;
    System.Windows.Forms.Application.DoEvents();
    _Context.MainForm.Show();
    System.Windows.Forms.Application.DoEvents();
    Skapac.WinUI.FrmFlash.Instance.Close();
    }
    }
    }

  4. student说道:

    能仔细解释一下吗,不大懂啊。谢谢。

  5. 匿名说道:

    好,SetForegroundWindow(Process.GetCurrentProcess().MainWindowHandle);
    不是很多都说不好用嘛?我试的也有问题的。请问您是如何解决的?谢谢

  6. asdf说道:

    _log是什么东东啊!

Leave a Reply


提醒: 评论者允许使用'@user空格'的方式将自己的评论通知另外评论者。例如, ABC是本文的评论者之一,则使用'@ABC '(不包括单引号)将会自动将您的评论发送给ABC。请务必注意user必须和评论者名相匹配(大小写一致)。