爱悠闲 > WinForm中实现自动关闭的MessageBox(CSharp)

WinForm中实现自动关闭的MessageBox(CSharp)

标签: winform,string,icons,winapi,class,user  |  作者: lijshuai 相关  |  发布日期 : 2015-11-23  |  热度 : 780°
WinForm中自定义类实现自动关闭的MessageBox实例.
using System;
using System.Windows.Forms;
using System.Threading;
using System.Runtime.InteropServices;

namespace CustomControls
{
    /// <summary>
    /// 自定义关闭消息窗体
    /// </summary>
    public static class CusMessageBox
    {
        //常量定义
         private const int WM_CLOSE = 0x10;

        // WinAPI 函数声明
         [DllImport("user32.dll",SetLastError = true)]
        static extern IntPtr FindWindow(string strClassName, string strWindowName);

        [DllImport("user32.dll",CharSet=CharSet.Auto)]
        static extern int PostMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lPara);

        /// <summary>
        /// 显示消息函数
         /// </summary>
        /// <param name="strMsg">消息信息</param>
        /// <param name="strTitle">显示标题</param>
        /// <param name="btns">按钮类型</param>
        /// <param name="icons">图标类型</param>
        /// <param name="iShowTimeSpan">等待时间(毫秒)</param>
        public static void Show(string strMsg, string strTitle, MessageBoxButtons btns, MessageBoxIcon icons, int iShowTimeSpan)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(CloseWindow), new CloseEntity() {Title=strTitle,TimeOutSpan = iShowTimeSpan });
            MessageBox.Show(strMsg, strTitle, btns, icons);
        }

        /// <summary>
        /// 关闭窗口线程执行体
         /// </summary>
        /// <param name="state"></param>
        private static void CloseWindow(object state)
        {
            CloseEntity cs = state as CloseEntity;
            Thread.Sleep(cs.TimeOutSpan);
            IntPtr dlg = FindWindow(null, cs.Title);
            if (dlg != IntPtr.Zero)
            {
	       //关闭弹出消息窗口
                 PostMessage(dlg, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
            }
        }
    }

    public class CloseEntity
    {
        private string strTitle;//标题
         private int iTimeOutSpan;//等待时间(毫秒)

        public string Title
        {
            get { return strTitle; }
            set { strCaption = value; }
        }

        public int TimeOutSpan
        {
            get { return iTimeOutSpan; }
            set { iTimeOutSpan = value; }
        }
    }
}