c# 定时关闭 MessageBox 或弹出的模态窗口

时间:2023-03-09 16:33:12
c# 定时关闭 MessageBox 或弹出的模态窗口

我们都知道,MessageBox弹出的窗口是模式窗口,模式窗口会自动阻塞父线程的。所以如果有以下代码:

MessageBox.Show("内容',"标题"); 

则只有关闭了MessageBox的窗口后才会运行下面的代码。而在某些场合下,我们又需要在一定时间内如果在用户还没有关闭窗口时能自动关闭掉窗口而避免程序一直停留不前。这样的话我们怎么做呢?上面也说了,MessageBox弹出的模式窗口会先阻塞掉它的父级线程。所以我们可以考虑在MessageBox前先增加一个用于“杀”掉MessageBox窗口的线程。因为需要在规定时间内“杀”掉窗口,所以我们可以直接考虑使用Timer类,然后调用系统API关闭窗口。

核心代码如下:

c# 定时关闭 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 StartKiller()
{
Timer timer = new Timer();
timer.Interval = ; //10秒启动
timer.Tick += new EventHandler(Timer_Tick);
timer.Start();
} private void Timer_Tick(object sender, EventArgs e)
{
KillMessageBox();
//停止计时器
((Timer)sender).Stop();
} private void KillMessageBox()
{
//查找MessageBox的弹出窗口,注意MessageBox对应的标题
IntPtr ptr = FindWindow(null,"标题");
if(ptr != IntPtr.Zero)
{
//查找到窗口则关闭
PostMessage(ptr,WM_CLOSE,IntPtr.Zero,IntPtr.Zero);
}
}
c# 定时关闭 MessageBox 或弹出的模态窗口

在需要的地方调用 StartKiller 方法即可达到自动关闭 MessageBox 的效果。

出处:https://www.cnblogs.com/feiyuhuo/p/5110330.html

=======================================================================

经过测试,这个方法没办法关闭下面的代码弹出窗口:

new ViewMessage().ShowDialog(this);   //我弹出的模态窗口,并且指定主窗口的类为this

我是通过下面的代码获取窗口并关闭

private void ExitAllForm()
{
var fs = System.Windows.Forms.Application.OpenForms;
for (int i = ; i < fs.Count; i++)
{
//........逻辑代码
KillForm(fs[i].Text);
}
} private void KillForm(string strTitle)
{
IntPtr ptr = Common.WindowsAPI.FindWindow(null, strTitle);
if (ptr != IntPtr.Zero)
{
Common.WindowsAPI.PostMessage(ptr, 0x10, IntPtr.Zero, IntPtr.Zero);
}
} /// <summary>
/// 获取指定标题窗口的句柄
/// </summary>
/// <param name="lpClassName"></param>
/// <param name="lpWindowName"></param>
/// <returns></returns>
[DllImport("user32.dll", EntryPoint = "FindWindow", CharSet = CharSet.Auto)]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName); /// <summary>
/// 向指定窗口句柄发送消息
/// </summary>
/// <param name="hWnd"></param>
/// <param name="msg"></param>
/// <param name="wParam"></param>
/// <param name="lParam"></param>
/// <returns></returns>
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern int PostMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);