首页
学习
活动
专区
工具
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秒)。

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

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

相关·内容

领券