winform 可自动关闭的消息框

主要就是利用 Window API 来实现功能

学习了

https://blog.csdn.net/sunxiaotianmg/article/details/17136719

https://blog.csdn.net/tpstu/article/details/44566581

这两篇,讲的蛮不错的

 

要用到 InteropServices 这个,就是下面那个,其实复制主要程序之后,直接 ALT + ENTER 就行了

using System.Runtime.InteropServices;

 

伸手党简单复制以下程序即可,做了标注,使用时,直接调用 ShowMessageBoxTimeout()就行

 

        #region 自动关闭消息框

        // 寻找窗口的API函数
        [DllImport("user32.dll", SetLastError = true)]
        static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        // 关闭窗口的API函数
        [DllImport("user32.dll")]
        static extern bool EndDialog(IntPtr hDlg, out IntPtr nResult);

        /// <summary>
        /// 可定时自动关闭的消息框 ,
        /// text-->内容 ,
        /// caption-->标题 ,
        /// buttons-->MessageBoxButtons.XX ,
        /// timeout-->定时
        /// </summary>
        /// <param name="text">消息框的主体内容</param>
        /// <param name="caption">消息框的标题内容</param>
        /// <param name="buttons">消息按钮,MessageBoxButtons.XX</param>
        /// <param name="timeout">自动关闭定时,单位毫秒</param>
        public void ShowMessageBoxTimeout(string text, string caption,
             MessageBoxButtons buttons, int timeout)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(CloseMessageBox),
               new CloseState(caption, timeout));
            MessageBox.Show(text, caption, buttons);
        }

        // 定义类
        private class CloseState
        {
            private int _Timeout;

            ///<summary>
            /// 单位毫秒 1s = 1000ms
            ///</summary>
            public int Timeout
            {
                get
                {
                    return _Timeout;
                 }
             }

            private string _Caption;

            ///<summary>
            /// 提示窗口的标题
            ///</summary>
            public string Caption
            {
                get
                {
                    return _Caption;
                 }
             }

            public CloseState(string caption, int timeout)
            {
                 _Timeout = timeout;
                 _Caption = caption;
             }
         }

        private void CloseMessageBox(object state)
        {
            CloseState closeState = state as CloseState;

            Thread.Sleep(closeState.Timeout);
        IntPtr dlg = FindWindow(null, closeState.Caption);

            if (dlg != IntPtr.Zero)
            {
                IntPtr result;
                EndDialog(dlg, out result);
            }
        }

        #endregion

posted @ 2021-08-23 14:49  Lee597  阅读(252)  评论(0)    收藏  举报