首页 > 编程语言 >c#自动关闭 MessageBox 弹出的窗口

c#自动关闭 MessageBox 弹出的窗口

时间:2024-07-24 13:24:35浏览次数:5  
标签:MessageBox form c# System DialogResult 弹出 new using

第一种方法:

原理:

1、我们都知道,MessageBox弹出的窗口是模式窗口,模式窗口会自动阻塞父线程的,只有关闭了MessageBox的窗口后才会运行下面的代码。

2、所以可以考虑在MessageBox前先增加一个用于“杀”掉MessageBox窗口的线程。因为需要在规定时间内“杀”掉窗口,所以我们可以直接考虑使用Timer类,然后调用系统API关闭窗口。

3、这个工作线程等待一定时间后开始查找消息对话框的窗口句柄,找到后调用SendMessage API 函数关闭这个消息对话框

4、这个只能在form框调用

具体实现:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Windows.Forms;

namespace ConsoleApp2
{
    public partial class Form1 : Form
    {

        // 查找窗口
        [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, uint Msg, IntPtr wParam, IntPtr lParam);

        // 关闭消息
        private const uint WM_CLOSE = 0x0010;
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            ShowMessage("测试测试", 2);
        }

        private void ShowMessage(string sMsg, int nSecondCount)
        {
            // 创建一个线程来执行倒计时操作
            Thread thread = new Thread(() =>
            {
                // 倒计时3秒
                Thread.Sleep(nSecondCount * 1000);

                // 关闭MessageBox
                if (InvokeRequired)
                {
                    Invoke(new Action(() => { CloseMessageBox(); }));
                }
                else
                {
                    CloseMessageBox();
                }
            });

            // 启动线程
            thread.Start();

            // 弹出MessageBox提示框,注意:这里的标题必须与下方查找关闭MessageBox里的标题一致。
            MessageBox.Show(sMsg, "完成提示");
        }

        private void CloseMessageBox()
        {
            // 查找并关闭MessageBox窗口
            IntPtr hwnd = FindWindow(null, "完成提示");//一致
            if (hwnd != IntPtr.Zero)
            {
                SendMessage(hwnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
            }
        }

        private void Form1_SizeChanged(object sender, EventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}

第二种方法:

原理:

这个直接就是自己画一个form然后定时器关闭 ,博主已经画好尺寸了,和MessageBox的尺寸一致,可以直接调用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using System.Windows.Forms;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            ShowTimedMessageWithYesNoButtons("123123123", 3000);
           MessageBox.Show("123123123", "重新打印标签", MessageBoxButtons.YesNo);
            Console.ReadLine();
        }


        public static DialogResult ShowTimedMessageWithYesNoButtons(string message, int timeoutMilliseconds)
        {
            Form form = new Form();
            Label label = new Label();
            Button yesButton = new Button();
            Button noButton = new Button();
            form.Text = "重新打印标签"; 
            form.Size = new Size(300, 150);
            label.Size = new Size(250, 50);
            yesButton.Size = new Size(80, 30);
            noButton.Size = new Size(80, 30);
            form.StartPosition = FormStartPosition.CenterScreen; // 让表单在屏幕中央显示  

            // 设置标签位置在表单中央  
            label.Location = new Point((form.Width - label.Width) / 2, 20);

            // 设置 “是” 按钮位置在表单中央底部  
            yesButton.Location = new Point((form.Width - yesButton.Width - noButton.Width - 10) / 2, form.Height - yesButton.Height - 50);

            // 设置 “否” 按钮位置在表单中央底部  
            noButton.Location = new Point(yesButton.Location.X + yesButton.Width + 10, form.Height - noButton.Height - 50);


            label.Text = message;
            Font existingFont = new Font("Arial", 12, FontStyle.Regular);
            label.Font = new Font(existingFont, FontStyle.Regular); /// 设置字体为微软雅黑,大小为12,正常样式  

            yesButton.Text = "是";
            yesButton.Click += (sender, e) => form.DialogResult = DialogResult.Yes;
            noButton.Text = "否";
            noButton.Click += (sender, e) => form.DialogResult = DialogResult.No;

            form.Controls.Add(label);
            form.Controls.Add(yesButton);
            form.Controls.Add(noButton);

            Timer timer = new Timer();
            timer.Interval = timeoutMilliseconds; // 设置定时器间隔为5秒  
            timer.Tick += (sender, e) =>
            {
                form.DialogResult = DialogResult.None;
                form.Close();
                timer.Stop(); // 停止定时器  
                timer.Dispose(); // 释放资源  
            };

            form.FormClosing += (sender, e) =>
            {
                if (form.DialogResult == DialogResult.None)
                {
                    form.DialogResult = DialogResult.No; // 如果5秒后还未确认,则默认为“否”  
                }
            };

            timer.Start(); // 启动定时器  

            form.ShowDialog();

            if (form.DialogResult == DialogResult.Yes || form.DialogResult == DialogResult.No)
            {
                Console.WriteLine(form.DialogResult);
                return form.DialogResult;
            }
            Console.WriteLine(DialogResult.No);
            return DialogResult.No;
        }

    }
}


