创建了一个新的线程,在该线程中进行倒计时操作。在倒计时3秒后,通过调用CloseMessageBox
方法来关闭MessageBox窗口。
由于MessageBox是一个模态对话框,无法直接通过代码关闭。在这里,我们使用了WinAPI中的FindWindow
和SendMessage
方法来查找并关闭MessageBox窗口。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form3 : Form
{
// 查找窗口
[System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
// 发送消息
[System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
// 关闭消息
private const uint WM_CLOSE = 0x0010;
public Form3()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
ShowMessage("测试测试",2);
}
private void ShowMessage(string sMsg, int nSecondCount)
{
// 创建一个线程来执行倒计时操作
Thread thread = new Thread(() =>
{
// 倒计时3秒
Thread.Sleep(nSecondCount * 1000);
// 关闭MessageBox
if (InvokeRequired)
{
Invoke(new Action(() => { CloseMessageBox(); }));
}
else
{
CloseMessageBox();
}
});
// 启动线程
thread.Start();
// 弹出MessageBox提示框,注意:这里的标题必须与下方查找关闭MessageBox里的标题一致。
MessageBox.Show(sMsg, "完成提示");
}
private void CloseMessageBox()
{
// 查找并关闭MessageBox窗口
IntPtr hwnd = FindWindow(null, "完成提示");//一致
if (hwnd != IntPtr.Zero)
{
SendMessage(hwnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
}
}
}
}