What is the usage of the MessageBox in C#?

In C#, the MessageBox class is the class used for displaying message boxes. It provides a simple way to show messages, warnings, or prompts to users and receive their response.

Common methods of the MessageBox class include:

  1. Show method: Used to display a message box containing the specified text and returning the user’s response result.
    Example: MessageBox.Show(“Hello World!”);
  2. The Show method can be overloaded to specify not only the text, but also the title bar text, buttons, and icons of the message box.
    Example: MessageBox.Show(“Hello World!”, “Prompt”, MessageBoxButtons.OK, MessageBoxIcon.Information);
  3. The ShowDialog method is similar to the Show method, but it displays the message box modally, meaning the user must close the message box before continuing to interact with other windows.
  4. The Buttons property is used to specify the type of buttons for the message box, which can be OK, OKCancel, YesNo, and so on.
  5. Icon property: specifies the type of icon displayed in the message box, such as Information, Warning, or Error.
  6. DefaultButton property: used to specify the default button of the message box, which can be the first, last, or any other button.
  7. MessageBoxResult enumeration: Used to represent the user’s response to a message box, such as OK, Cancel, Yes, No, etc.

Here is a sample code demonstrating how to use MessageBox.

using System;
using System.Windows.Forms;

class Program
{
    static void Main()
    {
        // 显示一个带有OK按钮的消息框
        MessageBox.Show("Hello World!");

        // 显示一个带有Yes和No按钮以及问号图标的消息框,并获取用户的响应
        DialogResult result = MessageBox.Show("是否继续?", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

        // 根据用户的响应结果进行相应的操作
        if (result == DialogResult.Yes)
        {
            Console.WriteLine("用户选择了Yes");
        }
        else
        {
            Console.WriteLine("用户选择了No");
        }
    }
}

These are just some basic uses of the MessageBox class, other methods and properties can also be utilized based on specific needs.

bannerAds