标签:MessageBox,form,c#,System,DialogResult,弹出,new,using
From: https://blog.csdn.net/weixin_44941809/article/details/140641653

相关文章

  • 如何使用整数键制作 TypedDict?
    是否可以在TypedDict中使用整数键(类似于dict?)。尝试一个简单的示例:fromtypingimportTypedDictclassMoves(TypedDict):0:int=11:int=2抛出:SyntaxError:illegaltargetforannotation似乎只支持Mapping[str,int......
  • C/C++ 建议编译选项
    本文介绍一些OI选手可能用到的编译选项。警告选项在程序设计中,我们可能不小心写出一些不合常理的代码语句。大部分情况下,这会使程序行为脱离我们的本意。使编译器发出警告可以在一定程度下规避这种情况。-Wall启动常见的警告选项,包括但不限于:未使用的变量、函数或标签未......
  • oracle大表性能优化
    1不修改表结构的优化1.1收缩表,降低高水位线ALTERTABLETESTENABLEROWMOVEMENT;ALTERTABLETESTSHRINKSPACE;1.2对表收集统计信息BEGINDBMS_STATS.GATHER_TABLE_STATS(ownname=>user,tabname=>'TEST');END;1.3使用oracle的并行查询功......
  • 易优CMS模板标签field字段值输出指定栏目ID的下级栏目的文档列表
    【基础用法】标签:field描述:获取channelartlist标签里的字段值,field标签只能在channelartlist标签里使用。用法:{eyou:channelartlisttypeid='栏目ID'type='son'row='20'}<ahref='{eyou:fieldname='typeurl'/}'>{eyou:fieldname='typen......
  • 帝国CMS网站给前台会员批量发送邮件
    一、登录后台,单击“用户”菜单,选择“批量发送邮件”子菜单,进入批量发送邮件界面: 二、进入批量发送邮件界面:接收会员组选择接收邮件的会员组(全选用"CTRL+A",选择多个用CTRL/SHIFT+点击选择)。每组发送个数分组发送设置,防止php超时中断执行。标题......
  • 易优CMS模板标签relevarticle相关文档
    [基础用法]标签:relevarticle描述:通过前3个TAG标签或前3个关键词,检索整站文档标题中含有tag标签或者关键词的相关文档,进行关联。在没有tag标签情况下,就以前3个关键词检索文档标题进行关联。这个标签随着数据量的增加可能会比较影响检索性能。提示:使用该标签之前,必须先安装相关文档......
  • 易优CMS模板标签uibackground背景图片在模板文件index.htm中调用uibackground标签,实现
    【基础用法】标签:uibackground描述:背景图片上传标签,使用时结合html一起才能完成可视化布局,只针对具有可视化功能的模板。用法:<divclass="eyou-edit"e-id="文件模板里唯一的数字ID"e-page='文件模板名'e-type="background"style="background-image:url({eyou:uibackgrounde......
  • Python 类型暗示​​一个充满 myclass 对象的双端队列
    使用Python3.6或更高版本,我想输入提示一个返回MyClass对象的函数myfunc我如何提示myqueue是一个deque|||充满MyClass对象?objects?fromcollectionsimportdequeglobal_queue=deque()classMyClass:passdefmyfunc(m......
  • SpringMVC基础
    SpringMVCssm:mybatis+Spring+SpringMVCMVC三层架构1、什么是MVCMVC是模型(Model)、视图(View)、控制器(Controller)的简写,是一种软件设计规范是将业务逻辑、数据、显示分离的方法来组织代码MVC的主要作用是降低了视图与业务逻辑间的双向耦合MVC不是一种设计模式,MVC是一......
  • 在 Celery 任务中获取 task_id
    这可能是一个愚蠢的问题,但它让来自Ruby背景的我感到困惑。当我尝试打印它时,我有一个看起来像这样的对象。printcelery.AsyncResult.task_id>>><propertyobjectat0x10c383838>我期望task_id属性的实际值是打印在这里。我如何获得实际值?更新1@celery......