0
点赞
收藏
分享

微信扫一扫

C# 软件初始化时 自动关闭MessageBox的方法

kolibreath 2022-02-18 阅读 102

C#自动关闭MessageBox的方法


前言

在winform或WPF软件开发过程中会遇上软件初始化需要加载各类配置文件或者调用各种方法的情况,此时调用的方法可能存在MessageBox,窗口弹出后需要人工干预才能关闭,本文描述了C#开发过程中MessageBox自动关闭的方法

一、方法

1、在MessageBox打开前,开启定时器
2、程序运行至MessageBox开启
3、定时器时间到达,Time_Tick内运行FindWindow方法,找到MessageBox窗口,并将其关闭
4、关闭定时器

二、步骤

1.引入库

代码如下(示例):

using System.Runtime.InteropServices;
using System.Windows.Threading;

其中
System.Runtime.InteropServices 用于FindWindow函数
System.Windows.Threading 用于定时器Timer类,可根据实际情况替换,此处对应为WPF下的DispatcherTimer类

2.开启定时器

代码如下(示例):

DispatcherTimer timer = new DispatcherTimer();
timer.Interval = new TimeSpan(0, 0, 0, 0, 5); //5ms
timer.Tick += new EventHandler(Time_Tick);
timer.Start();

3.MessageBox弹窗显示

 MessageBox.Show("CardConfig.ini导入成功", "MessageBox");

4.自动关闭MessageBox

 [DllImport("user32.dll", EntryPoint = "FindWindow", CharSet = CharSet.Auto)]
 private extern static IntPtr FindWindow(string lpClassName, string lpWindowName);

 [DllImport("user32.dll", CharSet = CharSet.Auto)]
 public static extern int PostMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);

 public const int WM_CLOSE = 0x10;
 private void Time_Tick(object sender, EventArgs e)
 {
     //按照MessageBox的标题,找到MessageBox的窗口
     IntPtr ptr = FindWindow(null, "MessageBox");
     if (ptr != IntPtr.Zero)
     {
         //找到则关闭MessageBox窗口
         PostMessage(ptr, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
     }
     ((DispatcherTimer)sender).Stop();
 }
参考文章 https://blog.csdn.net/sunxiaotianmg/article/details/17136719

总结

通过定时器和FindWindow解决用户无法自动关闭掉窗口而导致程序一直停留不前的问题
举报

相关推荐

0 条评论