- Order of events ‘Form.Load’, ‘Form.Shown’ and ‘Form.Activated’ in Windows Forms
- 5 Answers 5
- Событие Form. Load (Access) Form.Load event (Access)
- Синтаксис Syntax
- Примечания Remarks
- Пример Example
- Поддержка и обратная связь Support and feedback
- How do I execute code AFTER a form has loaded?
- 8 Answers 8
- Программное добавление элементов управления в Windows Forms во время выполнения с помощью Visual C#
- Сводка
- Требования
- Создание приложения Windows Forms
- Настройка свойств формы и элемента управления
- Добавление элементов управления в форму
- Проверка работы
- Ссылки
Order of events ‘Form.Load’, ‘Form.Shown’ and ‘Form.Activated’ in Windows Forms
What is the difference between form Form.Load, Form.Shown and Form.Activated events? What is the order in which they are fired?
5 Answers 5
- Move: This event occurs when the form is moved. Although by default, when a form is instantiated and launched, the user does not move it, yet this event is triggered before the Load event occurs.
- Load: This event occurs before a form is displayed for the first time.
- VisibleChanged: This event occurs when the Visible property value changes.
- Activated: This event occurs when the form is activated in code or by the user.
- Shown: This event occurs whenever the form is first displayed.
- Paint: This event occurs when the control is redrawn.
- Deactivate: This event occurs when the form loses focus and is not the active form.
- Closing: This event occurs when the form is closing.
- Closed: This event occurs when the form is being closed.
The Load event fires when the form has been initialized, after its handle has been created but before it is shown.
The Shown event fires after the first time the form becomes visible, when you call form.Show() (or form.Visible = true ).
If you hide your form, then show it again, Shown will fire again. (But Load won’t)
The Activate event fires when the user switches to your form.
If the user switches to a different program (or form), then switches back to your form, Activate will fire again.
Событие Form. Load (Access) Form.Load event (Access)
Возникает при открытии формы и отображении ее записей. Occurs when a form is opened and its records are displayed.
Синтаксис Syntax
Expression. Load (Загрузка ) expression.Load
выражение: переменная, представляющая объект Form. expression A variable that represents a Form object.
Примечания Remarks
Для запуска макроса или процедуры обработки события при возникновении этих событий задайте для свойства OnLoad имя макроса или [процедура обработки события]. To run a macro or event procedure when these events occur, set the OnLoad property to the name of the macro or to [Event Procedure].
Событие Load вызывается действиями пользователя, такими как: The Load event is caused by user actions such as:
- Запуск приложения. Starting an application.
- Открытие формы с помощью команды Открыть в окне базы данных. Opening a form by choosing Open in the Database window.
- Выполнение макрокоманды «ОткрытьФорму» в макросе. Running the OpenForm action in a macro.
При запуске макроса или процедуры обработки события при возникновении события загрузки формы можно указать параметры по умолчанию для элементов управления или отобразить вычисляемые данные, которые зависят от данных в записях формы. By running a macro or an event procedure when a form’s Load event occurs, you can specify default settings for controls, or display calculated data that depends on the data in the form’s records.
При запуске макроса или процедуры обработки события при возникновении события выгрузки формы можно проверить, следует ли выгрузить форму, или указать действия, которые должны выполняться при выгрузке формы. By running a macro or an event procedure when a form’s Unload event occurs, you can verify that the form should be unloaded or specify actions that should take place when the form is unloaded. Кроме того, можно открыть другую форму или отобразить диалоговое окно с запросом имени пользователя, чтобы сделать запись в журнале, указав пользователя, который использовал эту форму. You can also open another form or display a dialog box requesting the user’s name to make a log entry indicating who used the form.
При первом открытии формы выполняются следующие события в указанном порядке. When you first open a form, the following events occur in this order:
Последовательно выберите пункты → загрузить → изменить размер → активировать → Текущая Open → Load → Resize → Activate → Current
Если вы пытаетесь решить, следует ли использовать событие Open или Load для макроса или процедуры обработки события, то одно существенное различие заключается в том, что событие Open можно отменить, но событие Load не может быть. If you are trying to decide whether to use the Open or Load event for your macro or event procedure, one significant difference is that the Open event can be canceled, but the Load event can’t. Например, если вы динамически создаете источник записей для формы в процедуре обработки события Open формы, можно отменить открытие формы, если нет записей для отображения. For example, if you are dynamically building a record source for a form in an event procedure for the form’s Open event, you can cancel opening the form if there are no records to display.
При закрытии формы выполняются следующие события в указанном порядке. When you close a form, the following events occur in this order:
Unload → Отключить → Закрыть Unload → Deactivate → Close
Событие unload (выгрузка ) возникает перед событием закрытия . The Unload event occurs before the Close event. Событие unload может быть отменено, но событие Close не может быть отменено. The Unload event can be canceled, but the Close event can’t.
При создании макросов или процедур обработки событий для событий, связанных с событием Load , таких как Активация и Получение фокуса, убедитесь в том, что они не конфликтуют (например, не приводят к возникновению ошибки в одном макросе или процедуре, которая отменяется другим) и не вызывает каскадных событий. When you create macros or event procedures for events related to the Load event, such as Activate and GotFocus, be sure that they don’t conflict (for example, make sure that you don’t cause something to happen in one macro or procedure that is canceled in another) and that they don’t cause cascading events.
Пример Example
В следующем примере отображается текущая дата в заголовке формы при загрузке формы. The following example displays the current date in the form’s caption when the form is loaded.
Чтобы попробовать пример, добавьте приведенную ниже процедуру обработки события в форму. To try the example, add the following event procedure to a form.
Поддержка и обратная связь Support and feedback
Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Have questions or feedback about Office VBA or this documentation? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь. Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.
How do I execute code AFTER a form has loaded?
In .NET, Windows Forms have an event that fires before the Form is loaded (Form.Load), but there is no corresponding event that is fired AFTER the form has loaded. I would like to execute some logic after the form has loaded.
Can anyone advise on a solution?
8 Answers 8
You could use the «Shown» event: MSDN — Form.Shown
«The Shown event is only raised the first time a form is displayed; subsequently minimizing, maximizing, restoring, hiding, showing, or invalidating and repainting will not raise this event.»
I sometimes use (in Load)
(change «this» to your form variable if you are handling the event on an instance other than «this»).
This pushes the invoke onto the windows-forms loop, so it gets processed when the form is processing the message queue.
[updated on request]
The Control.Invoke/Control.BeginInvoke methods are intended for use with threading, and are a mechanism to push work onto the UI thread. Normally this is used by worker threads etc. Control.Invoke does a synchronous call, where-as Control.BeginInvoke does an asynchronous call.
Normally, these would be used as:
It does this by pushing a message onto the windows message queue; the UI thread (at some point) de-queues the message, processes the delegate, and signals the worker that it completed. so far so good ;-p
OK; so what happens if we use Control.Invoke / Control.BeginInvoke on the UI thread? It copes. if you call Control.Invoke, it is sensible enough to know that blocking on the message queue would cause an immediate deadlock — so if you are already on the UI thread it simply runs the code immediately. so that doesn’t help us.
But Control.BeginInvoke works differently: it always pushes work onto the queue, even it we are already on the UI thread. This makes a really simply way of saying «in a moment», but without the inconvenience of timers etc (which would still have to do the same thing anyway!).
First time it WILL NOT start «AfterLoading»,
It will just register it to start NEXT Load.
I had the same problem, and solved it as follows:
Actually I want to show Message and close it automatically after 2 second. For that I had to generate (dynamically) simple form and one label showing message, stop message for 1500 ms so user read it. And Close dynamically created form. Shown event occur After load event. So code is
You could also try putting your code in the Activated event of the form, if you want it to occur, just when the form is activated. You would need to put in a boolean «has executed» check though if it is only supposed to run on the first activation.
This an old question and depends more upon when you need to start your routines. Since no one wants a null reference exception it is always best to check for null first then use as needed; that alone may save you a lot of grief.
The most common reason for this type of question is when a container or custom control type attempts to access properties initialized outside of a custom class where those properties have not yet been initialized thus potentially causing null values to populate and can even cause a null reference exceptions on object types. It means your class is running before it is fully initialized — before you have finished setting your properties etc. Another possible reason for this type of question is when to perform custom graphics.
To best answer the question about when to start executing code following the form load event is to monitor the WM_Paint message or hook directly in to the paint event itself. Why? The paint event only fires when all modules have fully loaded with respect to your form load event. Note: This.visible == true is not always true when it is set true so it is not used at all for this purpose except to hide a form.
The following is a complete example of how to start executing you code following the form load event. It is recommended that you do not unnecessarily tie up the paint message loop so we’ll create an event that will start executing your code outside that loop.
Программное добавление элементов управления в Windows Forms во время выполнения с помощью Visual C#
Эта статья поможет программным способом добавлять и настраивать элементы управления в форме Windows Forms с помощью Visual C#.
Исходная версия продукта: Visual C #
Исходный номер статьи базы знаний: 319266
Сводка
В этой статье приведены пошаговые инструкции по добавлению и настройке нескольких часто используемых элементов управления в форме Windows Forms. В примере кода отсутствует обработка событий.
Пакет средств разработки программного обеспечения (SDK) Microsoft .NET Framework предоставляет множество визуальных элементов управления, которые можно использовать для создания приложения Windows Forms. Вы можете добавлять и настраивать элементы управления во время конструирования в Visual Studio .NET или в Visual Studio. Вы можете добавлять и настраивать элементы управления программным способом во время выполнения.
Требования
В этой статье предполагается, что вы знакомы со следующими разделами:
- Синтаксис Visual C#
- Среда Visual Studio .NET, среда Visual Studio
- Назначение распространенных элементов управления Visual C#
Создание приложения Windows Forms
Запустите Visual Studio .NET или Visual Studio и создайте новый проект приложения Visual C# для Windows с именем винконтролс. По умолчанию форма Form1 добавляется в проект.
Дважды щелкните Form1, чтобы создать и просмотреть Form1_Load процедуру обработки события.
Добавьте в класс переменные частных экземпляров Form1 для работы с общими элементами управления Windows. Form1 Класс запускается следующим образом:
Код должен быть изменен в Visual Studio. Когда вы создаете проект Windows Forms, Visual C# добавляет по умолчанию одну форму в проект. Эта форма называется Form1. Два файла, представляющие форму, называются Form1.CS и Form1.Designer.CS. Вы пишете свой код в Form1.CS. Файл Designer.CS — это место, в котором конструктор Windows Forms записывает код, который реализует все действия, выполненные путем добавления элементов управления. Дополнительные сведения о конструкторе Windows Forms в Visual C# приведены в статье Создание проекта (Visual c#).
Настройка свойств формы и элемента управления
Нахождение Form1_Load процедуры обработки события и добавление в процедуру следующего кода для настройки внешнего вида элемента управления формы:
Добавьте следующий код в Form1_Load процедуру обработки события для настройки внешнего вида элемента управления «Кнопка»:
Добавьте следующий код для настройки внешнего вида элемента управления TextBox в Form1_Load :
Добавьте следующий код для настройки внешнего вида элемента управления ListBox в Form1_Load :
Добавьте следующий код, чтобы настроить внешний вид элемента управления CheckBox в Form1_Load :
Добавьте следующий код, чтобы настроить внешний вид элемента управления Label в Form1_Load :
Добавление элементов управления в форму
Добавьте следующий код, чтобы добавить каждый объект в Controls массив формы в конце Form1_Load :
Проверка работы
Чтобы убедиться, что пример работает, выберите команду начать в меню Отладка .
- Хотя отображаются форма и элементы управления, в настоящее время они не выполняют никаких действий, так как вы не записали обработчики событий.
- Помните, что позиции этих элементов управления являются статическими. Чтобы сделать их более надежными при растяжении формы, сделайте точки динамическими относительно положения формы. Если элементы управления статичны, растягивание формы может помешать отображению других элементов управления в форме.
Ссылки
Дополнительные сведения об использовании элементов управления программным способом можно найти в разделе приложения Windows в разделе Visual C# справочной документации по Visual Studio .NET Online или в справочной документации по Visual Studio Online.