首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

在C#中自动关闭消息框

可以通过使用定时器来实现。以下是一个示例代码:

代码语言:csharp
复制
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秒)。

请注意,这只是一个简单的示例代码,实际应用中可能需要根据具体情况进行适当的修改和扩展。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

6分5秒

063-在nginx 中关闭keepalive

8分15秒

99、尚硅谷_总结_djangoueditor添加的数据在模板中关闭转义.wmv

59秒

BOSHIDA DC电源模块在工业自动化中的应用

46分33秒

雁栖学堂-湖存储专题直播第九期

1分51秒

Ranorex Studio简介

1分0秒

一分钟让你快速了解FL Studio21中文版

2分59秒

Elastic 5分钟教程:使用机器学习,自动化异常检测

2分3秒

小白教程:如何在Photoshop中制作真实的水波纹效果?

1分52秒

Web网页端IM产品RainbowChat-Web的v7.0版已发布

1分53秒

安全帽佩戴识别系统

1分36秒

SOLIDWORKS Electrical 2023电气设计解决方案全新升级

7分38秒

人工智能:基于强化学习学习汽车驾驶技术

领券