Windows forms modal form

Example

After defining the structure of your form with the WinForms designer you can display your forms in code with two different methods.

  • Method — A Modeless form

     Form1 aForm1Instance = new Form1(); 
     aForm1Instance.Show();
    
  • Method — A Modal Dialog

     Form2 aForm2Instance = new Form2(); 
     aForm2Instance.ShowDialog();
    

The two methods have a very important distinction. The first method (the modeless one) shows your form and then returns immediately without waiting the closure of the just opened form. So your code continues with whatever follows the Show call.
The second method instead (the modal one) opens the form and blocks any activity on the whole application until you close the form via the close button or with some buttons appropriately configured to close the form


Purchase and download the full PDF and ePub versions of this Visual C# eBook for only $9.99

When developing a Windows application using C# it is a fairly safe bet to assume that it will consist of multiple forms (otherwise known as windows). It is unlikely, however, that all of those forms will need to be displayed as soon as the application starts up. In fact, it is more likely that most of the forms will remain hidden until the user performs some action that requires a form to be displayed.

In this chapter we will cover the topic of hiding and showing forms when developing applications in C#.

Contents

Contents

  • 1 Creating a C# Application Containing Multiple Forms
  • 2 Understanding Modal and Non-modal Forms
  • 3 Writing C# Code to Display a Non-Modal Form
  • 4 Writing C# Code to Display a Modal Form
  • 5 Hiding Forms in C#
  • 6 Closing Forms in C#

Creating a C# Application Containing Multiple Forms

Before we can look at hiding and showing Forms we first need to create an application in Visual Studio which contains more than one form. Begin by starting Visual Studio and creating a new Windows Form Application project called CSharpShowForm.

Visual Studio will prime the new project with a single form. Click on the Form to select it and, using the Properties panel change the Name of the form to mainForm. Next we need to add a second form. To do this, click on the Add New Item in the Visual Studio toolbar to invoke the Add New Item window:

Visual studio add new item.jpg

The Add New Item window allows new items of various types to be added to the project. For this example we just need to add a new Windows Form to our application. With Windows Form selected in the window change the name of the form to subForm.cs and click on Add. Visual Studio will now display an additional tab containing the second form:

C sharp two forms.jpg

Switch between the two forms by clicking on the respective tabs.

Now that you have created two forms, add a Button to each form by displaying the Toolbox and dragging a Button onto each form.

Now that we have created an application with two forms the next step is provide a mechanism for hiding and showing subForm. Before doing that, however, we first need to understand the difference between modal and non-modal windows.

Understanding Modal and Non-modal Forms

A Windows form can be displayed in one of two modes, modal and non-modal. When a form is non-modal it means that other forms in the other forms in the application remain accessible to the user (in that they can still click on controls or use the keyboard in other forms).

When a form is modal, as soon as it is displayed all other forms in the application are disabled until the modal dialog is dismissed by the user. Modal forms are typically used when the user is required to complete a task before proceeding to another part of the application. In the following sections we will cover the creation of both modal and non-modal forms in C#.

Writing C# Code to Display a Non-Modal Form

We are going to use the button control on mainForm to display subForm when it is clicked by the user. To do this, double click on the button control to display the Click event procedure.

Before we can call any methods on the subForm we first need to instantiate it as an object. To do so we simply use the new statement to create a new object from the subForm class:

        private void button1_Click(object sender, EventArgs e)
        {
            subForm myNewForm = new subForm();
        }

In this event procedure we want to call the Show() method of the myNewForm object we have instantiated from the subForm class to make it display. To achieve this, modify the Click event handler as follows:

        private void button1_Click(object sender, EventArgs e)
        {
            subForm myNewForm = new subForm();

            myNewForm.Show();
        }

To test this code press F5 to compile and run the application. When it appears click on the button in the main form and the sub form will appear. You will notice that, since this is a non-modal form, you can still interact with the main form while the sub-form is visible (i.e you can click on the button in the main form).

Close the running application.

