System windows forms application doevents

Windows Forms Application Base. Do Events Метод

Определение

Обрабатывает все сообщения Windows, которые в данный момент находятся в очереди сообщений. Processes all Windows messages currently in the message queue.

Примеры

В этом примере используется My.Application.DoEvents метод, чтобы разрешить обновление пользовательского интерфейса TextBox1 . This example uses the My.Application.DoEvents method to allow the UI for TextBox1 to update.

Этот код должен быть в форме, имеющей TextBox1 компонент со Text свойством. This code should be in a form that has a TextBox1 component with a Text property.

Комментарии

My.Application.DoEvents Метод позволяет приложению обрабатывать другие события, которые могут возникнуть при выполнении кода. The My.Application.DoEvents method allows your application to handle other events that might be raised while you code runs. My.Application.DoEvents Метод имеет то же поведение, что и DoEvents метод. The My.Application.DoEvents method has the same behavior as the DoEvents method.

При запуске приложения Windows Forms создается новая форма, которая затем ожидает обработки событий. When you run a Windows Forms application, it creates a new form, which then waits for events to be handled. Каждый раз, когда форма обрабатывает событие, например нажатие кнопки, она обрабатывает весь код, связанный с этим событием. Each time the form handles an event, such as a button click, it processes all the code associated with that event. Все остальные события ожидают в очереди. All other events wait in the queue. Пока код обрабатывает событие, приложение не отвечает. While your code handles the event, your application does not respond. Например, окно не перерисовывается, если в верхней части перетаскивается другое окно. For example, the window does not repaint if another window is dragged on top.

При вызове My.Application.DoEvents в коде приложение может управлять другими событиями. If you call My.Application.DoEvents in your code, your application can handle the other events. Например, если код добавляет данные в ListBox цикл, а после каждого шага в цикле вызывается My.Application.DoEvents , форма перерисовывается при перетаскивании другого окна. For example, if your code adds data to a ListBox in a loop, and after each step of the loop it calls My.Application.DoEvents , your form repaints when another window is dragged over it. Если удалить My.Application.DoEvents из кода, форма не будет перерисовываться до завершения выполнения обработчика событий нажатия кнопки. If you remove My.Application.DoEvents from your code, your form will not repaint until the click event handler of the button is finished executing.

Как правило, этот метод используется в цикле для обработки сообщений. Typically, you use this method in a loop to process messages.

Application. Do Events Method

Definition

Processes all Windows messages currently in the message queue.

Examples

The following code example demonstrates using the DoEvents method. When the example runs, a user can select graphics files from an OpenFileDialog. The selected files are displayed in the form. The DoEvents method forces a repaint of the form for each graphics file opened. To run this example, paste the following code in a form containing a PictureBox named PictureBox1 , an OpenFileDialog named OpenFileDialog1 , and a button named fileButton . Call the InitializePictureBox and InitializeOpenFileDialog methods from the form’s constructor or Load method.

In Visual Studio, if you add an OpenFileDialog to your form by using a drag operation, you will have to modify the following InitializeOpenFileDialog method by removing the line that creates a new instance of OpenFileDialog.

The example also requires that the Control.Click event of the Button control and the FileOk event of the OpenFileDialog are connected to the event handlers defined in the example. When the example is running, display the dialog box by clicking the button.

Читайте также:  Windows зависает от hdd

Remarks

When you run a Windows Form, it creates the new form, which then waits for events to handle. Each time the form handles an event, it processes all the code associated with that event. All other events wait in the queue. While your code handles the event, your application does not respond. For example, the window does not repaint if another window is dragged on top.

If you call DoEvents in your code, your application can handle the other events. For example, if you have a form that adds data to a ListBox and add DoEvents to your code, your form repaints when another window is dragged over it. If you remove DoEvents from your code, your form will not repaint until the click event handler of the button is finished executing. For more information on messaging, see User Input in Windows Forms.

Unlike Visual Basic 6.0, the DoEvents method does not call the Thread.Sleep method.

