Windows forms c всплывающее окно

Последнее обновление: 31.10.2015

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

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

public static DialogResult Show(
	string text,
	string caption,
	MessageBoxButtons buttons,
	MessageBoxIcon icon,
	MessageBoxDefaultButton defaultButton,
	MessageBoxOptions options
)

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

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: окно сообщения отображается на активном рабочем столе, даже если в системе не зарегистрирован ни один пользователь

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

private void button1_Click(object sender, EventArgs e)
{
    MessageBox.Show(
        "Выберите один из вариантов", 
        "Сообщение", 
        MessageBoxButtons.YesNo, 
        MessageBoxIcon.Information, 
        MessageBoxDefaultButton.Button1, 
        MessageBoxOptions.DefaultDesktopOnly);
}

MessageBox в Windows Forms

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

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

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

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

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

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

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

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

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

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

private void button1_Click(object sender, EventArgs e)
{
    DialogResult result = MessageBox.Show(
        "Окрасить кнопку в красный цвет?", 
        "Сообщение", 
        MessageBoxButtons.YesNo, 
        MessageBoxIcon.Information, 
        MessageBoxDefaultButton.Button1, 
        MessageBoxOptions.DefaultDesktopOnly);
		
	if (result == DialogResult.Yes)
        button1.BackColor=Color.Red;
    
	this.TopMost = true;
}

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

C# MessageBox in Windows Forms displays a message with the given text and action buttons. You can also use MessageBox control to add additional options such as a caption, an icon, or help buttons. In this article, you’ll learn how to display and use a MessageBox in C# WinForms app. You will also learn how to use C# MessageBox class dynamically in code samples. 

C# MessageBox

MessageBox class has an overloaded static Show method that displays a message box with a message and action buttons. The action buttons can be OK and Cancel, Yes and No etc. Here are some of the options that can be used in C# message box.

Simple MessageBox

The simplest form of a MessageBox is a dialog with text and OK button. When you click OK button, the box disappears.

The following code snippet creates a simple Message Box.

string message = "Simple MessageBox";  
MessageBox.Show(message);

MessageBox with Title

The following code snippet creates a simple MessageBox with a title. 

string message = "Simple MessageBox";  
string title = "Title";  
MessageBox.Show(message, title); 

 MessageBox with Title

MessageBox with Buttons

A MessageBox can have different button combinations such as YesNo and OKCancel. The MessageBoxButtons enumeration represents the buttons to be displayed on a MessageBox and has following values.

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

The following code snippet creates a MessageBox with a title and Yes and No buttons. This is a typical MessageBox you may call when you want to close an application. If the Yes button is clicked, the application will be closed. The Show method returns a DialogResult enumeration.

string message = "Do you want to close this window?";  
string title = "Close Window";  
MessageBoxButtons buttons = MessageBoxButtons.YesNo;  
DialogResult result = MessageBox.Show(message, title, buttons);  
if (result == DialogResult.Yes) {  
    this.Close();  
} else {  
    // Do something  
}

MessageBox with Buttons

MessageBox with Icon

A MessageBox can display an icon on the dialog. A MessageBoxIcons enumeration represents an icon to be displayed on a MessageBox and has the following values.

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

The following code snippet creates a MessageBox with a title, buttons, and an icon.

string message = "Do you want to abort this operation?";  
string title = "Close Window";  
MessageBoxButtons buttons = MessageBoxButtons.AbortRetryIgnore;  
DialogResult result = MessageBox.Show(message, title, buttons, MessageBoxIcon.Warning);  
if (result == DialogResult.Abort) {  
    this.Close();  
}  
elseif(result == DialogResult.Retry) {  
    // Do nothing  
}  
else {  
    // Do something  
}

MessageBox with Icon

MessageBox with Default Button

We can also set the default button on a MessageBox. By default, the first button is the default button. The MessageBoxDefaultButton enumeration is used for this purpose and it has the following three values.

  • Button1
  • Button2
  • Button3

The following code snippet creates a MessageBox with a title, buttons, and an icon and sets the second button as a default button.

string message = "Do you want to abort this operation?";  
string title = "Close Window";  
MessageBoxButtons buttons = MessageBoxButtons.AbortRetryIgnore;  
DialogResult result = MessageBox.Show(message, title, buttons, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);  
if (result == DialogResult.Abort) {  
    this.Close();  
}  
elseif(result == DialogResult.Retry) {  
    // Do nothing  
}  
else {  
    // Do something  
}

