Update from windows forms

Control. Update Метод

Определение

Вызывает перерисовку элементом управления недопустимых областей клиентской области. Causes the control to redraw the invalidated regions within its client area.

Комментарии

Выполняет все ожидающие запросы на рисование. Executes any pending requests for painting.

Существует два способа перерисовки формы и ее содержимого: There are two ways to repaint a form and its contents:

С помощью метода можно использовать одну из перегрузок Invalidate метода Update . You can use one of the overloads of the Invalidate method with the Update method.

Можно вызвать Refresh метод, который заставляет элемент управления перерисовывать себя и все его дочерние элементы. You can call the Refresh method, which forces the control to redraw itself and all its children. Это эквивалентно присвоению Invalidate метода true и его использованию с Update . This is equivalent to setting the Invalidate method to true and using it with Update.

InvalidateМетод управляет нарисованным или перекрашенным. The Invalidate method governs what gets painted or repainted. UpdateМетод управляет тем, когда происходит рисование или перерисовка. The Update method governs when the painting or repainting occurs. Если вы используете Invalidate методы и Update вместе, а не вызываете Refresh , что перерисовывается, зависит от того, какая перегрузка Invalidate используется. If you use the Invalidate and Update methods together rather than calling Refresh, what gets repainted depends on which overload of Invalidate you use. UpdateМетод просто заставляет элемент управления закрашен немедленно, но Invalidate метод управляет тем, что рисуется при вызове Update метода. The Update method just forces the control to be painted immediately, but the Invalidate method governs what gets painted when you call the Update method.

Дополнительные сведения см. в разделе WM_PAINT . For more information, see the WM_PAINT topic.

how to update a windows form GUI from another class?

how do you update a win forms control (ex. label, progress bar) from another class which created the GUI but not in the creating thread? (for example, an event handler of Program.cs)

I’ve found several posts regarding updating GUI from another thread using Invoke() method, but what i’ve found so far only works if the codes are written in the same class as the form

2 Answers 2

You need to call the Invoke method on the form. For example:

If you don’t need the updates to be finished before returning back to the method, you should use BeginInvoke instead of Invoke .

Well, there are two separate issues here:

  • Updating the UI from a different class
  • Updating the UI from a different thread

The two are almost completely orthogonal. Once you’ve solved each of them in isolation, you can put the two together.

If there are well-understood ways in which the UI needs to be changed (e.g. updating the text in a status bar or something like that) I would write methods in the UI class itself to do that, and just call those methods from the other class. Alternatively, you can expose the individual control of the UI — preferably through properties — and then use Control.Invoke in the normal way from the other class, e.g.

Читайте также:  Пакеты обновления для windows 10 pro

So long as you call Invoke on a control which «lives» on the same thread as all the controls you touch, it doesn’t matter which one you use. so an alternative could be:

One difference here is that in this latter code, the StatusLabel property is being evaluated in the worker thread — which could lead to race conditions if your UI is changing it to refer to different labels at different times. I would generally prefer the first approach.

(I agree with icktoofay’s comment about BeginInvoke being preferable unless you really need to wait, by the way. although you do then need to be careful about changes to any variables captured by anonymous functions.)

C#: Update Label Text On Windows Forms From Console Application

I’m trying to update a the text inside a label in a Windows Forms launched from a Console Application, as an example I’ve created this code.

I’ve done my research but my knowledge of Windows Forms is quite limited, the libraries for this are already included and are not a problem.

What else do I need to do to update the text or any other Control feature?

4 Answers 4

I run this on my pc, and work.

Just Add public function to change the existing label in the form:

And from the main function you call this function after creating form object

For this you need to create new form Example MainForm

If all you want is customization on startup, this is actually really simple; just like with any other object you want to customize, give it a constructor that accepts any arguments you want to use to customize the class behaviour. Like, in your case, the label text.

There is no need for threading or communication here. Setting that label from an external source is completely unnecessary. Just design the form class in advance, with the label already on it, and give it a custom constructor which accepts the string to put on that label.

And in the MyForm class itself:

By the way. I’m not sure if you’re clear on what a «console app» really is. Any program can be started from command prompt, and it’s perfectly possible to give a Windows app the static void Main(String[] args) constructor to make it accept command line parameters, and, in fact, also like any other application, you can change the Main function’s return type to int to make it return an exit code after it finished running. There is usually little use for a console app to show forms, though; that generally defeats the purpose of a console app.

Force GUI update from UI Thread

In WinForms, how do I force an immediate UI update from UI thread?

What I’m doing is roughly:

Label text does not get set to «Please Wait. » before the operation.

I solved this using another thread for the operation, but it gets hairy and I’d like to simplify the code.

Читайте также:  Урок информатики операционная система windows

11 Answers 11

At first I wondered why the OP hadn’t already marked one of the responses as the answer, but after trying it myself and still have it not work, I dug a little deeper and found there’s much more to this issue then I’d first supposed.