Typically, you use this method in a loop to process messages.

Calling this method causes the current thread to be suspended while all waiting window messages are processed. If a message causes an event to be triggered, then other areas of your application code may execute. This can cause your application to exhibit unexpected behaviors that are difficult to debug. If you perform operations or computations that take a long time, it is often preferable to perform those operations on a new thread. For more information about asynchronous programming, see Asynchronous Programming Model (APM).

Use of Application.DoEvents()

Can Application.DoEvents() be used in C#?

Is this function a way to allow the GUI to catch up with the rest of the app, in much the same way that VB6’s DoEvents does?

10 Answers 10

Hmya, the enduring mystique of DoEvents(). There’s been an enormous amount of backlash against it, but nobody ever really explains why it is «bad». The same kind of wisdom as «don’t mutate a struct». Erm, why does the runtime and the language supports mutating a struct if that’s so bad? Same reason: you shoot yourself in the foot if you don’t do it right. Easily. And doing it right requires knowing exactly what it does, which in the case of DoEvents() is definitely not easy to grok.

Right off the bat: almost any Windows Forms program actually contains a call to DoEvents(). It is cleverly disguised, however with a different name: ShowDialog(). It is DoEvents() that allows a dialog to be modal without it freezing the rest of the windows in the application.

Most programmers want to use DoEvents to stop their user interface from freezing when they write their own modal loop. It certainly does that; it dispatches Windows messages and gets any paint requests delivered. The problem however is that it isn’t selective. It not only dispatches paint messages, it delivers everything else as well.

And there’s a set of notifications that cause trouble. They come from about 3 feet in front of the monitor. The user could for example close the main window while the loop that calls DoEvents() is running. That works, user interface is gone. But your code didn’t stop, it is still executing the loop. That’s bad. Very, very bad.

There’s more: The user could click the same menu item or button that causes the same loop to get started. Now you have two nested loops executing DoEvents(), the previous loop is suspended and the new loop is starting from scratch. That could work, but boy the odds are slim. Especially when the nested loop ends and the suspended one resumes, trying to finish a job that was already completed. If that doesn’t bomb with an exception then surely the data is scrambled all to hell.

Читайте также:  Настройка виртуальной машины vmware windows 10

Back to ShowDialog(). It executes DoEvents(), but do note that it does something else. It disables all the windows in the application, other than the dialog. Now that 3-feet problem is solved, the user cannot do anything to mess up the logic. Both the close-the-window and start-the-job-again failure modes are solved. Or to put it another way, there is no way for the user to make your program run code in a different order. It will execute predictably, just like it did when you tested your code. It makes dialogs extremely annoying; who doesn’t hate having a dialog active and not being able to copy and paste something from another window? But that’s the price.

Which is what it takes to use DoEvents safely in your code. Setting the Enabled property of all your forms to false is a quick and efficient way to avoid problems. Of course, no programmer ever actually likes doing this. And doesn’t. Which is why you shouldn’t use DoEvents(). You should use threads. Even though they hand you a complete arsenal of ways to shoot your foot in colorful and inscrutable ways. But with the advantage that you only shoot your own foot; it won’t (typically) let the user shoot hers.

Where is the Application.DoEvents() in WPF?

I have the following sample code that zooms each time a button is pressed:

as you can see, there is a problem, that I thought solve by using Application.DoEvents(); but. it does not exist a priori in .NET 4.

9 Answers 9

The old Application.DoEvents() method has been deprecated in WPF in favor of using a Dispatcher or a Background Worker Thread to do the processing as you have described. See the links for a couple of articles on how to use both objects.

If you absolutely must use Application.DoEvents(), then you could simply import the system.windows.forms.dll into your application and call the method. However, this really isn’t recommended, since you’re losing all the advantages that WPF provides.

Try something like this

Well, I just hit a case where I start work on a method that runs on the Dispatcher thread, and it needs to block without blocking the UI Thread. Turns out that msdn explains how to implement a DoEvents() based on the Dispatcher itself:

