您现在的位置:首页 >> 软件开发 >> 内容

C# winform编程实现自动关闭MessageBox对话框

时间:2023-12-12 23:13:44 点击:

  核心提示:在C# winform编程中实现自动关闭MessageBox对话框,需要配合一个定时器,下面代码是一个timer4定时器的例子。原理是:在打开对话框前,先执行一个函数,该函数的作用时在对话框打开3秒后...

在C# winform编程中实现自动关闭MessageBox对话框,需要配合一个定时器,下面代码是一个timer4定时器的例子。原理是:在打开对话框前,先执行一个函数,该函数的作用时在对话框打开3秒后自动关闭对话框。下面代码直接复制粘贴到主程序区即可。


        [DllImport("user32.dll", EntryPoint = "FindWindow", CharSet = CharSet.Auto)]
        private extern static IntPtr FindWindow(string lpClassName, string lpWindowName);
        [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;


        //此处定义要打开的对话框的内容*****************   
        private void button1_Click(object sender, EventArgs e)
        {
           StartKiller(); //开启定时关闭对话框功能
           MessageBox.Show("3秒钟后自动关闭MessageBox窗口", "MessageBox");
        }

        private void StartKiller()
        {
          timer4.Interval = 3000; //3秒启动
          timer4.Tick += new EventHandler(Timer_Tick);
          timer4.Start();
        }
        private void Timer_Tick(object sender, EventArgs e)
        {
          KillMessageBox();
          timer4.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相关评论
发表我的评论
  • 大名:
  • 内容:
  • 陈工笔记(www.dui580.com) © 2024 版权所有 All Rights Reserved.
  • 站长:陈工 微信号:chengongbiji QQ:24498854
  • Powered by 陈工