MessageBox with Default Button

MessageBox with Message Options

MessageBoxOptions enumeration represents various options and has the following values.

  • ServiceNotification
  • DefaultDesktopOnly
  • RightAlign
  • RtlReading

The following code snippet creates a MessageBox with various options.

DialogResult result = MessageBox.Show(message, title, buttons,  
MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2,  
MessageBoxOptions.RightAlign|MessageBoxOptions.RtlReading);  

MessageBox with Message Options

MessageBox with Help Button

A MessageBox can have an extra button called Help button. This is useful when we need to display a help file. The following code snippet creates a MessageBox with a Help button.

DialogResult result = MessageBox.Show(message, title, buttons,  
MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2,  
MessageBoxOptions.RightAlign, true );  

MessageBox with Help Button

We can also specify a help file when the Help button is clicked. The following code snippet references a help file.

DialogResult result = MessageBox.Show(message, title,  
buttons, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1, 0, "helpfile.chm");  

Summary

In this article, we discussed how to create and use a MessageBox in a Windows Forms application.

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

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

using System;

using System.Windows.Forms;

namespace Сообщения

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)

        {

        }

    }

}

Для того что бы вывести обычно сообщения достаточно вписать в метод нажатия кнопки строку:

private void button1_Click(object sender, EventArgs e)

        {

            MessageBox.Show(«nookery.ru»);

        }

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

private void button1_Click(object sender, EventArgs e)

        {

            MessageBox.Show(«nookery.ru», «Сайт»);

        }

В следующем примере нам придется использовать MessageBoxButtons в качестве передаваемого аргумента. Однако он имеет несколько параметров:

  • MessageBoxButtons.AbortRetryIgnore – Прервать | Повтор | Пропустить
  • MessageBoxButtons.OK — ОК
  • MessageBoxButtons.OKCancel — ОК | Отмена
  • MessageBoxButtons.RetryCancel — Повтор | Отмена
  • MessageBoxButtons.YesNo — Да | Нет
  • MessageBoxButtons.YesNoCancel — Да | Нет | Отмена

Это нам позволит разместить в диалоговом окне сообщение кнопку или кнопки, в зависимости от параметров.

Рассмотрим все примеры с использованием кнопок:

Вариант AbortRetryIgnore

private void button1_Click(object sender, EventArgs e)

        {

            MessageBox.Show(«nookery.ru», «Сайт», MessageBoxButtons.AbortRetryIgnore);

        }

Вариант OK

В этом варианте у нас ничего не измениться так как он используется по умолчанию, выводит кнопку Ok.

Вариант OKCancel

private void button1_Click(object sender, EventArgs e)

        {

            MessageBox.Show(«nookery.ru», «Сайт», MessageBoxButtons.OKCancel);

        }

Вариант RetryCancel Диалоговое окно подходит для вывода сообщения пользователю с возможностью повторения какого-либо действия, имея в функционале диалогового окна две кнопки Повтор, Отмена.

private void button1_Click(object sender, EventArgs e)

        {

            MessageBox.Show(«nookery.ru», «Сайт», MessageBoxButtons.RetryCancel);

        }

Вариант YesNo Диалоговое окно подходит для вывода сообщения пользователю с возможностью выбора, подтвердить или отказаться имя в функционале диалогового окна две кнопки Да, Нет.

private void button1_Click(object sender, EventArgs e)

        {

            MessageBox.Show(«nookery.ru», «Сайт», MessageBoxButtons.YesNo);

        }

Вариант YesNoCancel Диалоговое окно подходит для вывода сообщения пользователю с возможностью выбора, подтвердить или отказаться имя в функционале диалогового окна три кнопки Да, Нет, Отмена.

private void button1_Click(object sender, EventArgs e)

        {

            MessageBox.Show(«nookery.ru», «Сайт», MessageBoxButtons.YesNoCancel);

        }

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

MessageBoxIcon.Error Диалоговое окно подходит для вывода сообщения пользователю об ошибке.

private void button1_Click(object sender, EventArgs e)

        {

            MessageBox.Show(«nookery.ru», «Сайт», MessageBoxButtons.OK, MessageBoxIcon.Error);

        }