Some may prefer it in a single method that will enforce the same logic:

If you need just update window graphic, better use like this

seems to work as well.

One problem with both proposed approaches is that they entail idle CPU usage (up to 12% in my experience). This is suboptimal in some cases, for instance when modal UI behavior is implemented using this technique.

The following variation introduces a minimum delay between frames using a timer (note that it is written here with Rx but can be achieved with any regular timer):

Since the introduction of async and await its now possible to relinquish the UI thread partway through a (formerly)* synchronous block of code using Task.Delay , e.g.

I’ll be honest, I’ve not tried it with the exact code above, but I use it in tight loops when I’m placing many items into an ItemsControl which has an expensive item template, sometimes adding a small delay to give the other stuff on the UI more time.

On Windows Store, when there’s a nice theme transition on the collection, the effect is quite desirable.

  • see comments. When I was quickly writing my answer, I was thinking about the act of taking a synchronous block of code and then relinquishing the thread back to its caller, the effect of which makes the block of code asynchronous. I don’t want to completely rephrase my answer because then readers can’t see what Servy and I were bickering about.
Читайте также:  Как удалить snapshots mac os

Функция DoEvents DoEvents function

Уступает выполнение, чтобы операционная система могла обработать другие события. Yields execution so that the operating system can process other events.

Синтаксис Syntax

DoEvents() DoEvents( )

Примечания Remarks

Функция выполнения событий DoEvents возвращает целое число, представляющее количество открытых форм в автономных версиях Visual Basic, таких как профессиональный выпуск Visual Basic. The DoEvents function returns an Integer representing the number of open forms in stand-alone versions of Visual Basic, such as Visual Basic, Professional Edition. DoEvents возвращает нуль во всех других приложениях. DoEvents returns zero in all other applications.

DoEvents передает управление операционной системе. DoEvents passes control to the operating system. Управление возвращается, когда операционная система завершает обработку событий в очереди и все ключи в очереди SendKeys отправлены. Control is returned after the operating system has finished processing the events in its queue and all keys in the SendKeys queue have been sent.

Функция DoEvents наиболее полезна для простых действий, таких как разрешение пользователю отменить процесс (например, поиск файла) после его запуска. DoEvents is most useful for simple things like allowing a user to cancel a process after it has started, for example a search for a file. Для длительных процессов передачу процессора лучше выполнять с помощью функции Timer или передачи задачи компоненту ActiveX EXE. For long-running processes, yielding the processor is better accomplished by using a Timer or delegating the task to an ActiveX EXE component. В последнем случае задача может продолжать полностью независимо от приложения, а операционная система отвечает за многозадачность и временной срез. In the latter case, the task can continue completely independent of your application, and the operating system takes care of multitasking and time slicing.

Временно уступая процессор в процедуре события, всегда проверяйте, чтобы процедура не выполнялась повторно из другой части вашего кода, прежде чем будет возвращен первый вызов; это может привести к непредсказуемым результатам. Any time you temporarily yield the processor within an event procedure, make sure the procedure is not executed again from a different part of your code before the first call returns; this could cause unpredictable results. Кроме того, не используйте DoEvents, если есть вероятность, что другие приложения будут взаимодействовать с вашей процедурой непредсказуемым образом в то время, на которое вы отдали управление. In addition, do not use DoEvents if other applications could possibly interact with your procedure in unforeseen ways during the time you have yielded control.

Пример Example

В этом примере функция DoEvents используется для вызова передачи выполнения в операционной системе один раз на каждые 1000 итераций цикла. This example uses the DoEvents function to cause execution to yield to the operating system once every 1000 iterations of the loop. DoEvents возвращает количество открытых форм Visual Basic, но только в том случае, если ведущее приложение — Visual Basic. DoEvents returns the number of open Visual Basic forms, but only when the host application is Visual Basic.

См. также See also

Поддержка и обратная связь 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.

Оцените статью