A better understanding can be gained by reading from a similar question: Why won’t control update/refresh mid-process

Lastly, for the record, I was able to get my label to update by doing the following:

Though from what I understand this is far from an elegant and correct approach to doing it. It’s a hack that may or may not work depending upon how busy the thread is.

Call label.Invalidate and then label.Update() — usually the update only happens after you exit the current function but calling Update forces it to update at that specific place in code. From MSDN:

The Invalidate method governs what gets painted or repainted. The Update method governs when the painting or repainting occurs. If you use the Invalidate and Update methods together rather than calling Refresh, what gets repainted depends on which overload of Invalidate you use. The Update method just forces the control to be painted immediately, but the Invalidate method governs what gets painted when you call the Update method.

Call Application.DoEvents() after setting the label, but you should do all the work in a separate thread instead, so the user may close the window.

I’ve just stumbled over the same problem and found some interesting information and I wanted to put in my two cents and add it here.

First of all, as others have already mentioned, long-running operations should be done by a thread, which can be a background worker, an explicit thread, a thread from the threadpool or (since .Net 4.0) a task: Stackoverflow 570537: update-label-while-processing-in-windows-forms, so that the UI keeps responsive.

But for short tasks there is no real need for threading although it doesn’t hurt of course.

I have created a winform with one button and one label to analyze this problem:

My analysis was stepping over the code (using F10) and seeing what happened. And after reading this article Multithreading in WinForms I have found something interesting. The article says at the bottom of the first page, that the UI thread can not repaint the UI until the currently executed function finishes and the window is marked by Windows as «not responding» instead after a while. I have also noticed that on my test application from above while stepping through it, but only in certain cases.

(For the following test it is important to not have Visual Studio set to fullscreen, you must be able to see your little application window at the same time next to it, You must not have to switch between the Visual Studio window for debugging and your application window to see what happens. Start the application, set a breakpoint at label1->Text . , put the application window beside the VS window and place the mouse cursor over the VS window.)

Читайте также:  Браузер который не грузит windows

When I click once on VS after app start (to put the focues there and enable stepping) and step through it WITHOUT moving the mouse, the new text is set and the label is updated in the update() function. This means, the UI is repainted obviously.

When I step over the first line, then move the mouse around a lot and click somewhere, then step further, the new text is likely set and the update() function is called, but the UI is not updated/repainted and the old text remains there until the button1_click() function finishes. Instead of repainting, the window is marked as «not responsive»! It also doesn’t help to add this->Update(); to update the whole form.

Adding Application::DoEvents(); gives the UI a chance to update/repaint. Anyway you have to take care that the user can not press buttons or perform other operations on the UI that are not permitted!! Therefore: Try to avoid DoEvents()!, better use threading (which I think is quite simple in .Net).
But (@Jagd, Apr 2 ’10 at 19:25) you can omit .refresh() and .invalidate() .

My explanations is as following: AFAIK winform still uses the WINAPI function. Also MSDN article about System.Windows.Forms Control.Update method refers to WINAPI function WM_PAINT. The MSDN article about WM_PAINT states in its first sentence that the WM_PAINT command is only sent by the system when the message queue is empty. But as the message queue is already filled in the 2nd case, it is not send and thus the label and the application form are not repainted.

<>joke> Conclusion: so you just have to keep the user from using the mouse 😉 <>/joke>

обновление формы

есть label1, button1.
с самого начала label1 скрыт визуально

в реальности происходит ничего(видимый эффект), форма обновляется только после и поэтому label1 не появляется на время задержки.
Можно ли обновлять форму во время выполнения функции или каким способом можно решить проблему? возможно нужно организовывать совсем по другому программу?

Добавлено через 11 минут
функцией Update();
Сам ответил на свой вопрос, всем спасибо за поддержку

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

Обновление главной формы
Здравствуйте. Имеется код: Форма 1 private void button1_Click(object sender, EventArgs.

Обновление формы по нажатию F5
Всем привет. Подскажите, пожалуйста, как обновить форму по нажатию F5 (как будто только открылась)

Обновление формы в курсовой на cs
Здраствуйте, подскажите пожалуйста, как сделать так, чтобы при добавлении новой строки с данными.

Заказываю контрольные, курсовые, дипломные и любые другие студенческие работы здесь или здесь.

Обновление формы из таймера
Добрый день,спасибо,что откликнулись на мой призыв У меня есть два класса Form1 и Timer Timer: .

Обновление listbox со второй формы
Доброго времени суток. На первой форме находится листбокс, во второй форме присходит заполнение.

Обновление одной формы из другой
Здравствуйте. Можете ответить на вопрос. Открыты два окна. Как из одной формы приложения выполнить.

Обновление datagridview из другой формы
Всем привет.Очень нужна помощь знающих людей.Необходимо сделать небольшой проект на winforms.Суть.

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