C# MessageBox消息框的用法(附带实例)
在 C# 程序中,使用 MessageBox() 方法创建消息框。MessageBox() 方法的语法如下:
1) Caption:消息框的标题。
2) MessageBoxButtons:MessageBox的按钮样式,这是列举(enum)格式,有以下几个选项。
3) MessageBoxIcon:消息框的图示,这是列举(enum)格式,有以下几个选项。
4) MessageBoxDefaultButton:消息框第几个按钮是默认按钮,这是列举(enum)格式,有以下几个选项。
5) MessageBoxOptions:消息框使用的选项,这是列举(enum)格式,有以下几个选项。
MessageBox 的回传值 DigalogResult,也是使用列举 (enum) 回传,代表消息框各种按钮回传的结果。
result = MessageBox(message, Caption, MessageBoxButtons, MessageBoxIcon, MessageBoxDefaultButton, MessageBoxOptions);上述语句除了 message 是要告诉使用者信息,必须要有此项此方法才有意义外,其他都是可选项,所有参数与回传值的意义如下。
1) Caption:消息框的标题。
2) MessageBoxButtons:MessageBox的按钮样式,这是列举(enum)格式,有以下几个选项。
| MessageBoxButtons 列举常数 | 数 值 | 说 明 |
|---|---|---|
| OK | 0 | 显示确定按钮 |
| OKCancel | 1 | 显示确定和取消按钮 |
| AbortRetryIgnore | 2 | 显示中止、重试和忽略按钮 |
| YesNoCancel | 3 | 显示是 (Y)、否 (N) 和取消按钮 |
| YesNo | 4 | 显示是(Y) 和否 (N) 按钮 |
| RetryCancel | 5 | 显示重试 (R) 和取消按钮 |
| CancelTryContinue | 6 | 显示取消、重试、和继续 (C) 按钮 |
3) MessageBoxIcon:消息框的图示,这是列举(enum)格式,有以下几个选项。
| MessageBoxIcon 列举常数 | 数 值 | 说 明 |
|---|---|---|
| None | 0 | 消息框没有任何符号 |
| Error 或 Stop 或 Hand | 16 | 消息框有 ❌ 符号 |
| Question | 32 | 消息框有 ❓ 符号 |
| Exclamation 或 Warning | 48 | 消息框有 ⚠ 符号 |
| Information | 64 | 消息框有 ℹ 符号 |
4) MessageBoxDefaultButton:消息框第几个按钮是默认按钮,这是列举(enum)格式,有以下几个选项。
| MessageBoxDefaultButton 列举常数 | 数 值 | 说 明 |
|---|---|---|
| Button1 | 0 | 第 1 个按钮是默认按钮 |
| Button2 | 256 | 第 2 个按钮是默认按钮 |
| Button3 | 512 | 第 3 个按钮是默认按钮 |
| Button4 | 768 | 说明按钮是默认按钮 |
5) MessageBoxOptions:消息框使用的选项,这是列举(enum)格式,有以下几个选项。
| MessageBoxOptions 列举常数 | 数 值 | 说 明 |
|---|---|---|
| DefaultDesktopOnly | 131072 | 消息框显示在使用桌面上 |
| RightAlign | 524288 | 消息框靠右对齐 |
| RtlReading | 1048176 | 消息框从右到左显示 |
| ServiceNotification | 2097152 | 消息框显示在使用桌面上,调用者通知使用者发生事件的服务 |
MessageBox 的回传值 DigalogResult,也是使用列举 (enum) 回传,代表消息框各种按钮回传的结果。
| DialogResult 列举常数 | 数 值 | 说 明 |
|---|---|---|
| None | 0 | 消息框回传 Nothing,对话框继续执行 |
| OK | 1 | 消息框单击“确定”按钮 |
| Cancel | 2 | 消息框单击“取消”按钮 |
| Abort | 3 | 消息框单击“中止”按钮 |
| Retry | 4 | 消息框单击“重试”按钮 |
| Ignore | 5 | 消息框单击“掠过”按钮 |
| Yes | 6 | 消息框单击“是”按钮 |
| No | 7 | 消息框单击“否”按钮 |
| TryAgain | 10 | 消息框单击“重试”按钮 |
| Continue | 11 | 消息框单击“继续”按钮 |
C# MessageBox()方法实例
这个程序如果单击“关闭”按钮,会出现消息框,询问是否真的要结束此窗体,单击“是”按钮可以关闭窗体,如果单击“否”按钮可以取消关闭窗体。
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
string message = "是否关闭窗体";
string caption = "关闭窗体提醒";
var result = MessageBox.Show(message, caption,
MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.No) // 如果单击“否”按钮
{
e.Cancel = true; // 取消关闭窗体
}
}
}
执行结果为:
ICP备案:
公安联网备案: