可以通过使用定时器来实现。以下是一个示例代码:
using System;
using System.Windows.Forms;
namespace AutoCloseMessageBox
{
public static class MessageBoxAutoClose
{
public static void Show(string message, string caption, int timeout)
{
Timer timer = new Timer();
timer.Interval = timeout;
timer.Tick += (sender, e) =>
{
timer.Stop();
IntPtr mbWnd = FindWindow(null, caption);
if (mbWnd != IntPtr.Zero)
{
SendMessage(mbWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
}
};
timer.Start();
MessageBox.Show(message, caption);
}
[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, UInt32 Msg, IntPtr wParam, IntPtr lParam);
private const UInt32 WM_CLOSE = 0x0010;
}
public class Program
{
static void Main(string[] args)
{
MessageBoxAutoClose.Show("This message box will automatically close in 5 seconds.", "Auto Close", 5000);
}
}
}
这段代码定义了一个名为MessageBoxAutoClose
的静态类,其中包含了一个名为Show
的静态方法。该方法接受三个参数:message
表示消息框中显示的消息内容,caption
表示消息框的标题,timeout
表示消息框自动关闭的时间间隔(以毫秒为单位)。
在Show
方法中,首先创建了一个定时器timer
,并设置其间隔为timeout
。然后通过定时器的Tick
事件来处理定时器到期时的逻辑。在事件处理程序中,首先停止定时器,然后通过FindWindow
函数找到指定标题的消息框的句柄mbWnd
。如果找到了消息框的句柄,就使用SendMessage
函数发送关闭消息给消息框,从而实现自动关闭。
最后,在Main
方法中调用MessageBoxAutoClose.Show
方法来显示一个自动关闭的消息框,其中消息内容为"This message box will automatically close in 5 seconds.",标题为"Auto Close",关闭时间为5000毫秒(即5秒)。
请注意,这只是一个简单的示例代码,实际应用中可能需要根据具体情况进行适当的修改和扩展。
领取专属 10元无门槛券
手把手带您无忧上云