using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace WindowsApplication1
{
public partial classAutoDeleteMessageBox : Form
{
/*
通过[DllImport]特性引入user32.dll的FindWIndow方法,用于搜索具有指定窗口类和标题的窗口,,并将窗口句柄存储在 hWnd 中.
lpClassName是要搜索的窗口类的名称,lpWindowName是要搜索的窗口的标题名称。
*/
[DllImport("user32.dll", EntryPoint ="FindWindow", CharSet = CharSet.Auto)]
private extern static IntPtr FindWindow(string lpClassName, string lpWindowName);
/*
通过[DllImport]特性引入user32.dll的PostMessage方法,用于向具有特定句柄的窗口发送指定消息,这里是 WM_CLOSE,以请求关闭该窗口。
hWnd是窗口句柄。
msg 是一个整数值,代表要发送的 Windows 消息。
wParam,lParam是 Windows 消息的参数。它们的具体含义取决于消息类型。在发送 WM_CLOSE 消息时,通常不需要使用这些参数,因此它们被设置为 IntPtr.Zero,表示没有特定的参数传递给 WM_CLOSE 消息。
*/
[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;
public AutoDeleteMessageBox()
{
InitializeComponent();
}
private void button1_Click(object sender,EventArgs e)
{
StartKiller();
MessageBox.Show("3秒钟后自动关闭MessageBox窗口", "MessageBox");
}
//通过计时器实现倒计时,在触发事件中指定user.dll的两个方法自动关闭窗体。
private void StartKiller()
{
Timer timer = new Timer();
timer.Interval = 3000; //3秒启动
timer.Tick+= new EventHandler(Timer_Tick);
timer.Start();
}
private void Timer_Tick(object sender, EventArgse)
{
KillMessageBox();
//停止Timer
((Timer)sender).Stop();
}
private void KillMessageBox()
{
//按照MessageBox的标题,找到MessageBox的窗口
IntPtr ptr= FindWindow(null, "MessageBox");
if (ptr !=IntPtr.Zero)
{
//找到则关闭MessageBox窗口
PostMessage(ptr, WM_CLOSE,IntPtr.Zero, IntPtr.Zero);
}
}
}
}
07-03
2654
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
07-11
660
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
05-01
1278
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
05-31
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交