Another way to hide and show a form is to set the Visible property of the form object to either true or false. For example:

        private void button1_Click(object sender, EventArgs e)
        {
            subForm myNewForm = new subForm();

            myNewForm.Visible = true;
        }

Writing C# Code to Display a Modal Form

We will now modify the event procedure for the button to create a modal form. To do so we need to call the ShowDialog() method of the subForm. Modify the Click event procedure of the mainForm button as follows:

       private void button1_Click(object sender, EventArgs e)
        {
            subForm myNewForm = new subForm();

            myNewForm.ShowDialog();
        }

Press F5 once again to build and run the application. After pressing the button in the main form to display the sub form you will find that the main form is inactive as long as the sub form is displayed. Until the sub form is dismissed this will remain the case.

Close the running application.

Hiding Forms in C#

There are two ways to make a form disappear from the screen. One way is to Hide the form and the other is to Close the form. When a form is hidden, the form and all its properties and settings still exist in memory. In other words, the form still exists, it is just not visible. When a form is closed, the form is physically deleted from memory and will need to be completely recreated before it can be displayed again.

To hide a form it is necessary to call the Hide() method of the form to be hidden. Using our example, we will wire up the button on the subForm to close the form. Click on the tab for the second form (the subForm) in your design and double click on the button control to display the Click event procedure.

One very important point to note here is that the button control is going to hide its own Form. In this case, the event procedure can reference this instead of referencing the object by name. With this in mind, modify the procedure as follows:

        private void button1_Click(object sender, EventArgs e)
        {
            this.Hide();
        }

Press F5 to build and run the application. Click on the button in the main form to display the sub form. Now, when you press the button in the sub form, the form will be hidden.

Closing Forms in C#

As mentioned in the previous section, in order to remove a form both from the display, and from memory, it is necessary to Close rather than Hide it. In Visual Studio double click, once again, the button in subForm to view the Click event procedure. Once again, because the button is in the form we are closing we need to use this instead of subForm when calling the Close() method:

        private void button1_Click(object sender, EventArgs e)
        {
            this.Close();
        }

When the subForm button is pressed the form will be closed and removed from memory.

Purchase and download the full PDF and ePub versions of this Visual C# eBook for only $9.99


Вступление

В этом разделе объясняется, как работает механизм WinForms для отображения форм и того, как вы контролируете их жизнь.

Показать немодальную или модальную форму

После определения структуры вашей формы с помощью дизайнера WinForms вы можете отображать свои формы в коде двумя разными способами.

  • Метод — модельная форма

     Form1 aForm1Instance = new Form1(); 
     aForm1Instance.Show();
    
  • Метод — Модальный диалог

     Form2 aForm2Instance = new Form2(); 
     aForm2Instance.ShowDialog();
    

Эти два метода имеют очень важное различие. Первый метод (немодальный) показывает вашу форму и затем немедленно возвращается, не дожидаясь закрытия только что открытой формы. Таким образом, ваш код продолжает все, что следует за вызовом Show. Второй метод вместо этого (модальный) открывает форму и блокирует любую активность во всем приложении до тех пор, пока вы не закроете форму с помощью кнопки закрытия или с некоторыми кнопками, соответствующим образом настроенными для закрытия формы

Закрытие немодальной формы

Используется немодальная форма (обычно), когда вам нужно показать что-то постоянное рядом с основным экраном приложения (подумайте о легенде или представлении о потоке данных, поступающих асинхронно с устройства или в дочернее окно MDI).
Но немодальная форма представляет собой уникальную задачу, когда вы хотите ее закрыть. Как получить экземпляр и вызвать метод Close в этом экземпляре?

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

theGlobalInstance.Close();
theGlobalInstance.Dispose();
theGlobalInstance = null;

Но мы также можем использовать коллекцию Application.OpenForms, где механизм формы хранит все экземпляры форм, созданные и открытые.

Вы можете извлечь этот конкретный экземпляр из этой коллекции и вызвать метод Close

