方法一
1. 创建一个C# Windows窗体应用程序,将主窗体改名为FormMain,再创建一个窗体起名为SplashScreen。向程序中加载一个图片作为启动画面。
2. 然后编辑SplashScreen.cs代码
在这里插入代码片
public partial class SplashScreen : Form
{
static SplashScreen instance;
Bitmap bitmap;
public static SplashScreen Instance
{
get
{
return instance;
}
set
{
instance = value;
}
}
public SplashScreen()
{
InitializeComponent();
// 设置窗体的类型
const string showInfo = "启动画面:我们正在努力的加载程序,请稍后...";
FormBorderStyle = FormBorderStyle.None;
StartPosition = FormStartPosition.CenterScreen;
ShowInTaskbar = false;
bitmap = new Bitmap(Properties.Resources.SplashScreen);
ClientSize = bitmap.Size;
using (Font font = new Font("Consoles", 10))
{
using (Graphics g = Graphics.FromImage(bitmap))
{
g.DrawString(showInfo, font, Brushes.White, 130, 100);
}
}
BackgroundImage = bitmap;
}
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
if (bitmap != null)
{
bitmap.Dispose();
bitmap = null;
}
components.Dispose();
}
base.Dispose(disposing);
}
public static void ShowSplashScreen()
{
instance = new SplashScreen();
instance.Show();
}
}
3. 在主程序启动时调用
在这里插入代码片
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// 启动
SplashScreen.ShowSplashScreen();
// 进行自己的操作:加载组件,加载文件等等
// 示例代码为休眠一会
System.Threading.Thread.Sleep(3000);
// 关闭
if (SplashScreen.Instance != null)
{
SplashScreen.Instance.BeginInvoke(new MethodInvoker(SplashScreen.Instance.Dispose));
SplashScreen.Instance = null;
}
Application.Run(new FormMain());
}
}
方法二
界面的控件越多,闪烁也越多,试过多种解决办法效果都不理想。
解决办法:把此段代码加入到窗体代码中:
protected override CreateParams CreateParams {
get {
CreateParams paras = base.CreateParams;
paras.ExStyle |= 0x02000000;
return paras;
}
}
方法三
protected override void WndProc(ref Message m)
{
if (m.Msg == 0x0014) // 禁掉清除背景消息
return;
base.WndProc(ref m);
}
方法四
封装Panel类
新建一个PanelEnhanced类继承Panel类,代码如下:
/// <summary>
/// 加强版 Panel
/// </summary>
class PanelEnhanced : Panel
{
/// <summary>
/// OnPaintBackground 事件
/// </summary>
/// <param name="e"></param>
protected override void OnPaintBackground(PaintEventArgs e)
{
// 重载基类的背景擦除函数,
// 解决窗口刷新,放大,图像闪烁
return;
}
/// <summary>
/// OnPaint 事件
/// </summary>
/// <param name="e"></param>
protected override void OnPaint(PaintEventArgs e)
{
// 使用双缓冲
this.DoubleBuffered = true;
// 背景重绘移动到此
if (this.BackgroundImage != null)
{
e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
e.Graphics.DrawImage(
this.BackgroundImage,
new System.Drawing.Rectangle(0, 0, this.Width, this.Height),
0,
0,
this.BackgroundImage.Width,
this.BackgroundImage.Height,
System.Drawing.GraphicsUnit.Pixel);
}
base.OnPaint(e);
}
}
方法五
- 添加如下代码到构造函数:
SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.AllPaintingInWmPaint, true); // 禁止擦除背景.
SetStyle(ControlStyles.DoubleBuffer, true); // 双缓冲
SetStyle(ControlStyles.OptimizedDoubleBuffer, true); //先绘制到缓冲区
UpdateStyles();
- 将load函数加到构造函数中。