Как вывести сообщение в c windows form

от admin

Как вывести сообщение в c windows form

Как правило, для вывода сообщений применяется элемент MessageBox. Однако кроме сообственно вывода строки сообщения данный элемент может устанавливать ряд настроек, которые определяют его поведение.

Для вывода сообщения в классе MessageBox предусмотрен метод Show , который имеет различные версии и может принимать ряд параметров. Рассмотрим одну из наиболее используемых версий:

Здесь применяются следующие параметры:

text : текст сообщения

caption : текст заголовка окна сообщения

buttons : кнопки, используемые в окне сообщения. Принимает одно из значений перечисления MessageBoxButtons :

AbortRetryIgnore : три кнопки Abort (Отмена), Retry (Повтор), Ignore (Пропустить)

OK : одна кнопка OK

OKCancel : две кнопки OK и Cancel (Отмена)

RetryCancel : две кнопки Retry (Повтор) и Cancel (Отмена)

YesNo : две кнопки Yes и No

YesNoCancel : три кнопки Yes, No и Cancel (Отмена)

Таким образом, в зависимости от выбора окно сообщения может иметь от одной до трех кнопок.

icon : значок окна сообщения. Может принимать одно из следующих значений перечисления MessageBoxIcon :

Asterisk, Information : значок, состоящий из буквы i в нижнем регистре, помещенной в кружок

Error, Hand, Stop : значок, состоящий из белого знака «X» на круге красного цвета.

Exclamation, Warning : значок, состоящий из восклицательного знака в желтом треугольнике

Question : значок, состоящий из вопросительного знака на периметре круга

None : значок у сообщения отсутствует

defaultButton : кнопка, на которую по умолчанию устанавливается фокус. Принимает одно из значений перечисления MessageBoxDefaultButton :

Button1 : первая кнопка из тех, которые задаются перечислением MessageBoxButtons

Button2 : вторая кнопка

Button3 : третья кнопка

options : параметры окна сообщения. Принимает одно из значений перечисления MessageBoxOptions :

DefaultDesktopOnly : окно сообщения отображается на активном рабочем столе.

RightAlign : текст окна сообщения выравнивается по правому краю

RtlReading : все элементы окна располагаются в обратном порядке справа налево

ServiceNotification : окно сообщения отображается на активном рабочем столе, даже если в системе не зарегистрирован ни один пользователь

Нередко используется один параметр — текст сообщения. Но посмотрим, как использовать остальные параметры. Пусть у нас есть кнопка, в обработчике нажатия которой открывается следующее окно сообщения:

Однако нам не просто дается возможность установки кнопок в окне сообщения. Метод MessageBox.Show возвращает объект DialogResult , с помощью которого мы можем узнать, какую кнопку в окне сообщения нажал пользователь. DialogResult представляет перечисление, в котором определены следующие значения:

Abort : нажата кнопка Abort

Retry : нажата кнопка Retry

Ignore : нажата кнопка Ignore

OK : нажата кнопка OK

Cancel : нажата кнопка Cancel

None : отсутствие результата

Yes : нажата кнопка Yes и No

No : нажата кнопка No

Используем обработку выбора пользователя, изменив обработчик нажатия кнопки следующим образом:

И теперь, если в окне сообщения мы выберем выриант Yes, то кнопка окрасится в красный цвет.

Message Box in C# Windows Application

In this c#.net post we will learn how to display MessageBox in windows form with an example.
C# MessageBox in windows application used to display a message on form with given text message and action buttons. We can also add some additional option such as a title text, conditional button, or help button in MessageBox.

Simple MessageBox

The simple MessageBox displays text with OK button. When we click ok button the MessageBox will disappears from form.

Here, we can see the code for create simple MessageBox with an example.
We have a button control on windows form, we will get MessageBox with “Hello MeeraAcademy” message while click button.

Here, is the output of above MessageBox example.

meeraacademy.com

C# Message Box in Windows Application

MessageBox with Title

We can display Message Box with text message and title.
Here is the code of display MessageBox with title.

Читать:
Как обновить сводную таблицу в excel если изменил данные

The output of above code.

meeraacademy.com

Message Box with title in windows application

MessageBox with Buttons

In above example by default there is only one OK button display. We can display different combination of buttons in MessageBox such as OKCancel, YesNo, YesNoCancel. The MessageBoxButtons enumeration represents the buttons to be displayed on MessageBox.

MessageBoxButtons

  • AbortRetryIgnore
  • OK
  • OKCancel
  • RetryCancel
  • YesNo
  • YesNoCancel

Here is the example of display MessageBox with YesNo button with title.

Above example first MessageBox will display when click button, it display a message “Are you sure to quit?” with two buttons Yes and No. If we click on Yes button it will create new MessageBox with text “Bye Bye” and if we click on No button it will display MessageBox with “Welcome back” message.

meeraacademy.com

C# Message Box with Buttons

If we use OKCancel Button with above example it should display like:

meeraacademy.com

C# Message Box with Buttons

Icons with MessageBox

We can display icon on MessageBox dialog. The MessageBoxIcon enumeration represents an icon to be displayed on MessageBox.

MessageBoxIcon

  • Asterisk
  • Error
  • Exclamation
  • Hand
  • Information
  • None
  • Question
  • Stop
  • Warning

Here we see an example of Question. write MessageBoxIcon.Question after MessageBoxButtons.OKCancel and then run program.

C# Message Box with Icon

We hope that this windows application tutorial helped you to understand about how to create different types of MessageBox.

Next, c# windows application tutorial we will learn about Show() and ShowDialog() methods.

How do I create a MessageBox in C#?

I have just installed C# for the first time, and at first glance it appears to be very similar to VB6. I decided to start off by trying to make a ‘Hello, World!’ UI Edition.

I started in the Form Designer and made a button named «Click Me!» proceeded to double-click it and typed in

I received the following error:

MessageBox is a ‘type’ but used as a ‘variable’

Fair enough, it seems in C# MessageBox is an Object. I tried the following

I received the following error: MessageBox does not contain a constructor that takes ‘1’ arguments

How to create message box in C#?

A message box or dialog box is used to interact with the users of your application. The purpose of using a message box may include notifying about a particular action e.g. success message after entering a record. Similarly, an error message if an operation was unsuccessful. In both cases, you may display the “OK” button in the message box with the message.

In other cases, you may display a message box for the user confirmation before performing a critical action e.g. deleting a record permanently. In that case, a Yes/No button in the dialog box makes sense.

In this tutorials, I will show you how to create various types of C# message box with code.

How to make message box work in Visual Studio?

If you are working in Visual Studio then you have to include the System.Windows.Forms by following this:

  • In your project name under “Solution Explorer” right click and select “Add Reference”.
  • There you can see a few tabs. Select “.Net” tab.
  • Now locate the System.Windows.Forms and press OK

The example of creating a simple message box

After taking the above steps, you need including the System.Windows.Forms namespace as used in the code below.

You may provide a message to be displayed and the title of the dialog box by using the MessageBox class’s show method. The following example simply displays a box with the OK button:

Похожие статьи