C# Message自动关闭

参考:http://t.csdn.cn/zUGus

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace WindowsApplication1
{
    public partial classAutoDeleteMessageBox : Form
    {
        /*
        通过[DllImport]特性引入user32.dll的FindWIndow方法,用于搜索具有指定窗口类和标题的窗口,,并将窗口句柄存储在 hWnd 中.
        lpClassName是要搜索的窗口类的名称,lpWindowName是要搜索的窗口的标题名称。
        */
        [DllImport("user32.dll", EntryPoint ="FindWindow", CharSet = CharSet.Auto)]
        private extern static IntPtr FindWindow(string lpClassName, string lpWindowName);

        /*
        通过[DllImport]特性引入user32.dll的PostMessage方法,用于向具有特定句柄的窗口发送指定消息,这里是 WM_CLOSE,以请求关闭该窗口。
        hWnd是窗口句柄。
        msg 是一个整数值,代表要发送的 Windows 消息。
        wParam,lParam是 Windows 消息的参数。它们的具体含义取决于消息类型。在发送 WM_CLOSE 消息时,通常不需要使用这些参数,因此它们被设置为 IntPtr.Zero,表示没有特定的参数传递给 WM_CLOSE 消息。    
        */
        [DllImport("user32.dll", CharSet =CharSet.Auto)]
        public static extern int PostMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);

        public const int WM_CLOSE = 0x10;

        public AutoDeleteMessageBox()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender,EventArgs e)
        {
            StartKiller();
            MessageBox.Show("3秒钟后自动关闭MessageBox窗口", "MessageBox");
        }
        //通过计时器实现倒计时,在触发事件中指定user.dll的两个方法自动关闭窗体。
        private void StartKiller()
        {
            Timer timer = new Timer();
            timer.Interval = 3000; //3秒启动
            timer.Tick+= new EventHandler(Timer_Tick);
            timer.Start();
        }

        private void Timer_Tick(object sender, EventArgse)
        {
            KillMessageBox();
            //停止Timer
            ((Timer)sender).Stop();
        }

        private void KillMessageBox()
        {
            //按照MessageBox的标题,找到MessageBox的窗口
            IntPtr ptr= FindWindow(null, "MessageBox");
            if (ptr !=IntPtr.Zero)
            {
                //找到则关闭MessageBox窗口
                PostMessage(ptr, WM_CLOSE,IntPtr.Zero, IntPtr.Zero);
            }
        }
    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值