messagebox 订阅
MessageBox指的是显示一个模态对话框,其中包含一个系统图标、 一组按钮和一个简短的特定于应用程序消息,如状态或错误的信息。消息框中返回一个整数值,该值指示用户单击了哪个按钮。 展开全文
MessageBox指的是显示一个模态对话框,其中包含一个系统图标、 一组按钮和一个简短的特定于应用程序消息,如状态或错误的信息。消息框中返回一个整数值,该值指示用户单击了哪个按钮。
信息
编程语言
C/C++,VB
函数名
MessageBox
作    用
弹出模式对话框
中文名
模态对话框
外文名
MessageBox
所属头文件
Windows.h和afxwin.h
MessageBox函数
hWnd:此参数代表消息框拥有的窗口。如果为NULL,则消息框没有拥有窗口。lpText:消息框的内容。如果使用了Unicode库,则把文本变成:lpCaption:消息框的标题。如果使用了Unicode库,则把文本变成:uType:指定一个决定对话框的内容和行为的位标志集。此参数可以为下列标志组中标志的组合。指定下列标志中的一个来显示消息框中的按钮以及图标。按钮:附:图标:形态:其他:通过将 uType 参数设置为相应的标志值,可以在消息框中系统图标,具体图标可参见MSDN网站。添加两个从右到左标记 (RLMs),Unicode 格式字符中用 U+200F表示。在消息框显示字符串的开头被由 MessageBox 渲染引擎解释,以致造成 MessageBox 的阅读顺序,呈现为从右向左 (RTL) 。当您使用一个系统模式消息框指示时,当系统内存不足时,由 lpText 和 lpCaption 的参数的字符串不应被从资源文件,因为加载资源的尝试可能会失败。如果在一个对话框存在时创建一个消息框,则使用对话框的句柄作为hWnd 参数。hWnd参数不应指定为一个子窗口,就像对话框中的控件一样。第一步:弹出对话框。语句: 选择是:语句: 选择否:语句:
收起全文
精华内容
下载资源
问答
  • PyQt自定义MessageBox

    2021-02-05 20:54:49
    PyQt5 自定义MessageBox

    本来想直接继承QMessageBox,但是继承之后窗口的大小、stylesheet什么的都不太好搞定,于是重新做了一个,参考:QT自定义messagebox弹窗,使用PyQt重写

    布局
    在这里插入图片描述
    自动生成代码

    from PyQt5 import QtCore, QtGui, QtWidgets
    
    class Ui_Dialog(object):
        def setupUi(self, Dialog):
            Dialog.setObjectName("Dialog")
            Dialog.resize(400, 165)
            Dialog.setStyleSheet("QDialog {\n"
    "    background-color:white;\n"
    "}\n"
    "QPushButton {\n"
    "    border:2px solid rgb(0, 0, 127);\n"
    "    padding:5px;\n"
    "    border-radius:15px;\n"
    "    color:#000000;\n"
    "    background-color:transparent;\n"
    "    font-family: \'Microsoft YaHei Ui\';\n"
    "    font-size: 9pt;\n"
    "    font-weight: bold;\n"
    "}\n"
    "QPushButton:hover {\n"
    "    color:#0078d7;\n"
    "    background:rgb(255, 255, 255);\n"
    "    border:2px solid #0078d7;\n"
    "}\n"
    "QPushButton:pressed {\n"
    "    color:#000000;\n"
    "    background:#B8C6D1;\n"
    "}\n"
    "")
            self.verticalLayout = QtWidgets.QVBoxLayout(Dialog)
            self.verticalLayout.setObjectName("verticalLayout")
            self.horizontalLayout = QtWidgets.QHBoxLayout()
            self.horizontalLayout.setObjectName("horizontalLayout")
            spacerItem = QtWidgets.QSpacerItem(15, 20, QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Minimum)
            self.horizontalLayout.addItem(spacerItem)
            self.pbt_icon = QtWidgets.QPushButton(Dialog)
            sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
            sizePolicy.setHorizontalStretch(0)
            sizePolicy.setVerticalStretch(0)
            sizePolicy.setHeightForWidth(self.pbt_icon.sizePolicy().hasHeightForWidth())
            self.pbt_icon.setSizePolicy(sizePolicy)
            self.pbt_icon.setMinimumSize(QtCore.QSize(68, 64))
            self.pbt_icon.setStyleSheet("background-color: transparent;\n"
    "border:none;")
            self.pbt_icon.setText("")
            self.pbt_icon.setIconSize(QtCore.QSize(64, 64))
            self.pbt_icon.setFlat(True)
            self.pbt_icon.setObjectName("pbt_icon")
            self.horizontalLayout.addWidget(self.pbt_icon)
            spacerItem1 = QtWidgets.QSpacerItem(20, 20, QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Minimum)
            self.horizontalLayout.addItem(spacerItem1)
            self.lb_text = QtWidgets.QLabel(Dialog)
            sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Preferred)
            sizePolicy.setHorizontalStretch(0)
            sizePolicy.setVerticalStretch(0)
            sizePolicy.setHeightForWidth(self.lb_text.sizePolicy().hasHeightForWidth())
            self.lb_text.setSizePolicy(sizePolicy)
            self.lb_text.setMinimumSize(QtCore.QSize(250, 0))
            font = QtGui.QFont()
            font.setFamily("Microsoft YaHei UI")
            self.lb_text.setFont(font)
            self.lb_text.setStyleSheet("QLabel {\n"
    "    background-color:transparent;\n"
    "}")
            self.lb_text.setAlignment(QtCore.Qt.AlignJustify|QtCore.Qt.AlignVCenter)
            self.lb_text.setWordWrap(True)
            self.lb_text.setObjectName("lb_text")
            self.horizontalLayout.addWidget(self.lb_text)
            self.verticalLayout.addLayout(self.horizontalLayout)
            self.hlayout = QtWidgets.QHBoxLayout()
            self.hlayout.setSizeConstraint(QtWidgets.QLayout.SetFixedSize)
            self.hlayout.setObjectName("hlayout")
            spacerItem2 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
            self.hlayout.addItem(spacerItem2)
            self.verticalLayout.addLayout(self.hlayout)
            self.retranslateUi(Dialog)
            QtCore.QMetaObject.connectSlotsByName(Dialog)
    
        def retranslateUi(self, Dialog):
            _translate = QtCore.QCoreApplication.translate
            Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
            self.lb_text.setText(_translate("Dialog", "提示框"))
    

    MessageBox

    from PyQt5.QtWidgets import QDialog, QApplication, QPushButton, QSizePolicy
    from PyQt5.QtCore import Qt, QSize
    from PyQt5.QtGui import QPixmap, QIcon
    from Ui_MessageBox import Ui_Dialog
    import sys
    
    class MessageBox(QDialog):
        """ 自定义MessageBox,继承自QDialog     
        其中有3个static method可用: information, warning, error,使用方法与QMessageBox基本一致
        Args:   
            parent: 父窗口
            title: MessageBox窗口标题 Window Title
            text: 消息文本
            btype: 按钮,有五种类型按钮:YES, NO, CANCLE, CLOSE, OK
            default: 默认按钮,默认值为YES
        """
        # 仅支持这几个按键
        YES    = 0x01
        NO     = 0x02
        CANCEL = 0x04
        CLOSE  = 0x08
        OK     = 0x10
        # 返回值
        retValue = 0
    
        def __init__(self, parent, title: str, text: str, btype=YES, default=YES):
            super().__init__(parent)
            self.ui = Ui_Dialog()
            self.ui.setupUi(self)
            self.setWindowModality(Qt.ApplicationModal)
            self.setAttribute(Qt.WA_QuitOnClose, True)
            self.setWindowTitle(title)
            self.btnList = {}
            self.ui.lb_text.setText(text)
            self.create_button(btype)
            self.set_default_btn(btype, default)
    
        def create_button(self, btype):
            # 如果按钮是yes
            if btype & MessageBox.YES == MessageBox.YES:
                self.yesbtn = QPushButton(self)
                self.set_button(self.yesbtn, u'Yes')
                self.btnList[MessageBox.YES] = self.yesbtn
                self.yesbtn.clicked.connect(self.btn_yes)
            # 如果按钮是no
            if btype & MessageBox.NO == MessageBox.NO:
                self.nobtn = QPushButton(self)
                self.set_button(self.nobtn, u'No')
                self.btnList[MessageBox.NO] = self.nobtn
                self.nobtn.clicked.connect(self.btn_no)
            # 如果按钮是cancel
            if btype & MessageBox.CANCEL == MessageBox.CANCEL:
                self.cancelbtn = QPushButton(self)
                self.set_button(self.cancelbtn, u'Cancel')
                self.btnList[MessageBox.CANCEL] = self.cancelbtn
                self.cancelbtn.clicked.connect(self.btn_cancel)
            # 如果按钮是close
            if btype & MessageBox.CLOSE == MessageBox.CLOSE:
                self.closebtn = QPushButton(self)
                self.set_button(self.closebtn, u'Close')
                self.btnList[MessageBox.CLOSE] = self.closebtn
                self.closebtn.clicked.connect(self.btn_close)
            # 如果按钮是ok
            if btype & MessageBox.OK == MessageBox.OK:
                self.okbtn = QPushButton(self)
                self.set_button(self.okbtn, u'Ok')
                self.btnList[MessageBox.OK] = self.okbtn
                self.okbtn.clicked.connect(self.btn_ok)
    
        def set_default_btn(self, btype, default):
            # default键必须是一个独立的按键
            if default not in {MessageBox.YES, MessageBox.NO, MessageBox.CANCEL, MessageBox.OK, MessageBox.CLOSE}:
                return
            if default & btype != 0:
                self.btnList[default].setDefault(True)
    
        def set_button(self, btn:QPushButton, text:str):
            # 设置按钮的一些参数
            btn.setText(text)
            btn.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
            btn.setFixedSize(QSize(95, 35))
            self.ui.hlayout.addWidget(btn)
    
        def btn_yes(self):
            MessageBox.retValue = MessageBox.YES
            self.close()
            
        def btn_no(self):
            MessageBox.retValue = MessageBox.NO
            self.close()
            
        def btn_cancel(self):
            MessageBox.retValue = MessageBox.CANCEL
            self.close()
            
        def btn_close(self):
            MessageBox.retValue = MessageBox.CLOSE
            self.close()
            
        def btn_ok(self):
            MessageBox.retValue = MessageBox.OK
            self.close()
    
        def ret_val(self):
            return MessageBox.retValue
    
        # 使用时调用的静态方法
        @staticmethod
        def information(parent, title, text, btype=YES, default=YES):
            box = MessageBox(parent, title, text, btype, default)
            box.ui.pbt_icon.setIcon(QIcon(QPixmap(":/mainui/icon/notify.png")))
            box.exec()
            return box.ret_val()
    
        @staticmethod
        def warning(parent, title, text, btype=YES, default=YES):
            box = MessageBox(parent, title, text, btype, default)
            box.ui.pbt_icon.setIcon(QIcon(QPixmap(":/mainui/icon/warning.png")))
            box.exec()
            return box.ret_val()
    
        @staticmethod
        def error(parent, title, text, btype=YES, default=YES):
            box = MessageBox(parent, title, text, btype, default)
            box.ui.pbt_icon.setIcon(QIcon(QPixmap(":/mainui/icon/error.png")))
            box.exec()
            return box.ret_val()
    

    将其中图标换成自己的图标(推荐一个网站:iconfont-阿里巴巴矢量图标库)。
    使用

    # information
    btn = MessageBox.information(None, 'messagebx', '这是一个messagebox', MessageBox.YES | MessageBox.NO, MessageBox.YES)
    
    # warning
    btn = MessageBox.warning(None, 'messagebx', '这是一个messagebox', MessageBox.YES | MessageBox.CANCEL | MessageBox.CLOSE)
    
    # error
    btn = MessageBox.error(None, 'messagebx', '这是一个messagebox', MessageBox.OK)
    

    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述

    展开全文
  • Java实现MessageBox

    2021-02-12 16:49:06
    MessageBox类弹出Java应用程序的警告,错误。 package com.nova.colimas.install; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt....

    MessageBox类弹出Java应用程序的警告,错误。 package com.nova.colimas.install; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.

    MessageBox类弹出Java应用程序的警告,错误。

    package com.nova.colimas.install;

    import java.awt.event.ActionEvent;

    import java.awt.event.ActionListener;

    import java.awt.event.KeyEvent;

    import java.awt.event.KeyListener;

    import java.awt.event.WindowEvent;

    import java.awt.event.WindowListener;

    import javax.swing.*;

    import java.awt.*;

    public class MessageBox implements Runnable, ActionListener, WindowListener,

    KeyListener {

    // ---------- Private Fields ------------------------------

    private ActionListener listener;

    private JDialog dialog;

    private String closeWindowCommand = "CloseRequested";

    private String title;

    private JFrame frame;

    private boolean frameNotProvided;

    private JPanel buttonPanel = new JPanel();

    // ---------- Initialization ------------------------------

    /**

    * This convenience constructor is used to delare the listener that will be

    * notified when a button is clicked. The listener must implement

    * ActionListener.

    */

    public MessageBox(ActionListener listener) {

    this();

    this.listener = listener;

    }

    /**

    * This constructor is used for no listener, such as for a simple okay

    * dialog.

    */

    public MessageBox() {

    }

    // Unit test. Shows only simple features.

    public static void main(String args[]) {

    MessageBox box = new MessageBox();

    box.setTitle("Test MessageBox");

    box.askYesNo("Tell me now./nDo you like Java?");

    }

    // ---------- Runnable Implementation ---------------------

    /**

    * This prevents the caller from blocking on ask(), which if this class is

    * used on an awt event thread would cause a deadlock.

    */

    public void run() {

    dialog.setVisible(true);

    }

    // ---------- ActionListener Implementation ---------------

    public void actionPerformed(ActionEvent evt) {

    dialog.setVisible(false);

    dialog.dispose();

    if (frameNotProvided)

    frame.dispose();

    if (listener != null) {

    listener.actionPerformed(evt);

    }

    }

    // ---------- WindowListener Implementatons ---------------

    public void windowClosing(WindowEvent evt) {

    // User clicked on X or chose Close selection

    fireCloseRequested();

    }

    public void windowClosed(WindowEvent evt) {

    }

    public void windowDeiconified(WindowEvent evt) {

    }

    public void windowIconified(WindowEvent evt) {

    }

    public void windowOpened(WindowEvent evt) {

    }

    public void windowActivated(WindowEvent evt) {

    }

    public void windowDeactivated(WindowEvent evt) {

    }

    // ---------- KeyListener Implementation ------------------

    public void keyTyped(KeyEvent evt) {

    }

    public void keyPressed(KeyEvent evt) {

    if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) {

    fireCloseRequested();

    }

    }

    public void keyReleased(KeyEvent evt) {

    }

    private void fireCloseRequested() {

    ActionEvent event = new ActionEvent(this, ActionEvent.ACTION_PERFORMED,

    closeWindowCommand);

    actionPerformed(event);

    }

    // ---------- Public Methods ------------------------------

    /**

    * This set the listener to be notified of button clicks and WindowClosing

    * events.

    */

    public void setActionListener(ActionListener listener) {

    this.listener = listener;

    }

    public void setTitle(String title) {

    this.title = title;

    }

    /**

    * If a Frame is provided then it is used to instantiate the modal Dialog.

    * Otherwise a temporary Frame is used. Providing a Frame will have the

    * effect of putting the focus back on that Frame when the MessageBox is

    * closed or a button is clicked.

    */

    public void setFrame(JFrame frame) { // Optional

    this.frame = frame;

    }

    /**

    * Sets the ActionCommand used in the ActionEvent when the user attempts to

    * close the window. The window may be closed by clicking on "X", choosing

    * Close from the window menu, or pressing the Escape key. The default

    * command is "CloseRequested", which is just what a Close choice button

    * would probably have as a command.

    */

    public void setCloseWindowCommand(String command) {

    closeWindowCommand = command;

    }

    /**

    * The

    *

    * @param label

    *            will be used for the button and the

    * @param command

    *            will be returned to the listener.

    */

    public void addChoice(String label, String command) {

    JButton button = new JButton(label);

    button.setActionCommand(command);

    button.addActionListener(this);

    button.addKeyListener(this);

    buttonPanel.add(button);

    }

    /**

    * A convenience method that assumes the command is the same as the label.

    */

    public void addChoice(String label) {

    addChoice(label, label);

    }

    /**

    * One of the "ask" methods must be the last call when using a MessageBox.

    * This is the simplest "ask" method. It presents the provided

    *

    * @param message.

    */

    public void ask(String message) {

    if (frame == null) {

    frame = new JFrame();

    frameNotProvided = true;

    } else {

    frameNotProvided = false;

    }

    dialog = new JDialog(frame, true); // Modal

    dialog.addWindowListener(this);

    dialog.addKeyListener(this);

    dialog.setTitle(title);

    dialog.setLayout(new BorderLayout(5, 5));

    JPanel messagePanel = createMultiLinePanel(message);

    JPanel centerPanel = new JPanel();

    centerPanel.add(messagePanel);

    dialog.add("Center", centerPanel);

    dialog.add("South", buttonPanel);

    dialog.pack();

    enforceMinimumSize(dialog, 200, 100);

    centerWindow(dialog);

    Toolkit.getDefaultToolkit().beep();

    // Start a new thread to show the dialog

    Thread thread = new Thread(this);

    thread.start();

    }

    /**

    * Same as ask(String message) except adds an "Okay" button.

    */

    public void askOkay(String message) {

    addChoice("Okay");

    ask(message);

    }

    /**

    * Same as ask(String message) except adds "Yes" and "No" buttons.

    */

    public void askYesNo(String message) {

    addChoice("Yes");

    addChoice("No");

    ask(message);

    }

    // ---------- Private Methods -----------------------------

    private JPanel createMultiLinePanel(String message) {

    JPanel mainPanel = new JPanel();

    GridBagLayout gbLayout = new GridBagLayout();

    mainPanel.setLayout(gbLayout);

    addMultilineString(message, mainPanel);

    return mainPanel;

    }

    // There are a variaty of ways to do this....

    private void addMultilineString(String message, Container container) {

    GridBagConstraints constraints = getDefaultConstraints();

    constraints.gridwidth = GridBagConstraints.REMAINDER;

    // Insets() args are top, left, bottom, right

    constraints.insets = new Insets(0, 0, 0, 0);

    GridBagLayout gbLayout = (GridBagLayout) container.getLayout();

    while (message.length() > 0) {

    int newLineIndex = message.indexOf('/n');

    String line;

    if (newLineIndex >= 0) {

    line = message.substring(0, newLineIndex);

    message = message.substring(newLineIndex + 1);

    } else {

    line = message;

    message = "";

    }

    JLabel label = new JLabel(line);

    gbLayout.setConstraints(label, constraints);

    container.add(label);

    }

    }

    private GridBagConstraints getDefaultConstraints() {

    GridBagConstraints constraints = new GridBagConstraints();

    constraints.weightx = 1.0;

    constraints.weighty = 1.0;

    constraints.gridheight = 1; // One row high

    // Insets() args are top, left, bottom, right

    constraints.insets = new Insets(4, 4, 4, 4);

    // fill of NONE means do not change size

    constraints.fill = GridBagConstraints.NONE;

    // WEST means align left

    constraints.anchor = GridBagConstraints.WEST;

    return constraints;

    }

    private void centerWindow(JDialog win) {

    Dimension screenDim = Toolkit.getDefaultToolkit().getScreenSize();

    // If larger than screen, reduce window width or height

    if (screenDim.width < win.getSize().width) {

    win.setSize(screenDim.width, win.getSize().height);

    }

    if (screenDim.height < win.getSize().height) {

    win.setSize(win.getSize().width, screenDim.height);

    }

    // Center Frame, Dialogue or Window on screen

    int x = (screenDim.width - win.getSize().width) / 2;

    int y = (screenDim.height - win.getSize().height) / 2;

    win.setLocation(x, y);

    }

    private void enforceMinimumSize(JDialog comp, int minWidth, int minHeight) {

    if (comp.getSize().width < minWidth) {

    comp.setSize(minWidth, comp.getSize().height);

    }

    if (comp.getSize().height < minHeight) {

    comp.setSize(comp.getSize().width, minHeight);

    }

    }

    } // End class

    在调用它的WindowsMain类里添加一个Close按钮,点击Close按钮时调用MessageBox选择yes或no。

    jCloseButton.addActionListener(new java.awt.event.ActionListener() {

    public void actionPerformed(java.awt.event.ActionEvent e) {

    //System.out.println("actionPerformed()"); // TODO Auto-generated Event stub actionPerformed()

    MessageBox box = new MessageBox();

    box.setTitle("Warning");

    box.askYesNo("Do you really want to exit?");

    //添加MessageBox的按钮事件Listener。

    box.setActionListener(new java.awt.event.ActionListener(){

    public void actionPerformed(java.awt.event.ActionEvent e){

    JButton button=(JButton)e.getSource();

    if(button.getText()=="Yes")

    System.exit(0);

    }        }

    );

    }

    });

    展开全文
  • 1、定义DataContext对象2、绑定属性3、泛型调用二、代码三、实例1、Toast(1)Toast.xaml(2)调用方法(3)效果预览2、简单MessageBox(1)MessageBoxSimple.xaml(2)调用方法(3)效果预览3、完整MessageBox(1)...

    WPF 自定义MessageBox系列

    第一节 简单MessageBox
    第二节 倒计时MessageBox
    第三节 自定义按钮的MessageBox
    第四节 界面操作分离的MessageBox(本节)
    第五节 替换系统的MessageBox



    前言

    本篇是上一篇《C# wpf 实现自定义按钮及Toast的MessageBox》的优化,将MessageBox的操作逻辑与界面完全分离了,这样做的好处是在于,界面的随意切换,操作逻辑可以不用改动或重写。


    一、如何分离?

    1、定义DataContext对象

    定义一个DataContext对象,将需要的数据全部定义在DataContext对象中,通过INotifyPropertyChanged实现双向通知。
    MessageBox需要的属性有:

    /// <summary>
    /// 消息框的标题
    /// </summary>
    public string Title{get;get;}
    /// <summary>
    /// 消息框的文本内容
    /// </summary>
    public string Context{get;get;}
    /// <summary>
    /// Yes按钮的文本
    /// </summary>
    public string YesText{get;get;}
    /// <summary>
    /// No按钮的文本
    /// </summary>
    public string NoText{get;get;}
    /// <summary>
    /// Yes选项剩余时间
    /// </summary>
    public TimeSpan? YesLeftTime{get;get;}
    /// <summary>
    /// No选项剩余时间
    /// </summary>
    public TimeSpan? NoLeftTime{get;get;}
    /// <summary>
    /// No按钮命令
    /// </summary>
    public ICommand NoCommand{get;get;}
    /// <summary>
    /// Yes按钮命令
    /// </summary>
    public ICommand YesCommand{get;get;}
    /// <summary>
    ///Cancel按钮命令
    /// </summary>
    public ICommand CancelCommand{get;get;}
    

    2、绑定属性

    在xaml中实现消息框的样式,并绑定上述属性。上述属性不需要全部绑定可以根据需要自行选择,比如只需要定义一个Toast则只绑定Context即可。

    <TextBlock  Text="{Binding Context}" />
    

    3、泛型调用

    将MessageBox的操作方法定义成泛型,根据具体传入的MessageBox与DataContext对象关联后再显示。比如将方法定义在MessageBoxHelper类中:
    MessageBox窗口

     MessageBoxHelper.ShowDialog<MessageBox>("Ensure?", "Yes", "No",TimeSpan.FromSeconds(10), null);
    

    Toast窗口

     MessageBoxHelper.Toast<Toast>("Hello word",TimeSpan.FromSeconds(10));
    

    二、代码

    代码的逻辑关系:
    在这里插入图片描述
    上图对应到代码:
    在这里插入图片描述

    将所有操作逻辑封装在MessageBoxHelper中:

    using System;
    using System.ComponentModel;
    using System.Runtime.InteropServices;
    using System.Windows;
    using System.Windows.Input;
    using System.Windows.Threading;
    namespace WpfApp1
    {
        /// <summary>
        /// 结果按钮
        /// </summary>
        public enum MessageBoxResultButton
        {
            Yes,
            No,
            Cancel
        }
        /// <summary>
        /// 结果
        /// </summary>
        public class MessageBoxResult
        {
            /// <summary>
            /// 结果按钮
            /// </summary>
            public MessageBoxResultButton Button { get; set; }
            /// <summary>
            /// Yes剩余时间
            /// </summary>
            public TimeSpan? YesLeftTime { get; set; }
            /// <summary>
            /// No剩余时间
            /// </summary>
            public TimeSpan? NoLeftTime { get; set; }
        }
        /// <summary>
        /// 业务数据对象
        /// </summary>
        public class MessageBoxDataContext : INotifyPropertyChanged
        {
            public event PropertyChangedEventHandler PropertyChanged;
            /// <summary>
            /// 消息框的标题
            /// </summary>
            public string Title
            {
                get { return _title; }
                set { _title = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Title")); }
            }
            /// <summary>
            /// 消息框的文本内容
            /// </summary>
            public string Context
            {
                get { return _context; }
                set { _context = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Context")); }
            }
            /// <summary>
            /// Yes按钮的文本
            /// </summary>
            public string YesText
            {
                get { return _yesText; }
                set { _yesText = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("YesText")); }
            }
            /// <summary>
            /// No按钮的文本
            /// </summary>
            public string NoText
            {
                get { return _noText; }
                set { _noText = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("NoText")); }
            }
            /// <summary>
            /// Yes选项剩余时间
            /// </summary>
            public TimeSpan? YesLeftTime
            {
                get { return _yesLeftTime; }
                set { _yesLeftTime = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("YesLeftTime")); }
            }
            /// <summary>
            /// No选项剩余时间
            /// </summary>
            public TimeSpan? NoLeftTime
            {
                get { return _noLeftTime; }
                set { _noLeftTime = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("NoLeftTime")); }
            }
            /// <summary>
            /// No按钮命令
            /// </summary>
            public ICommand NoCommand
            {
                get { return _noCommand; }
                set { _noCommand = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("NoCommand")); }
            }
            /// <summary>
            /// Yes按钮命令
            /// </summary>
            public ICommand YesCommand
            {
                get { return _yesCommand; }
                set { _yesCommand = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("YesCommand")); }
            }
            /// <summary>
            ///Cancel按钮命令
            /// </summary>
            public ICommand CancelCommand
            {
                get { return _cancleCommand; }
                set { _cancleCommand = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("CancelCommand")); }
            }
    
            /// <summary>
            ///结果
            /// </summary>
            public MessageBoxResult Result { internal set; get; }
            /// <summary>
            /// 倒计时的时钟
            /// </summary>
            internal DispatcherTimer Timer { set; get; }
            string _title = "tips";
            string _context = "Ensure?";
            string _yesText = "Yes";
            string _noText = "No";
            TimeSpan? _yesLeftTime;
            TimeSpan? _noLeftTime;
            ICommand _noCommand;
            ICommand _yesCommand;
            ICommand _cancleCommand;
        }
    
        public class MessageBoxHelper
        {
            class Command : ICommand
            {
                Action<object> _action;
                public Command(Action<object> action)
                {
                    _action = action;
                }
                public event EventHandler CanExecuteChanged;
    
                public bool CanExecute(object parameter)
                {
                    return true;
                }
                public void Execute(object parameter)
                {
                    _action(parameter);
                }
            }   
            /// <summary>
            ///toast弹出消息
            /// </summary>
            /// <typeparam name="T">绑定MessageBoxDataContext属性的窗口</typeparam>
            /// <param name="context">显示内容</param>
            /// <param name="stayTime">停留时间</param>
            public static void Toast<T>(string context, TimeSpan stayTime) where T : Window, new()
            {
                App.Current.Dispatcher.BeginInvoke(new Action(() =>
                {
                    ShowDialog<T>(null, context, null, null, stayTime, null, false);
                }));
            }
            /// <summary>
            /// 显示消息框
            /// </summary>
            /// <typeparam name="T">绑定MessageBoxDataContext属性的窗口</typeparam>
            /// <param name="context">显示内容</param>
            /// <returns>结果</returns>
            public static MessageBoxResult ShowDialog<T>(string context) where T : Window, new()
            {
                return ShowDialog<T>(null, context, "确定", null, null, null, false);
            }
            /// <summary>
            /// 显示消息框
            /// </summary>
            /// <typeparam name="T">绑定MessageBoxDataContext属性的窗口</typeparam>
            /// <param name="title">标题</param>
            /// <param name="context">显示内容</param>
            /// <returns>结果</returns>
            public static MessageBoxResult ShowDialog<T>(string title, string context) where T : Window, new()
            {
                return ShowDialog<T>(title, context, "确定", null, null, null, false);
            }
    
            /// <summary>
            /// 显示消息框
            /// </summary>
            /// <typeparam name="T">绑定MessageBoxDataContext属性的窗口</typeparam>
            /// <param name="title">标题</param>
            /// <param name="context">显示内容</param>
            /// <param name="yesText">yes按钮的文本</param>
            /// <returns>结果</returns>
            public static MessageBoxResult ShowDialog<T>(string title, string context, string yesText) where T : Window, new()
            {
                return ShowDialog<T>(title, context, yesText, null, null, null, false);
            }
            /// <summary>
            /// 显示消息框
            /// </summary>
            /// <typeparam name="T">绑定MessageBoxDataContext属性的窗口</typeparam>
            /// <param name="title">标题</param>
            /// <param name="context">显示内容</param>
            /// <param name="yesText">yes按钮的文本</param>
            /// <param name="isCancelable">是否显示取消按钮</param>
            /// <returns>结果</returns>
            public static MessageBoxResult ShowDialog<T>(string title, string context, string yesText, bool isCancelable) where T : Window, new()
            {
                return ShowDialog<T>(title, context, yesText, null, null, null, isCancelable);
            }
            /// <summary>
            /// 显示消息框
            /// </summary>
            /// <typeparam name="T">绑定MessageBoxDataContext属性的窗口</typeparam>
            /// <param name="title">标题</param>
            /// <param name="context">显示内容</param>
            /// <param name="yesText">yes按钮的文本</param>
            /// <param name="noText">no按钮的文本</param>
            /// <returns>结果</returns>
            public static MessageBoxResult ShowDialog<T>(string title, string context, string yesText, string noText) where T : Window, new()
            {
                return ShowDialog<T>(title, context, yesText, noText, null, null, false);
            }
            /// <summary>
            /// 显示消息框
            /// </summary>
            /// <typeparam name="T">绑定MessageBoxDataContext属性的窗口</typeparam>
            /// <param name="title">标题</param>
            /// <param name="context">显示内容</param>
            /// <param name="yesText">yes按钮的文本</param>
            /// <param name="noText">no按钮的文本</param>
            /// <param name="isCancelable">是否显示取消按钮</param>
            /// <returns>结果</returns>
            public static MessageBoxResult ShowDialog<T>(string title, string context, string yesText, string noText, bool isCancelable) where T : Window, new()
            {
                return ShowDialog<T>(title, context, yesText, noText, null, null, isCancelable);
            }
            /// <summary>
            /// 显示消息框
            /// </summary>
            /// <typeparam name="T">绑定MessageBoxDataContext属性的窗口</typeparam>
            /// <param name="context">显示内容</param>
            /// <param name="yestCountDown">yes按钮倒计时</param>
            /// <param name="noCountDown">no按钮倒计时</param>
            /// <returns>结果</returns>
            public static MessageBoxResult ShowDialog<T>(string context, TimeSpan? yestCountDown, TimeSpan? noCountDown) where T : Window, new()
            {
                return ShowDialog<T>(null, context, null, null, yestCountDown, noCountDown, false);
            }
            /// <summary>
            /// 显示消息框
            /// </summary>
            /// <typeparam name="T">绑定MessageBoxDataContext属性的窗口</typeparam>
            /// <param name="context">显示内容</param>
            /// <param name="yesText">yes按钮的文本</param>
            /// <param name="noText">no按钮的文本</param>
            /// <param name="yestCountDown">yes按钮倒计时</param>
            /// <param name="noCountDown">no按钮倒计时</param>
            /// <returns>结果</returns>
            public static MessageBoxResult ShowDialog<T>(string context, string yesText, string noText, TimeSpan? yestCountDown, TimeSpan? noCountDown) where T : Window, new()
            {
                return ShowDialog<T>(null, context, yesText, noText, yestCountDown, noCountDown, false);
            }
            /// <summary>
            /// 显示消息框
            /// </summary>
            /// <typeparam name="T">绑定MessageBoxDataContext属性的窗口</typeparam>
            /// <param name="title">标题</param>
            /// <param name="context">显示内容</param>
            /// <param name="yesText">yes按钮的文本</param>
            /// <param name="noText">no按钮的文本</param>
            /// <param name="yestCountDown">yes按钮倒计时</param>
            /// <param name="noCountDown">no按钮倒计时</param>
            /// <returns>结果</returns>
            public static MessageBoxResult ShowDialog<T>(string title, string context, string yesText, string noText, TimeSpan? yestCountDown, TimeSpan? noCountDown) where T : Window, new()
            {
                return ShowDialog<T>(title, context, yesText, noText, yestCountDown, noCountDown, false);
            }
            /// <summary>
            /// 显示消息框
            /// </summary>
            /// <typeparam name="T">绑定MessageBoxDataContext属性的窗口</typeparam>
            /// <param name="title">标题</param>
            /// <param name="context">显示内容</param>
            /// <param name="yesText">yes按钮的文本</param>
            /// <param name="noText">no按钮的文本</param>
            /// <param name="yestCountDown">yes按钮倒计时</param>
            /// <param name="noCountDown">no按钮倒计时</param>
            /// <param name="isCancelable">是否显示取消按钮</param>
            /// <returns>结果</returns>
            public static MessageBoxResult ShowDialog<T>(string title, string context, string yesText, string noText, TimeSpan? yestCountDown, TimeSpan? noCountDown, bool isCancelable) where T : Window, new()
            {
    
                var mb = Create<T>(title, context, yesText, noText, yestCountDown, noCountDown, isCancelable);
                mb.ShowDialog();
                return GetResult(mb);
            }
            /// <summary>
            /// 获取结果,通常和MessageBoxHelper.Create<T>配合使用
            /// </summary>
            /// <typeparam name="T">绑定MessageBoxDataContext属性的窗口</typeparam>
            /// <param name="messageBox">MessageBoxHelper.Create<T>返回的对象</param>
            /// <returns>结果</returns>
            public static MessageBoxResult GetResult<T>(T messageBox) where T : Window, new()
            {
                var mc = messageBox.DataContext as MessageBoxDataContext;
                if (mc != null)
                {
                    return mc.Result;
                }
                return null;
            }
            /// <summary>
            /// 创建消息框
            /// </summary>
            /// <typeparam name="T">绑定MessageBoxDataContext属性的窗口</typeparam>
            /// <param name="context">显示内容</param>
            /// <returns>消息框对象</returns>
            public static T Create<T>(string context) where T : Window, new()
            {
                return Create<T>(null, context, "确定", null, null, null, false);
            }
            /// <summary>
            /// 创建消息框
            /// </summary>
            /// <typeparam name="T">绑定MessageBoxDataContext属性的窗口</typeparam>
            /// <param name="title">标题</param>
            /// <param name="context">显示内容</param>
            /// <returns>消息框对象</returns>
            public static T Create<T>(string title, string context) where T : Window, new()
            {
                return Create<T>(title, context, "确定", null, null, null, false);
            }
            /// <summary>
            /// 创建消息框
            /// </summary>
            /// <typeparam name="T">绑定MessageBoxDataContext属性的窗口</typeparam>
            /// <param name="title">标题</param>
            /// <param name="context">显示内容</param>
            /// <param name="yesText">yes按钮的文本</param>
            /// <returns>消息框对象</returns>
            public static T Create<T>(string title, string context, string yesText) where T : Window, new()
            {
                return Create<T>(title, context, yesText, null, null, null, false);
            }
            /// <summary>
            /// 创建消息框
            /// </summary>
            /// <typeparam name="T">绑定MessageBoxDataContext属性的窗口</typeparam>
            /// <param name="title">标题</param>
            /// <param name="context">显示内容</param>
            /// <param name="yesText">yes按钮的文本</param>
            /// <param name="isCancelable">是否显示取消按钮</param>
            /// <returns>消息框对象</returns>
            public static T Create<T>(string title, string context, string yesText, bool isCancelable) where T : Window, new()
            {
                return Create<T>(title, context, yesText, null, null, null, isCancelable);
            }
            /// <summary>
            /// 创建消息框
            /// </summary>
            /// <typeparam name="T">绑定MessageBoxDataContext属性的窗口</typeparam>
            /// <param name="title">标题</param>
            /// <param name="context">显示内容</param>
            /// <param name="yesText">yes按钮的文本</param>
            /// <param name="noText">no按钮的文本</param>
            /// <returns>消息框对象</returns>
            public static T Create<T>(string title, string context, string yesText, string noText) where T : Window, new()
            {
                return Create<T>(title, context, yesText, noText, null, null, false);
            }
    
            /// <summary>
            /// 创建消息框
            /// </summary>
            /// <typeparam name="T">绑定MessageBoxDataContext属性的窗口</typeparam>
            /// <param name="title">标题</param>
            /// <param name="context">显示内容</param>
            /// <param name="yesText">yes按钮的文本</param>
            /// <param name="noText">no按钮的文本</param>
            /// <param name="isCancelable">是否显示取消按钮</param>
            /// <returns>消息框对象</returns>
            public static T Create<T>(string title, string context, string yesText, string noText, bool isCancelable) where T : Window, new()
            {
                return Create<T>(title, context, yesText, noText, null, null, isCancelable);
            }
            /// <summary>
            /// 创建消息框
            /// </summary>
            /// <typeparam name="T">绑定MessageBoxDataContext属性的窗口</typeparam>
            /// <param name="context">显示内容</param>
            /// <param name="yestCountDown">yes按钮倒计时</param>
            /// <param name="noCountDown">no按钮倒计时</param>
            /// <returns>消息框对象</returns>
            public static T Create<T>(string context, TimeSpan? yestCountDown, TimeSpan? noCountDown) where T : Window, new()
            {
                return Create<T>(null, context, null, null, yestCountDown, noCountDown, false);
            }
            /// <summary>
            /// 创建消息框
            /// </summary>
            /// <typeparam name="T">绑定MessageBoxDataContext属性的窗口</typeparam>
            /// <param name="context">显示内容</param>
            /// <param name="yesText">yes按钮的文本</param>
            /// <param name="noText">no按钮的文本</param>
            /// <param name="yestCountDown">yes按钮倒计时</param>
            /// <param name="noCountDown">no按钮倒计时</param>
            /// <returns>消息框对象</returns>
            public static T Create<T>(string context, string yesText, string noText, TimeSpan? yestCountDown, TimeSpan? noCountDown) where T : Window, new()
            {
                return Create<T>(null, context, yesText, noText, yestCountDown, noCountDown, false);
            }
            /// <summary>
            /// 创建消息框
            /// </summary>
            /// <typeparam name="T">绑定MessageBoxDataContext属性的窗口</typeparam>
            /// <param name="title">标题</param>
            /// <param name="context">显示内容</param>
            /// <param name="yesText">yes按钮的文本</param>
            /// <param name="noText">no按钮的文本</param>
            /// <param name="yestCountDown">yes按钮倒计时</param>
            /// <param name="noCountDown">no按钮倒计时</param>
            /// <returns>消息框对象</returns>
            public static T Createg<T>(string title, string context, string yesText, string noText, TimeSpan? yestCountDown, TimeSpan? noCountDown) where T : Window, new()
            {
                return Create<T>(title, context, yesText, noText, yestCountDown, noCountDown, false);
            }
            /// <summary>
            /// 创建消息框
            /// </summary>
            /// <typeparam name="T">绑定MessageBoxDataContext属性的窗口</typeparam>
            /// <param name="title">标题</param>
            /// <param name="context">显示内容</param>
            /// <param name="yesText">yes按钮的文本</param>
            /// <param name="noText">no按钮的文本</param>
            /// <param name="yestCountDown">yes按钮倒计时</param>
            /// <param name="noCountDown">no按钮倒计时</param>
            /// <param name="isCancelable">是否显示取消按钮</param>
            /// <returns>消息框对象</returns>
            public static T Create<T>(string title, string context, string yesText, string noText, TimeSpan? yestCountDown, TimeSpan? noCountDown, bool isCancelable) where T : Window, new()
            {
                T mb = new T();
                MessageBoxDataContext mc = new MessageBoxDataContext();
                bool isLegal = false;
                mb.DataContext = mc;
                mc.Title = title;
                mc.Context = context;
                mc.YesText = yesText;
                mc.NoText = noText;
                mc.YesLeftTime = yestCountDown;
                mc.NoLeftTime = noCountDown;
                mc.YesCommand = new Command((o) =>
                {
                    mc.Result = new MessageBoxResult() { Button = MessageBoxResultButton.Yes, YesLeftTime = mc.YesLeftTime, NoLeftTime = mc.NoLeftTime };
                    isLegal = true;
                    mb.Close();
                });
                mc.NoCommand = new Command((o) =>
                {
                    mc.Result = new MessageBoxResult() { Button = MessageBoxResultButton.No, YesLeftTime = mc.YesLeftTime, NoLeftTime = mc.NoLeftTime };
                    isLegal = true;
                    mb.Close();
                });
                if (isCancelable)
                {
                    mc.CancelCommand = new Command((o) =>
                    {
                        mc.Result = new MessageBoxResult() { Button = MessageBoxResultButton.Cancel, YesLeftTime = mc.YesLeftTime, NoLeftTime = mc.NoLeftTime };
                        isLegal = true;
                        mb.Close();
                    });
                }
                mb.Loaded += (s, e) =>
                {
                    if (mc.YesLeftTime != null || mc.NoLeftTime != null)
                    {
                        mc.Timer = new DispatcherTimer();
                        mc.Timer.Interval = TimeSpan.FromSeconds(1);
                        mc.Timer.Tick += (S, E) =>
                        {
                            if (mc.YesLeftTime != null)
                            {
                                mc.YesLeftTime = mc.YesLeftTime.Value.Add(-TimeSpan.FromSeconds(1));
                                if (mc.YesLeftTime.Value.TotalSeconds < 1)
                                {
                                    mc.Timer.Stop();
                                    mc.YesCommand.Execute(null);
                                }
                            }
                            if (mc.NoLeftTime != null)
                            {
                                mc.NoLeftTime = mc.NoLeftTime.Value.Add(-TimeSpan.FromSeconds(1));
                                if (mc.NoLeftTime.Value.TotalSeconds < 1)
                                {
                                    mc.Timer.Stop();
                                    mc.NoCommand.Execute(null);
                                }
    
                            }
                        };
                        mc.Timer.Start();
                    }
                };
                mb.Closing += (s, e) =>
                {
                    e.Cancel = !isLegal;
                };
                mb.Closed += (s, e) =>
                {
                    if (mc.Timer != null && mc.Timer.IsEnabled)
                    {
                        mc.Timer.Stop();
                    }
                };
                return mb;
            }
        }
    }
    

    三、实例

    1、Toast

    (1)界面代码

    <Window x:Class="WpfApp1.Toast"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:local="clr-namespace:WpfApp1"
            mc:Ignorable="d"
            Title="Toast"
            AllowsTransparency="True"
            Background="Transparent"
            ResizeMode="NoResize"
            ShowInTaskbar="False"
            Topmost="True"
            WindowStartupLocation="CenterScreen"
            Width="400"
            Height="120"
            WindowStyle="None"              
            >
        <Grid>
            <Border  Margin="10" Background="White"  CornerRadius="10"  >
                <Border.Effect>
                    <DropShadowEffect ShadowDepth="0" BlurRadius="10" Opacity="0.5"/>
                </Border.Effect>
                <Grid Margin="20">
                    <StackPanel VerticalAlignment="Center">
                        <!--只需绑定Context-->
                        <TextBlock   Text="{Binding Context}"    HorizontalAlignment="Center"  VerticalAlignment="Center" FontSize="48"  Foreground="Gray"/>
                    </StackPanel>
                </Grid>
            </Border>
        </Grid>
    </Window>
    

    (2)调用方法

    MessageBoxHelper.Toast<Toast>("Hello word!", TimeSpan.FromSeconds(3));
    

    (3)效果预览

    在这里插入图片描述

    2、简单MessageBox

    (1)界面代码

    <Window x:Class="WpfApp1.MessageBoxSimple"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:local="clr-namespace:WpfApp1"
            mc:Ignorable="d"
            Title="MessageBoxSimple"
            AllowsTransparency="True"
            Background="Transparent"
            ResizeMode="NoResize"
            ShowInTaskbar="False"
            Topmost="True"
            WindowStartupLocation="CenterScreen"
            Width="600"
            Height="260"
            WindowStyle="None">
        <Grid>
            <Border  Margin="10" Background="White"    >
                <Border.Effect>
                    <DropShadowEffect ShadowDepth="0" BlurRadius="10" Opacity="0.5"/>
                </Border.Effect>
                <Grid Margin="20">
                    <!--绑定Context-->
                    <TextBlock  Margin="0,0,0,40" Text="{Binding Context}"    HorizontalAlignment="Center"  VerticalAlignment="Center" FontSize="48"  Foreground="Gray"/>
                    <StackPanel VerticalAlignment="Bottom"  Orientation="Horizontal" HorizontalAlignment="Center" >
                        <!--绑定NoCommand命令-->
                        <Button  Height="64" Width="144"    Cursor="Hand"   Command="{Binding NoCommand}">
                            <Button.Template>
                                <ControlTemplate  TargetType="{x:Type Button}">
                                    <Border   Background="White"  BorderBrush="#cccccc"  >
                                        <Border.Effect>
                                            <DropShadowEffect ShadowDepth="0" BlurRadius="10" Opacity="0.2"/>
                                        </Border.Effect>
                                        <!--绑定no文本NoText,也可以不绑定,直接使用页面上的文本-->
                                        <TextBlock  Name="text" Text="{Binding NoText}"   FontSize="24"    Foreground="Gray"  HorizontalAlignment="Center" VerticalAlignment="Center">
                                        </TextBlock>
                                    </Border>
                                </ControlTemplate>
                            </Button.Template>
                        </Button>
                        <!--绑定YesCommand命令-->
                        <Button  Margin="30,0,0,0"  Height="64" Width="144"    Cursor="Hand"  Command="{Binding YesCommand}">
                            <Button.Template>
                                <ControlTemplate  TargetType="{x:Type Button}">
                                    <Border  Background="Gray"  >
                                        <Border.Effect>
                                            <DropShadowEffect ShadowDepth="0" BlurRadius="10" Opacity="0.2"/>
                                        </Border.Effect>
                                        <!--绑定yes文本YesText,也可以不绑定,直接使用页面上的文本-->
                                        <TextBlock  Name="text"  Text="{Binding YesText}" FontSize="24"   Foreground="White"  HorizontalAlignment="Center" VerticalAlignment="Center">
                                        </TextBlock>
                                    </Border>
                                </ControlTemplate>
                            </Button.Template>
                        </Button>
                    </StackPanel>
                </Grid>
            </Border>
        </Grid>
    </Window>
    

    (2)调用方法

    var r = MessageBoxHelper.ShowDialog<MessageBoxSimple>(null,"Ensure?", "Yes", "No");
    if (r.Button == MessageBoxResultButton.Yes)
    {
        //选择了Yes
    }
    else if (r.Button == MessageBoxResultButton.No)
    {
        //选择了No
    }
    

    (3)效果预览

    在这里插入图片描述

    3、完整MessageBox

    (1)界面代码

    https://download.csdn.net/download/u013113678/34203243

    (2)调用方法及效果预览

    Toast框

     MessageBoxHelper.Toast<MessageBox>("Toast框", TimeSpan.FromSeconds(3));
    

    在这里插入图片描述

    OK框

    MessageBoxHelper.ShowDialog<MessageBox>(null, "OK框", "OK");
    

    在这里插入图片描述

    OK倒计时框

    MessageBoxHelper.ShowDialog<MessageBox>(null, "OK倒计时框", "OK", null, TimeSpan.FromSeconds(10), null);
    

    在这里插入图片描述

    YesNo框

    var r=MessageBoxHelper.ShowDialog<MessageBox>(null, "YesNo框", "Yes", "No");
    if (r.Button == MessageBoxResultButton.Yes)
    {
        //选择了Yes
    }
    else if (r.Button == MessageBoxResultButton.No)
    {
        //选择了No
    }
    

    在这里插入图片描述

    YesNo倒计时框

    var r=MessageBoxHelper.ShowDialog<MessageBox>(null, "YesNo倒计时框", "Yes", "No", TimeSpan.FromSeconds(10),null);
    if (r.Button == MessageBoxResultButton.Yes)
    {
        //选择了Yes
    }
    else if (r.Button == MessageBoxResultButton.No)
    {
        //选择了No
    }
    

    在这里插入图片描述
    带标题栏OK框

     MessageBoxHelper.ShowDialog<MessageBox>("标题", "带标题栏OK框", "OK",null);
    

    在这里插入图片描述

    带标题栏YesNo框

    var r=MessageBoxHelper.ShowDialog<MessageBox>("标题", "带标题栏YesNo框", "Yes", "No");
    if (r.Button == MessageBoxResultButton.Yes)
    {
        //选择了Yes
    }
    else if (r.Button == MessageBoxResultButton.No)
    {
        //选择了No
    }
    

    在这里插入图片描述

    可关闭YesNo框

    var r=MessageBoxHelper.ShowDialog<MessageBox>("标题", "可关闭YesNo框", "Yes", "No", true);
    if (r.Button == MessageBoxResultButton.Yes)
    {
        //选择了Yes
    }
    else if (r.Button == MessageBoxResultButton.No)
    {
        //选择了No
    
    }
    else if (r.Button == MessageBoxResultButton.Cancel)
    {
        //关闭了窗口
    }
    

    在这里插入图片描述

    可关闭倒计时框

    var r=MessageBoxHelper.ShowDialog<MessageBox>("标题", "可关闭倒计时框", "Yes", "No", null, TimeSpan.FromSeconds(10), true);
    if (r.Button == MessageBoxResultButton.Yes)
    {
        //选择了Yes
    }
    else if (r.Button == MessageBoxResultButton.No)
    {
        //选择了No
    }
    else if (r.Button == MessageBoxResultButton.Cancel)
    {
        //关闭了窗口
    }
    

    在这里插入图片描述


    总结

    操作与界面分离后,方便了界面的灵活设计,在不同的项目只需要定义MessageBox的界面即可,操作逻辑直接使用MessageBoxHelper,减少了造轮子。

    展开全文
  • MessageBox.Show 居中

    2021-05-25 05:52:19
    } ------解决方案-------------------- 学习~~ ------解决方案-------------------- 我的办法相对简单一些 重写MessageBox类C# codepublic class MessageBox { public MessageBox() { } public static DialogResult...

    C# codeusing System.Runtime.InteropServices;

    public delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam);

    [DllImport("user32.dll")]

    public static extern IntPtr SetWindowsHookEx(int hookid,

    HookProc pfnhook, IntPtr hinst, int threadid);

    [DllImport("user32.dll")]

    public static extern IntPtr CallNextHookEx(IntPtr hhook,

    int code, IntPtr wparam, IntPtr lparam);

    [DllImport("kernel32.dll")]

    public static extern IntPtr GetModuleHandle(string modName);

    [DllImport("user32.dll")]

    public static extern bool UnhookWindowsHookEx(IntPtr hhook);

    [DllImport("user32.dll")]

    public static extern bool GetWindowRect(IntPtr hWnd, ref Rectangle rect);

    [DllImport("user32.dll")]

    public static extern bool MoveWindow(

    IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);

    public const int WH_CBT = 5;

    public const int HCBT_ACTIVATE = 5;

    IntPtr hookHandle = IntPtr.Zero;

    private IntPtr CBTHookCallback(int nCode, IntPtr wParam, IntPtr lParam)

    {

    switch(nCode)

    {

    case HCBT_ACTIVATE:

    Rectangle vRectangle = new Rectangle();

    GetWindowRect(wParam, ref vRectangle);

    vRectangle.Width = vRectangle.Width - vRectangle.Left;

    vRectangle.Height = vRectangle.Height - vRectangle.Top;

    MoveWindow(wParam, // 右下

    Screen.GetWorkingArea(this).Width - vRectangle.Width,

    Screen.GetWorkingArea(this).Height - vRectangle.Height,

    vRectangle.Width, vRectangle.Height, false);

    UnhookWindowsHookEx(hookHandle);

    break;

    }

    return CallNextHookEx(hookHandle, nCode, wParam, lParam);

    }

    private void button1_Click(object sender, EventArgs e)

    {

    hookHandle = SetWindowsHookEx(WH_CBT, new HookProc(CBTHookCallback),

    GetModuleHandle(null), 0);

    MessageBox.Show("Zswang 路过");

    }

    ------解决方案--------------------

    学习~~

    ------解决方案--------------------

    我的办法相对简单一些

    重写MessageBox类C# codepublic class MessageBox

    {

    public MessageBox()

    {

    }

    public static DialogResult Show()

    {

    Form2 frm = new Form2();//Form2是自己新建的form,外观做的和MessageBox.show出来的效果一样。设置窗体的StartPosition为CenterParent.

    return frm.ShowDialog();

    }

    }

    ------解决方案--------------------

    崇拜一下zswang大侠!

    ------解决方案--------------------

    只有自己写个Form了

    ------解决方案--------------------C# codepublic class MessageBox

    {

    public MessageBox()

    {

    }

    public static DialogResult Show()

    {

    Form2 frm = new Form2();//Form2是自己新建的form,外观做的和MessageBox.show出来的效果一样。设置窗体的StartPosition为CenterParent.

    return frm.ShowDialog();

    }

    }

    ------解决方案--------------------C# codeFrom2 fm = new Form2();

    Point point = PointToScreen(this.Location);

    fm.StartPosition = FormStartPosition.Manual;

    fm.Location = new Point(point.X + (this.Size.Width - fm.Size.Width) / 2, point.Y + (this.Size.Height - fm.Size.Height) / 2);

    fm.Show();

    ------解决方案--------------------

    重写不错

    ------解决方案--------------------

    只能用API来实现了.

    ------解决方案--------------------探讨

    挺复杂的,得截获MessageBox显示。

    C# codeusingSystem.Runtime.InteropServices;publicdelegateIntPtr HookProc(intnCode, IntPtr wParam, IntPtr lParam);

    [DllImport("user32.dll")]publicstaticexternIntPtr SetWindowsHookEx(inthookid,

    HookProc pfnhook, IntPtr hinst,intthreadid);

    [DllImport("user32.dll")]publicstaticexternIntPtr CallNextHookEx(IntPtr hhook,intcode, IntPtr wparam, IntPtr lparam);

    […

    ------解决方案--------------------

    mark,看大侠重写

    展开全文
  • C语言messagebox用法

    2021-05-20 01:14:16
    pb 中messagebox 的具体用法及其的参数messagebox中的具体参数及其用法,请给举例看下。请尽量详细点。谢了.完整写法为 MessageBox ( '标题','内容',图标,按键,默认值) 其中标题与内容为要显示的字符串,不可省略 ...
  • done 用于关闭 MessageBox 实例—— lockScroll是否在 MessageBox 出现时将 body 滚动锁定boolean—true showCancelButton是否显示取消按钮boolean—false(以 confirm 和 prompt 方式调用时为 true) ...
  • private void button1_Click(object sender, EventArgs e){MessageBox.Show(" 1 个参数 ");}private void button2_Click(object sender, EventArgs e){MessageBox.Show(" 2 个参数。。 ","亮仔提示");}private void ...
  • C#中MessageBox用法大全

    2021-10-09 09:46:17
    我们在程序中经常会用到MessageBoxMessageBox.Show()共有21中重载方法。现将其常见用法总结如下: 1.MessageBox.Show("Hello~~~~"); 最简单的,只显示提示信息。 2.MessageBox.Show("There are ...
  • 使用过 element-ui 的朋友,应该都用过 MessageBox 弹框组件。MessageBox 弹框 只需要一条JS代码就可以调用使用,非常方便。那这是怎么实现的呢?我们也来搞一个这样的组件。
  • 文章目录系列文章目录前言一、模板1、MessageBox.xaml2、MessageBox.xaml.cs二、效果预览三、调用方法总结 前言 在wpf中实现一个MessageBox很容易,但是还是要去编写的,如果每次新建不同的项目都重头编写一个...
  • MessageBox弹框

    2021-01-31 14:32:09
    import { MessageBox } from 'element-ui'; Vue.prototype.$confirm = MessageBox.confirm <script> // 根据Id删除对应的用户信息 async removeUserById(id) { // 弹框询问用户是否删除数据 const ...
  • WPF 自定义一个MessageBox控件 先看效果: 新建一个WPF窗体UMessageBox: xaml代码: <Window x:Class="WPF20201123.Views.UMessageBox" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" ...
  • MessageBox只有Show方法,并且对Show方法进行了12种重载, 下面是最全的参数API [SecurityCritical] public static MessageBoxResult Show(Window owner, string messageBoxText, string caption, ...
  • 文章目录前言一、代码1、MessageBox.xaml2、MessageBox.xaml.cs二、效果预览三、调用方法总结 前言 本篇是在上一篇的基础上添加倒计时功能,有些应用场景会使用倒计时的消息框,这种通常需要我们自己实现,一般...
  • C++ MessageBox 定时关闭

    2021-11-03 11:16:39
    定时关闭MessageBox MessageBoxTimeout是一个微软未公开的Windows API函数。实现定时消息,功能类似于MessageBox。如果用户不回应,能定时关闭消息框。函数由user32.dll导出,windows2000及以下没有此函数。 直接上...
  • MessageBox.Show用法

    2021-05-09 13:15:42
    MessageBox.Show(“你要提示的文本”); //这是最简单的用法,括号里直接加上一个提示内容的文本就可以了 第一参数,就是提示文本 第二参数,为对话框的标题,比如“温馨提示”,用法: MessageBox.Show(“确定追这个...
  • 又想在Toplevel上使用messagebox。如果不设置参数,就会出现这样的情况: 一弹窗,就会跳到根窗口去,因为弹窗默认的父类是根窗口。 这样肯定是不行的。 于是研究,期初发现Dialog初始化时有个master参数,以为这...
  • 二、VC建WIN32程序(标准HELLO WORLD),试验发现,如果WndProc()里有MessageBox,当前的WndProc()会暂时停止在MessageBox,直到MessageBox返回才继续执行后面的语句!! 如果MessageBox出现,这时一个WM_PAINT出现...
  • 窗口大小 def box(): return messagebox.askyesno(title='弹窗', message='内容') Popup1 = Button(top, text="按钮1", fg="blue", bd=2, width=5, command=box, state="normal") Popup1.grid(row=1, column=1, ...
  • 分享给大家供大家参考,具体如下:相关内容:messagebox介绍使用filedialog介绍使用首发时间:2018-03-04 22:18messagebox:介绍:messagebox是tkinter中的消息框、对话框使用:导入模块:import tkinter.messageb...
  • Wpf MessageBox的用法

    2021-06-27 16:09:55
    1.MessageBox.Show(“Hello~~~~”); 最简单的,只显示提示信息。 2.MessageBox.Show(“There are something wrong!”,“ERROR”); 可以给消息框加上标题。 3.if(MessageBox.Show(“Deletethisuser?”,...
  • C++ MessageBox 的用法

    2021-01-08 14:46:42
    MessageBox(NULL,("对话框内容"),("对话框表达他"),常量); 注释: 常量在下面,也可以只接一个常量或者多个常量 最多只能接 一个按钮常量 一个图标常量 一个运行模式常量 想看成品的直接去第四项 二、头文件 #...
  • 一目了然看代码:import tkinter.messageboxfrom tkinter import *tkinter.messagebox.askokcancel("FishC Demo",'确定or取消?')tkinter.messagebox.askquestion("FishC Demo","你确定吗?")tkinter.messagebox....
  • Qt自定义MessageBox

    2021-04-01 09:10:40
    QMessageBox *box = new QMessageBox(QMessageBox::Information,"MessageTitle","MessageContent"); box->addButton("OK",QMessageBox::YesRole); box->setWindowIcon(QIcon(":/img/img/camera.png"));...
  • Java中,类似Windows中MessageBox的使用,用到了JOptionPane类。利用JOptionPane类中的各个static方法生成了各种类型的对话框。这些对话框都是模式对话框。具体的方法有:ConfirmDialog ---确认对话框,提出问题,由...
  • MessageBox 弹框模拟系统的消息提示框而实现的一套模态对话框组件,用于消息提示、确认消息和提交内容。从场景上说,MessageBox 的作用是美化系统自带的 alert、confirm 和 prompt,因此适合展示较为简单的内容。...
  • 点击打开 Message Box 全局方法 单独引用 Options 到此这篇关于Element MessageBox弹框的详细使用的文章就简介到这了,更多相关Element MessageBox弹框内容请搜索乐购源码以前的文章或继续浏览下面的相关文章希望大家...
  • 页面一打开就有一个提醒修改密码的弹框,如果这时候再有其他 messageBox 弹框的时候就会被覆盖,形成多个弹框排队等着处理的效果,第一个弹框永远在最前面,不能及时处理消息 分析 ElementUI 的组件是挂载在 Vue 上的,...
  • ElementUI 自定义MessageBox 弹框

    千次阅读 2021-05-25 18:20:32
    MessageBox 换个样式
  • 组件—弹框消息提示点击打开 Message Boxexport default {methods: {open() {this.$alert('这是一段内容', '标题名称', {confirmButtonText: '确定',callback: action => {this.$message({type: 'info',message: ...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 201,156
精华内容 80,462
关键字:

messagebox