Cкрытие и закрытие форм
Чтобы скрыть форму вызовите метод Hide.
В следующем примере кода показан способ скрытия формы frm1.
glob.frm1.Hide();
Внимание. При скрытии начальной формы вы не сможете без дополнительных команд закрыть приложение. Поэтому одновременоо с методом Hide для начальной формы прописывается команда ее открытия, привязанная к некоторому событию.
Пример: Можно передать функцию закрытия приложения другой форме. Для этого в событии FormClosed для этой формы необходимо прописать метод Show для начальной фомы.
private void Form2_FormClosed(object sender, FormClosedEventArgs e)
glob.frm1.Show();
Чтобы закрыть форму вызовите метод Close.
В следующем примере кода показан способ закрытия формы frm1.
glob.frm1.Close();
Примечание1. При закрытии начальной формы будет закрыто приложение.
Примечание2. При закрытии формы происходит ликвидация файловой переменной. Если закрытаяформа не является начальной и предполагается форму открывать неоднократно, то при открытии формы должны быть прописаны два метода: Show и new Form, например:
glob.frm2 = new Form2();
glob.frm2.Show();
Работа с элементами управления Windows Forms
Элемент управления — это компонент на форме, использующийся для отображения сведений или ввода пользовательских данных. В ходе разработки и изменения пользовательского интерфейса приложений Windows Forms требуется добавлять, выравнивать и размещать элементы управления. Каждый тип элемента управления имеет собственный набор свойств, методов и событий, соответствующих определенному назначению. С элементами управления можно работать в конструкторе или добавлять их динамически во время выполнения с помощью кода.
Существуют разнообразные элементы управления, которые можно разместить в Windows Forms в зависимости от требований конкретного приложения.
Добавление элементов управления в формы Windows Forms
Большинство форм разрабатываются путем добавления элементов управления на поверхность формы с целью создания пользовательского интерфейса.
Чтобы нарисовать элемент управления в форме, выполните следующие действия.
В панели элементов щелкните элемент управления, который требуется добавить в форму.
Щелкните место в форме, где должен располагаться левый верхний угол элемента управления, а затем перетащите указатель мыши на место, в котором должен располагаться правый нижний угол элемента управления.
Элемент управления добавляется на форму в указанное место с указанными размерами.
Примечание. Для каждого элемента управления существует размер, определенный по умолчанию. На форму можно добавить элемент управления, который будет иметь размер по умолчанию. Для этого требуется перетащить элемент управления из панели элементов на форму.
Чтобы перетащить элемент управления в форму, выполните следующие действия.
В панели элементов щелкните требуемый элемент управления и перетащите его в форму.
Элемент добавляется в форму в указанное место с размером по умолчанию.
Примечание. Чтобы добавить элемент управления с размером по умолчанию в верхний левый угол формы, щелкните его два раза в панели элементов.
Можно также добавлять элементы управления на форму динамически во время выполнения. В приведенном ниже примере элемент управления TextBox (текстовое поле) будет добавлен на форму после щелчка элемента управления Button (кнопка).
Примечание. Для следующей процедуры требуется форма с уже расположенным в ней элементом управления Кнопка Button1 .
Чтобы добавить элемент управления в форму с помощью программных средств, необходимо в метод, который обрабатывает событие (например, Click для кнопки) в результате которого должен быть добавлен элемент управления, добавить код, идентичный приведенному ниже. В коде прописаны команды: добавление ссылки на переменную элемента управления, задание расположения (свойство Location) элемента управления и добавления самого элемента управления.
Скрыть/показать форму OnVisibleChanged
т.е, при загрузке программы — форма сразу скрывается.
Как мне потом вызвать этот же метод, но только наоборот, чтобы форму показало?
Все тщетно, ну, оно и понятно, ведь вызывается OnVisibleChanged , а у него false стоит.
Скрывать/показывать форму через Hide/Show мне не подходят.
![]()
![]()
Изменяя видимость в функции реагирующей на на изменение видимости формы не правильно. Нужно перенести ваш код из OnVisibleChanged куда нибудь еще, например в OnLoad . А код @altexoander использовать в какой либо функции (кроме OnVisibleChanged ).
![]()
Проверяй состояние видимости формы и просто поменяй код. Например , у тебя сейчас
Кто тебе мешает проверить и поставить такое?
Т.е. на каждый вызов VisibleChanged ты просто будешь игнорировать внешние вызовы и поочередно менять видимость с true на false ( например 2умя вызовами .Show форма покажется и спряется вновь).
Hiding and Showing Forms in C Sharp

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
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:

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:

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.

report this ad
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:
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:
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:
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:
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:
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:
When the subForm button is pressed the form will be closed and removed from memory.
Как скрыть форму в c
![]()
Лучший отвечающий
Вопрос
Такой вопрос возник — как скрыть форму в шарпе? На мсдн не очень понятно про это написано, может кто-нить доступней объяснить?
Если я пытаюсь по клику бутона открыть одну форму и скрыть другую таким кодом:
То только открывается новая форма. Как правильно?
- Изменен тип Abolmasov Dmitry 7 марта 2012 г. 7:59
Ответы
Вы хотите скрыть форму из которой нажимаете кнопку?) Тогда вам не нужно создавать новый объект f1, нужно скрывать существующий. На него ссылается указатель this. Т.е. вам нужно писать this.Hide();
- Помечено в качестве ответа Abolmasov Dmitry 7 марта 2012 г. 7:59
Все ответы
Вы хотите скрыть форму из которой нажимаете кнопку?) Тогда вам не нужно создавать новый объект f1, нужно скрывать существующий. На него ссылается указатель this. Т.е. вам нужно писать this.Hide();
- Помечено в качестве ответа Abolmasov Dmitry 7 марта 2012 г. 7:59
И все же, почему у нас не получается сделать это через новосозданный объект?
И все же, почему у нас не получается сделать это через новосозданный объект?
Если сообщение помогло Вам, пожалуйста, не забудьте отметить его как ответ данной темы. Удачи в программировании!
Центры разработки
- Windows
- Office
- Visual Studio
- Microsoft Azure
- Дополнительно.
Обучение
- Microsoft Virtual Academy
- Канал Channel 9
- Журнал MSDN
Сообщество
- Новости
- Форумы
- Блоги
- Codeplex
Свяжитесь с нами
Программы
- BizSpark (для стартапов)
- Microsoft Imagine (for students)
- Информационный бюллетень
- Конфиденциальность и файлы cookie
- Условия использования
- Товарные знаки
© 2023 Microsoft