为什么C#/ .NET消息框不是模态的?
无意中,如果消息框在我们的主UI后面,那么主UI不响应,直到我们单击OK(在我们的消息框上).
除了创建自定义消息框之外,还有其他解决方法吗?
Cha*_*lie 59
您需要将MessageBox所有者属性分配给主UI窗口(查看第3个构造函数).
Jam*_*esM 12
这是一个简单的C#新Windows Forms应用程序:
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();
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
正如Dusty在他的回答中所述,消息框是一个模态对话框.指定"所有者"属性.在此示例中,所有者由关键字"this"表示.
小智 7
获取系统模态消息框设置MessageBoxOptions.DefaultDesktopOnly.
模态弹出窗口在技术上被定义为一个弹出框,可以中断应用程序的正常流程...不一定是一个停留在所有其他窗口顶部的弹出框,因此您描述的行为对于模式弹出窗口是正确的.
这是CodeProject上的一个项目,它试图模仿MessageBox样式Modal窗口的"always on top"功能:
CodeProject:TopMost MessageBox
您可以使用owner参数指定实现IWin32Window接口的特定对象,以将消息框放在前面.
消息框是模态对话框,这意味着除了模态窗体上的对象外,不会发生任何输入(键盘或鼠标单击).在输入到另一个表单之前,程序必须隐藏或关闭模式表单(通常是响应某些用户操作).