Form2 toClose = Application.OpenForms.OfType<Form2>().FirstOrDefault();
if(toClose != null)
{
    toClose.Close();
    toClose.Dispose();
}

Закрытие модальной формы

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

Чтобы закрыть форму, вам просто нужно установить свойство DialogResult формы (любому значению с помощью DialogResult.None ) в каком-либо обработчике событий. Когда ваш код выйдет из обработчика событий, механизм WinForm скроет форму, а код, следующий за начальным вызовом метода ShowDialog , продолжит выполнение.

private cmdClose_Click(object sender, EventArgs e)
{
    this.DialogResult = DialogResult.Cancel;
}

Вызывающий код может отображать возвращаемое значение из ShowDialog, чтобы определить, какую кнопку пользователь нажал в форме. При отображении с использованием ShowDialog() , форма не удаляться автоматически (так как она была просто скрыта и не закрыта), поэтому очень важно , чтобы использовать , using блок , чтобы обеспечить форма расположена.

Ниже приведен пример проверки результата использования встроенного OpenFileDialog , проверки результата и доступа к свойствам из диалогового окна перед его удалением.

using (var form = new OpenFileDialog())
{
    DialogResult result = form.ShowDialog();
    if (result == DialogResult.OK)
    {
        MessageBox.Show("Selected file is: " + form.FileName);
    }
}

Вы также можете установить свойство DialogResult на кнопку. Нажатие этой кнопки устанавливает для свойства DialogResult в форме значение, связанное с кнопкой. Это позволяет закрыть форму без добавления обработчика событий для установки DialogResult в коде.

Например, если вы добавите кнопку OK в свою форму и установите ее свойство в DialogResult.OK форма автоматически закрывается, когда вы нажимаете эту кнопку, а вызывающий код получает DialogResult.OK в ответ на ShowDialog() метода ShowDialog() .

  1. C# Tutorial
  2. Modal Forms in C#

Submitted by joken on Tuesday, May 13, 2014 — 11:46.

This tutorial will show you how to use the Modal Forms in C#. in C# instead of using a method “Show()” we will change it into “ShowDialog()”method and this creates a Modal form. This Modal form is something you need deal with before you can proceed with your program process.
To display a dialog box modally, here’s the following code:

  1. Form2 formDialog = new Form2();

  2. formDialog.ShowDialog();

In C#, a ShowDialog method has an optional argument that can be used to specify a parent-child relationship for a form.
At this time, let’s create a new project called “modal” then on the form1 design it look like as shown below:

Then add another from and design it looks like as shown below:

Next double click the “Ok” button and the code view will appear. Then add the following code:

  1. private void ok_Click(object sender, EventArgs e)

  2. {

  3. this.DialogResult = DialogResult.OK;

  4. }

The code above will record the result of the button click, and set it to OK. Then double click the “Abort” button and add the following code:

  1. private void abort_Click(object sender, EventArgs e)

  2. {

  3. this.DialogResult = DialogResult.Abort;

  4. }

At this time, let’s go back to Form1 then double click the “Click Me!” button and add the following code:

  1. Form2 formDialog = new Form2();

  2. formDialog.ShowDialog();

  3. if (formDialog.ShowDialog() == DialogResult.OK)

  4. {

  5.      MessageBox.Show(«OK button is click!»);

  6. }else if (formDialog .ShowDialog () == DialogResult .Abort )

  7. {

  8.       MessageBox.Show(«Abort button  is click!»);

  9. }

The code above will simply checks to see if the OK or the Abort button is clicked. If so, it display a message. you can now try to run the application and test it. In my example, I just simply click the “OK” button and the output looks like as shown below.

n3

Add new comment

  • 929 views

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Самая легкая версия windows 10 pro
  • Как сменить пароль на удаленном рабочем столе windows
  • Восстановление магазина windows 10 ltsc
  • Как посмотреть ip адрес принтера на windows 7
  • Активатор windows xp sp2 32 bit