C# / .NET messagebox is not modal

2019-01-17 14:05发布

Why is a C#/.NET message box not modal?

Accidentally, if the message box goes behind our main UI, then the main UI doesn't respond, until we click OK (on our message box).

Is there a workaround other than creating a custom message box?

10条回答
Ridiculous、
2楼-- · 2019-01-17 14:42

You need to assign the MessageBox owner property to the main UI window (look at the 3rd constructor).

查看更多
ゆ 、 Hurt°
3楼-- · 2019-01-17 14:42
public static System.Windows.Forms.DialogResult WW_MessageBox(string Message, string Caption,
        System.Windows.Forms.MessageBoxButtons buttons, System.Windows.Forms.MessageBoxIcon icon,
        System.Windows.Forms.MessageBoxDefaultButton defaultButton)
    {
        System.Windows.Forms.MessageBox.Show(Message, Caption, buttons, icon, defaultButton,
            (System.Windows.Forms.MessageBoxOptions)8192 /*MB_TASKMODAL*/);

    }
查看更多
Evening l夕情丶
4楼-- · 2019-01-17 14:44

Make the message box appear in the main thread, if your form has been created from it:

private bool ShowMessageBoxYesNo()
{
    if (this.InvokeRequired)
        return (bool)this.Invoke(new ShowMessageBoxYesNoDelegate(ShowMessageBoxYesNo));
    else
    {
        DialogResult res = MessageBox.Show("What ?", "Title", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
        if (res == DialogResult.Yes)
            return true;
        else
            return false;
    }
}
查看更多
可以哭但决不认输i
5楼-- · 2019-01-17 14:48

This is a simple C# new Windows Forms application:

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

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string message = "You did not enter a server name. Cancel this operation?";
            string caption = "No Server Name Specified";
            MessageBoxButtons buttons = MessageBoxButtons.YesNo;
            DialogResult result;

            // Displays the MessageBox.
            result = MessageBox.Show(this, message, caption, buttons);
            if (result == DialogResult.Yes)
            {
                // Closes the parent form.
                this.Close();
            }
        }
    }
}

As Dusty states in his answer, a message box is a modal dialog. Specify the 'owner' property. In this example, the owner is denoted by the keyword 'this'.

查看更多
登录 后发表回答