MessageBoxIcon.Information Диалоговое окно подходит для вывода сообщения пользователю о какой то информации.

   private void button1_Click(object sender, EventArgs e)

        {

            MessageBox.Show(«nookery.ru», «Сайт», MessageBoxButtons.OK, MessageBoxIcon.Information);

        }

MessageBoxIcon.None

Данные вариант стоит по умолчанию и не выводит никого изображения.

MessageBoxIcon.Question Диалоговое окно подходит для вывода сообщения пользователю о помощи.

  private void button1_Click(object sender, EventArgs e)

        {

            MessageBox.Show(«nookery.ru», «Сайт», MessageBoxButtons.OK, MessageBoxIcon.Question);

        }

MessageBoxIcon.Warning Диалоговое окно подходит для вывода сообщения пользователю об ошибке или опасности.

  private void button1_Click(object sender, EventArgs e)

        {

            MessageBox.Show(«nookery.ru», «Сайт», MessageBoxButtons.OK, MessageBoxIcon.Warning);

        }

MessageBoxIcon.Exclamation

private void button1_Click(object sender, EventArgs e)

        {

         MessageBox.Show(«nookery.ru», «Сайт», MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

        }

MessageBoxIcon.Stop

private void button1_Click(object sender, EventArgs e)

        {

         MessageBox.Show(«nookery.ru», «Сайт», MessageBoxButtons.OK, MessageBoxIcon.Stop);

        }

MessageBoxIcon.Asterisk

private void button1_Click(object sender, EventArgs e)

        {

         MessageBox.Show(«nookery.ru», «Сайт», MessageBoxButtons.OK, MessageBoxIcon.Asterisk);

        }

MessageBoxIcon.Hand

private void button1_Click(object sender, EventArgs e)

        {

         MessageBox.Show(«nookery.ru», «Сайт», MessageBoxButtons.OK, MessageBoxIcon.Hand);

        }

Для того что бы сохранить полученный результат после нажатия кнопки, нам достаточно создать переменную класса DialogResult

DialogResult может принимать следующие значения:

  • DialogResult.Abort —  Прервать
  • DialogResult.Cancel — Отмена
  • DialogResult.Ignore — Пропустить
  • DialogResult.No —  Нет
  • DialogResult.Yes —  Да
  • DialogResult.OK —  ОК
  • DialogResult.Retry —  Повтор

  DialogResult resualt=  MessageBox.Show(«nookery.ru», «Сайт», MessageBoxButtons.YesNo);

А что бы посмотреть, что хранить переменная resualt мы можем вывести ее в сообщении:

MessageBox.Show(resualt.ToString());

В моем примере я нажал на кнопку Да и вывелось сообщения

В этих примерах мы рассмотрели возможность вывода сообщений пользователю, на основе диалоговых окно в WinForm.

When I click a button, I want a box to popup on the screen and display a simple message. Nothing fancy really. How would I do that?

asked Nov 27, 2009 at 0:19

neuromancer's user avatar

neuromancerneuromancer

53.9k79 gold badges166 silver badges224 bronze badges

System.Windows.Forms.MessageBox.Show("My message here");

Make sure the System.Windows.Forms assembly is referenced your project.

Noctis's user avatar

Noctis

11.5k3 gold badges44 silver badges82 bronze badges

answered Nov 27, 2009 at 0:22

Alex J's user avatar

3

Just type mbox then hit tab it will give you a magic shortcut to pump up a message box.

answered Nov 27, 2009 at 0:21

Spence's user avatar

SpenceSpence

28.6k15 gold badges68 silver badges103 bronze badges

2

In Visual Studio 2015 (community edition), System.Windows.Forms is not available and hence we can’t use MessageBox.Show("text").

Use this Instead:

var Msg = new MessageDialog("Some String here", "Title of Message Box");    
await Msg.ShowAsync();

Note: Your function must be defined async to use above await Msg.ShowAsync().

nawfal's user avatar

nawfal

70.3k56 gold badges326 silver badges369 bronze badges

answered Oct 10, 2016 at 5:19

shubz's user avatar

shubzshubz

1331 gold badge3 silver badges9 bronze badges

1

Try this:

string text = "My text that I want to display";
MessageBox.Show(text);

Xiaoy312's user avatar

Xiaoy312

14.3k1 gold badge32 silver badges44 bronze badges

answered Jun 7, 2016 at 17:32

user6436606's user avatar

answered Nov 27, 2009 at 0:20

Andrei Drynov's user avatar

Andrei DrynovAndrei Drynov

8,3826 gold badges39 silver badges39 bronze badges

Why not make use of a tooltip?

private void ShowToolTip(object sender, string message)
{
  new ToolTip().Show(message, this, Cursor.Position.X - this.Location.X, Cursor.Position.Y - this.Location.Y, 1000);
}

The code above will show message for 1000 milliseconds (1 second) where you clicked.

To call it, you can use the following in your button click event:

ShowToolTip("Hello World");

answered Jan 31, 2018 at 10:35

RooiWillie's user avatar

RooiWillieRooiWillie

2,1981 gold badge30 silver badges36 bronze badges

In Windows Forms, the ToolTip represents a tiny pop-up box which appears when you place your pointer or cursor on the control and the purpose of this control is it provides a brief description about the control present in the windows form. In ToolTip, you are allowed to change the shape of the ToolTip window by using IsBalloon Property.
With the help of this property, you can change the ToolTip window from the standard rectangular window to the balloon window. You can set this property in two different ways:

1. Design-Time: It is the easiest way to set the value of the IsBalloon property as shown in the following steps:

  • Step 1: Create a windows form as shown in the below image:
    Visual Studio -> File -> New -> Project -> WindowsFormApp
  • Step 2: Drag the ToolTip from the ToolBox and drop it on the form. When you drag and drop this ToolTip on the form it will automatically add to the properties(named as ToolTip on ToolTip1) of every controls present in the current windows from.

  • Step 3: After drag and drop you will go to the properties of the ToolTip and set the value of the IsBalloon property.

    Output:

2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the IsBalloon property of ToolTip programmatically with the help of given syntax:

public bool IsBalloon { get; set; }

Here, the value of this property is of System.Boolean type. If the value of this property is set to true, then the ToolTip window is of balloon window. And if the value of this property is set to be false, then the ToolTip window is of the standard rectangular window. The default value of this property is false.

The following steps show how to set the IsBalloon Property of the ToolTip dynamically:

  • Step 1: Create a ToolTip using the ToolTip() constructor is provided by the ToolTip class.
    // Creating a ToolTip
    ToolTip t = new ToolTip();
    
  • Step 2: After creating Tooltip, set the IsBalloon property of the Tooltip provided by the ToolTip class.
    // Setting the IsBalloon property
    t.IsBalloon = true;
    
  • Step 3: And last add this ToolTip to the controls using SetToolTip() method. This method contains the control name and the text which you want to display in the ToolTip box.
     t.SetToolTip(box1, "Name should start with Capital letter");

    Example:

    using System;

    using System.Collections.Generic;

    using System.ComponentModel;

    using System.Data;

    using System.Drawing;

    using System.Linq;

    using System.Text;

    using System.Threading.Tasks;

    using System.Windows.Forms;

    namespace WindowsFormsApp34 {

    public partial class Form1 : Form {

        public Form1()

        {

            InitializeComponent();

        }

        private void Form1_Load(object sender, EventArgs e)

        {

            Label l1 = new Label();

            l1.Location = new Point(140, 122);

            l1.Text = "Name";

            this.Controls.Add(l1);

            TextBox box1 = new TextBox();

            box1.Location = new Point(248, 119);

            box1.BorderStyle = BorderStyle.FixedSingle;

            this.Controls.Add(box1);

            Label l2 = new Label();

            l2.Location = new Point(140, 152);

            l2.Text = "Password";

            this.Controls.Add(l2);

            TextBox box2 = new TextBox();

            box2.Location = new Point(248, 145);

            box2.BorderStyle = BorderStyle.FixedSingle;

            this.Controls.Add(box2);

            ToolTip t = new ToolTip();

            t.Active = true;

            t.AutoPopDelay = 4000;

            t.InitialDelay = 600;

            t.IsBalloon = true;

            t.SetToolTip(box1, "Name should start with Capital letter");

            t.SetToolTip(box2, "Password should be greater than 8 words");

        }

    }

    }

    Output:

Last Updated :
19 Jul, 2019

Like Article

Save Article

  • Windows flight simulator скачать торрент
  • Windows fix скачать для windows 7 официальный сайт
  • Windows firewall как по русски
  • Windows fix it tool for windows 10
  • Windows firewall что это такое