SplashForm - 一个 Splash 窗口窗体






4.56/5 (19投票s)
2005 年 2 月 17 日
2分钟阅读

229684

5015
本文介绍了一个扩展 Windows Forms 以创建启动画面和“关于”对话框的类。
引言
我之前写过一篇文章 CSplash - 一个启动画面类,介绍了使用 Win32 API 显示启动画面。本文介绍如何在 .NET 框架中实现相同的功能。此窗体也可以用于“关于”对话框。
准备图像
首先,在您最喜欢的图像编辑器中创建您想要显示为启动画面的图像。然后,选择图像中您不希望在屏幕上渲染的部分,并为其赋予图像中任何其他地方都没有的特定颜色。例如,如果您的图像是一个带有蓝色内部徽标或文本的红色圆盘,则用绿色(任何非红色和蓝色的颜色)填充圆圈外部的所有区域。
使用 SplashForm
该类的接口非常简单。在应用程序启动时,调用静态方法 StartSplash
并指定位图文件路径以及要设为透明的颜色。这将在新线程中创建并显示启动画面窗体,以便控制立即返回到您的应用程序,并可以继续进行其他初始化。
using System;
using Abhinaba.Splasher;
using System.Drawing;
SplashForm.StartSplash(@".\splash.bmp",
Color.FromArgb(128, 128, 128));
完成所有初始化后,调用静态方法 CloseSplash
以关闭启动画面窗体。
SplashForm.CloseSplash();
要将启动画面显示为“关于”对话框,请使用 ShowModal
方法。
SplashForm.ShowModal(@".\splash.bmp",
Color.FromArgb(128, 128, 128));
幕后
在 StartSplash
中,会创建一个新线程,该线程调用方法 MySplashThreadFunc
。
// Create and Start the splash thread
Thread InstanceCaller = new Thread(new ThreadStart(MySplashThreadFunc));
InstanceCaller.Start();
此方法创建启动画面窗体并在新线程中显示它。
private static void MySplashThreadFunc()
{
m_instance = new SplashForm(m_imageFile, m_transColor);
m_instance.TopMost = false;
m_instance.ShowDialog();
}
启动画面窗体构造函数然后准备窗体以实现透明度,然后加载图像
public SplashForm(String imageFile, Color col)
{
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.ShowInTaskbar = false;
this.TopMost = true;
// make form transparent
this.TransparencyKey = this.BackColor;
// tie up the events
//...
// load and make the bitmap transparent
m_bmp = new Bitmap(imageFile);
m_bmp.MakeTransparent(col);
// resize the form to the size of the iamge
this.Width = m_bmp.Width;
this.Height = m_bmp.Height;
// center the form
this.StartPosition =
System.Windows.Forms.FormStartPosition.CenterScreen;
// thread handling. Used because the window
// will be closed from a different thread
m_delegateClose = new DelegateCloseSplash(InternalCloseSplash);}
在 Paint
事件中,加载的图像被显示出来。
private void SplashForm_Paint(object sender,
System.Windows.Forms.PaintEventArgs e)
{
e.Graphics.DrawImage(m_bmp, 0,0);
}
要关闭窗体,必须调用 CloseSplash
方法。启动画面窗体已创建并在不同的线程中运行。因此,无法直接在其上调用 Close
。为此,使用了以下代码
public delegate void DelegateCloseSplash();
private DelegateCloseSplash m_delegateClose;
public SplashForm(String imageFile, Color col)
{
// ...
m_delegateClose = new DelegateCloseSplash(InternalCloseSplash);
// ...
}
public static void CloseSplash()
{
m_instance.Invoke(m_instance.m_delegateClose);
}