C# MessageBox.Show 详解
一、引入命名空间
using System.Windows.Forms;
Windows窗体应用默认引入;
MessageBox.Show(参数1,参数2,参数3,参数4)
参数1:弹出框要显示的内容
参数2:弹出框的标题
参数3:也可写作MessageBoxButtons,弹出框的按钮格式
参数4:弹出框的图标样式
注意: 4个参数除了参数1外都可以省略,参数1也可以用""输出无内容提示框
二、用法
2.1 简单用法
MessageBox.Show(“提示文本”);
也可配置第二参数,相当于提示标题,例如:
MessageBox.Show("确认要这么做吗?","温馨提示");2.2 带返回值的用法
DialogResult res = MessageBox.Show("确定要删除所选中的文档吗?", "删除提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
if (res == DialogResult.OK) //1为确定,2为取消,...
{
//按OK后,执行语句;
}上述MessageBox.Show的具体参数信息如下:
第一参数 >> 提示的文本信息;
第二参数 >> 提示窗口的标题;
第三参数 >> 提示窗体显示的按钮,例如:MessageBoxButtons.OKCancel(确认取消),具体参数如下表。
| 属性 | 描述 |
| OK | 确定 按钮 |
| OKCancel | 确定\取消 按钮 |
| YesNo | 是\否 按钮 |
| YesNoCancel | 是\否\取消 按钮 |
| AbortRetryIgnore | 中止\重试\忽略 按钮 |
第四参数 >> 弹窗显示的图标,例如:MessageBoxIcon.Question(询问图标),具体信息如下。
| 属性 | 描述 |
| Information | 普通消息图标 |
| Error | 出错图标 |
| Warning | 警告图标 |
| Question | 询问图标 |
| Exclamation | 惊叹号图标 |
| Asterisk | i星号图标 |
| Stop | 停止图标 |
三、DialogResult属性
强烈建议使用系统定义的 DialogResult属性访问,例如 DialogResult.OK, DialogResult.Yes,DialogResult.No。如表:
| 属性 | 描述 |
| None | 无,没有操作任何按钮 |
| OK | 确定 |
| Cancel | 取消 |
| Yes | 是 |
| No | 否 |
| Abort | 中止 |
| Ignore | 忽略 |
| Retry | 重试 |
四、MessageBoxOptions 枚举
| 属性 | 描述 |
| DefaultDesktopOnly | 消息框显示在活动桌面上。 |
| RightAlign | 消息框文本右对齐。 |
| RtlReading | 指定消息框文本按从右到左的阅读顺序显示。 |
| ServiceNotification | 消息框显示在活动桌面上。 调用方是通知用户某个事件的服务。 即使用户未登录到计算机,Show 也会在当前活动桌面上显示消息框。 |
示例代码:
private void validateUserEntry2()
{
// Checks the value of the text.
if(serverName.Text.Length == 0)
{
string message = "You did not enter a server name. Cancel this operation?";
string caption = "No Server Name Specified";
MessageBoxButtons buttons = MessageBoxButtons.YesNo;
DialogResult result;
result = MessageBox.Show(this, message, caption, buttons,
MessageBoxIcon.Question, MessageBoxDefaultButton.Button1,
MessageBoxOptions.RightAlign);
if(result == DialogResult.Yes)
{
this.Close();
}
}
}
