如何:显示消息框
MessageBox 是一个预定义对话框,用于向用户显示与应用程序相关的信息。 消息框也用于请求来自用户的信息。
在消息框中向用户显示信息
定位到要为消息框添加代码的位置。
添加使用 Show 方法代码。
下面的代码演示如何调用 MessageBox 类的 Show 方法向用户显示信息。 对 Show 方法的调用使用可选 style 参数,可指定要在消息框中显示的最适合于所示消息框类型的图标类型:
Public Sub PerformCalculations() ' Code is entered here that performs a calculation. ' Display a message box informing the user that the calculations ' are complete. MessageBox.Show("The calculations are complete", "My Application", _ MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk) End Sub
public void PerformCalculations() { // Code is entered here that performs a calculation // Display a message box informing the user that the calculations // are complete MessageBox.Show ("The calculations are complete", "My Application", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk); }
public: void PerformCalculations() { // Code is entered here that performs a calculation // Display a message box informing the user that the calculations // are complete MessageBox::Show("The calculations are complete", "My Application", MessageBoxButtons::OKCancel, MessageBoxIcon::Asterisk); }
消息框也可接受输入。 MessageBox 类的 Show 方法返回可用于确定用户所做选择的值。 可以整数形式存储此值;也可使用 if 语句,比较显示消息框时返回的值。 可设置 Show 方法的 style 参数,以便显示适当的按钮向用户询问信息。
显示消息框以请求信息
为类打开代码编辑器并定位到要为消息框添加代码的位置。
添加使用 MessageBox 类的 Show 方法的代码,以显示一个消息框。
下列代码演示如何调用 MessageBox 方法检索来自用户的信息,然后确定所选的值:
Public Sub ExitApplication() ' Display a message box asking users if they ' want to exit the application. If MessageBox.Show ("Do you want to exit?", "My Application", _ MessageBoxButtons.YesNo, MessageBoxIcon.Question) _ = DialogResult.Yes Then Application.Exit End If End Sub
public void ExitApplication() { // Display a message box asking users if they // want to exit the application. if (MessageBox.Show ("Do you want to exit?", "My Application", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { Application.Exit(); } }
public: void ExitApplication() { // Display a message box asking users if they // want to exit the application. if (MessageBox::Show("Do you want to exit?", "My Application", MessageBoxButtons::YesNo, MessageBoxIcon::Question) == DialogResult::Yes) { Application::Exit(); } }
Visual Basic 说明
在 Visual Basic 中,虽然仍支持使用 MsgBox() 创建要显示给用户的消息框,不过最好还是使用上述的新语法 MessageBox.Show()。 因此,参照上面的代码实例,下面的代码在 Visual Basic 中是可以接受的。
Public Sub ExitApplication() If MsgBox("Do you want to exit?", MsgBoxStyle.Exclamation, _ "My Application") = MsgBoxResult.Yes Then Application.Exit() End If End Sub
有关 MsgBox() 的更多信息,请参见 MsgBox 函数。
请参见
任务
参考
MsgBox Result Constants for Visual Basic 6.0 Users
MsgBox Style Constants for Visual Basic 6.0 Users