Три ужасные фичи программирования из прошлого
Время на прочтение6 мин
Количество просмотров57K
Я верю в программистское клише о том, что большинство плохих фич имеет причины для существования. Ненавидимый многими оператор goto
позволяет быстро и удобно выбраться из глубоко вложенной структуры, если пользоваться им с умом. Определённая степень нестрогости типов позволяет им быть более изящными. Указатели памяти могут заставить вас возненавидеть свою жизнь, но они были критически важны в те годы, когда компьютерное «железо» было слабее современного умного термостата. Список можно продолжать.
Но когда я вспоминаю об этих запылённых старых реликтах, то осознаю, что некоторые старые идеи настолько плохи, что лучше всего было бы сжечь их навечно. В этой статье я расскажу о трёх фичах языков программирования, которые были настоящим кошмаром.
1. On Error Resume Next (классический VB 6)
On Error Resume Next
реализует подход, который в большинстве ситуаций возникновения ошибок хуже всего: «просто продолжай выполнение». При этом он делает его правилом по умолчанию для любой проблемы. Представьте, если бы мы реагировали так же на сбои в реальной жизни. Попал в аварию на машине? Просто продолжай ехать!
' Напишем этот код на случай, если не сможем
' подключиться к базе данных.
On Error Resume Next
Dim TotalPayment As Decimal
Dim TotalHours As Decimal
Dim HourlyRate As Decimal
TotalPayment = 5000
' Ой, мы забыли задать TotalHours!
' Код не должен работать, но у нас есть иммунитет к ошибкам.
HourlyRate = TotalPayment / TotalHours
' Всё вроде правильно. Давайте обновим базу данных!
Call UpdateDatabase(HourlyRate)
Но подождите, это ещё не всё. On Error Resume Next
не имеет никаких границ. Он будет продолжать свой путь через длинные цепочки ошибок. Он даже не обязан находиться в начале модуля вашего кода (можно вставить его в любое место кода и переключиться на обычный режим при помощи On Error Resume 0
).
On Error Resume Next
гарантирует, что вы достигнете конца процедуры кода, и это соблазняет нас своей определённостью. Вам не нужно беспокоиться, что будет пропущена какая-то важная часть кода очистки. Но в пункт назначения вы доберётесь не совсем в том виде, в котором начинали путь. Это агрессивная стратегия «дойти до конца любой ценой», только «доходить до конца», если тебе не удалось выполнить обязательную задачу, обычно и не стоит.
Единственная возможная причина, по которой можно использовать On Error Resume Next
— это полное отсутствие кода обработки ошибок, когда вам нужно пропустить все не особо важные проблемы, которые вы игнорируете. Например, вы можете осознанно создавать файл, который уже может существовать, настраивать принтер, который может не поддерживаться, или выполнять вычисление, которое может привести к делению на ноль. Объективно, в такой момент вы поступаете не очень хорошо, но мы вас прощаем. Однако если вы используете On Error Resume Next
, то усугубляете своё невежество, беззаботно двигаясь в сторону ещё большей катастрофы.
Не буду врать. Я пользовался этой конструкцией (и она мне нравилась!) задолго до того, как начал учиться программированию по-настоящему. А теперь она практически мертва. VB.NET, текущая версия VB, которая влачит жалкое существование в мире .NET, заменила On Error Resume Next
логичной структурированной обработкой ошибок. Хотя так ли это на самом деле? Оказывается, в современном .NET можно по-прежнему использовать обработку ошибок из созданного десятки лет назад классического VB, в том числе и On Error Resume Next
. Это полное безумие, но, к счастью, кажется, сегодня этим никто не занимается.
Тем не менее, On Error Resume Next
всё ещё существует в реальном коде. Возможно, вы обнаружите, что эта конструкция ломает макрос электронной таблицы Excel, которую использует ваш отдел продаж. Спасибо тебе за это, VBA.
2. DoEvents (Windows Forms)
Даже по расплывчатому имени встроенной функции DoEvents()
уже можно понять, что стоит готовиться к чему-то уродливому. И метод Application.DoEvents()
нас не разочаровал.
DoEvents()
— это когда-то популярный, но очень опасный костыль для Windows-приложений, не желающих работать с многопоточностью. Например, классическим сценарием его использования является обновление UI в коротком цикле. Представим, что мы выполняем очень затратную по времени математическую операцию и помещаем значения в list box. Пользователь не увидит ни одно из этих чисел, пока вы не вернёте управление и Windows не сможет обновить окно. Обычно этого не случается, пока код не завершит работу, если вы не выполняете эту работу в фоне в отдельном потоке.
DoEvents()
просит приложение на мгновение приостановиться, чтобы Windows могла сделать то, что ей нужно. Так что если вы вызовете DoEvents()
в цикле, то, вероятно, дадите операционной системе возможность перерисовать окно:
for (int i = 0; i < 1000000; i++)
{
listBox.Items.Add(someCalculation(i));
// Этот цикл блокирует UI. Мы можем отрефакторить код
// или просто вставить этот маленький костыль...
Application.DoEvents();
}
Но после этого ситуация быстро начинает развиваться по наклонной. Проблема в том, что ты точно не знаешь, что будет делать DoEvents()
. Другие части приложения могут получать сообщения Windows (допустим, если пользователь куда-то нажал), и могут начать выполнять свой код в месте, которое ты создал при вызове DoEvents()
. Звучит печально, но на самом деле это очень весело (если вам нравится отладка по ночам), потому что результат на каждом компьютере будет чуть-чуть различаться!
Как знает любой программист, самая худшая проблема — это не когда что-то не работает, а когда программа работает на одном компьютере, но обладает такой вариативностью, что в другом месте способна загадочным образом вылетать. И если у вас нет пока этой проблемы, DoEvents()
вносит как раз нужное количество недетерминированности, чтобы она появилась.
Разумеется, работать с потоками сложно. Но в .NET уже есть простые в использовании инструменты, например, компонент BackgroundWorker
, позволяющие выполнять всю нужную работу в другом потоке при помощи простой модели на основе событий. Нет необходимости придумывать какие-то костыли с помощью DoEvents()
, и их создают очень немногие. Тем не менее, этот метод по-прежнему таится в библиотеке классов, импортированный из олдскульного VB и доступный для каждого языка .NET, в том числе и для современного C#.
Отвратительно.
3. Динамический Goto (COBOL)
В отличие от предыдущих проблем, этот кошмар программирования лично меня никогда не касался. (Может, я и стар, но я не стар как COBOL.) Однако эта фича настолько безумна, что я не могу её не упомянуть.
Представьте, что вы программируете на древнем языке с загадочными операторами управления потоком. А потом вы обнаруживаете, что этот язык способен изменять свой собственный код в процессе исполнения, меняя пути исполнения, по которым он движется через различные синтаксические структуры. Замысловато! Если всё работает, то программа сохраняет своё тонкое равновесие. Если она не работает, то вы получаете нечто вроде уробороса, поедающего свой собственный хвост.
Фича, которую я называю динамическим goto, имеет в языке COBOL имя оператора ALTER
. Он позволяет изменять существующую команду GO TO
так, чтобы она передавала контроль не той части программы, которая прописана в коде. Оператор GO TO
даже можно изменять многократно, перемещать в разные части кода, как по лабиринту. Проще говоря, ALTER
берёт всё то, что вы ненавидите в GO TO
— запутывающий поток выполнения, спагетти-код — и значительно это усиливает.
Вот о какой структуре я говорю
IF WS-X = 2 THEN
ALTER SELECT-PATH TO PROCEED TO PATH-2.
ELSE IF WS-X = 3 THEN
ALTER SELECT-PATH TO PROCEED TO PATH-3.
END-IF.
GO TO SELECT-PATH.
SELECT-PATH.
GO TO PATH-1.
В этом примере команда GO TO SELECT-PATH
может перенести нас к метке SELECT-PATH
(которая затем направляет нас к PATH-1
). Но в зависимости от предыдущей проверки переменной её можно изменить так, чтобы она перенаправляла нас к PATH-2
или к PATH-3
. И кто знает, что могло бы произойти в других частях кода. Другими словами, мы не можем точно сказать, куда приведёт нас GO TO
, если только не знаем полную историю выполнения приложения. Но не волнуйтесь, наверняка где-то есть лог, который можно изучить.
Можно назвать это метапрограммированием, но большинство из нас просто скажет, что это Очень Плохая Идея.
Да, на маломощных компьютерах того времени с небольшим размером стека подобная чёрная магия имела смысл (возможно?). И может быть, были времена, когда On Error Resume Next
и DoEvents()
были наилучшими компромиссами в случае сложных проблем. Сегодня, спустя шестьдесят с лишним лет после создания языка, оператор ALTER
считается устаревшим, и запланировал к удалению. Что ж, по крайней мере, они решили исправить ошибку.
Когда в следующий раз кто-то справедливо укажет вам на странные особенности JavaScript, на безумие необъявленных переменных или неявную типизацию любого языка, напомните ему, что всегда может быть хуже. И хуже было.
Надеюсь, вы никогда не столкнётесь с этим кошмаром в старой кодовой базе. А если у вас есть собственные любимые чудовищные конструкции прошлого, то поделитесь ими в комментариях!
C#,Windows Form, WPF, LINQ, Entity Framework Examples and Codes
Application.DoEvents Method Processes all Windows messages currently in the message queue.
To understand how Application.DoEvents() method works, create a new winforms application and add a picturebox and assign a image and add a button to the form.
write the below code, in form1.cs file Form1_Load method and button1_Click method
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
private void Form1_Load(object sender, EventArgs e) { pictureBox1.Visible = false; } private void button1_Click(object sender, EventArgs e) { pictureBox1.Visible = true; //Application.DoEvents(); System.Threading.Thread.Sleep(5000); pictureBox1.Visible = false; } |
Now run the above code.
When you click on button, you cannot see the picture box, though we are making picture box visible on button click.
Now uncomment the Applicaton.DoEvents line and run the code. You can see the picture box is visible on button click because calling Appliation.DoEvents method makes the current thread to be suspended all the waiting windows messages in the queue to be processed.
You may also like
Name
Application.DoEvents Method
Class
System.Windows.Forms.Application
Syntax
Application.DoEvents( )
Description
Allows the operating system to process events and messages waiting in
the message queue.
For example, you can allow a user to click a Cancel button while a
processor- intensive operation is executing. In this case, without
DoEvents, the click event is not processed until after the operation
had completed. With DoEvents, Windows allocates time for the Cancel
button’s Click event to fire and the event handler
to execute.
Example
The following example uses a form with two command buttons to
illustrate DoEvents. Suppose the user clicks CommandButton1. Then the
Do
loop in the click event executes indefinitely.
However, if the user clicks CommandButton2, its click event is
processed when the DoEvents
statement in
CommandButton1_Click is executed. This sets the Boolean flag to
False
, which terminates the Do
loop.
Option Explicit Private lngCtr As Long Private blnFlag As Boolean Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles Button1.Click blnFlag = True Do While blnFlag lngCtr = lngCtr + 1 DoEvents( ) Loop MsgBox("Loop interrupted after " & lngCtr & _ " iterations.") End Sub Private Sub CommandButton2_Click( ) blnFlag = False End Sub
Programming Tips and Gotchas
-
While DoEvents can be indispensable for increasing the responsiveness of your application, it should at the same time be used judiciously, since it entails an enormous performance …
How to cause a Winform (and all its child controls) to fully render before you do additional processing.
- Download demo — 12.6 KB
Introduction
One of my pet peeves is forms that don’t instantly appear. You see it all the time: the user clicks a button, then waits a few seconds until the expected UI appears. This is typically due to the newly-created form performing some time-consuming (blocking) task in its Load()
event handler (or, in the non-.NET world, the WM_INITDIALOG
message handler). Aside from being poor UI design (never leave the user wondering what’s happening!), it can have some really undesirable consequences: a button-click doesn’t have an immediate effect, users will tend to click the button again, which can result in the action being invoked twice.
Since my earliest Windows programming, I’ve always implemented «instant feedback» in my Forms (f/k/a «dialog boxes»). My technique has evolved as Windows API has evolved; I’ll discuss my older techniques (which can still be used in .NET), and end up with my current implementation using .NET WinForms APIs.
The Goal
Create a simple, reliable mechanism for doing post-form-load processing which ensures that the form is «fully rendered» before the post-load processing commences. This means that all the controls in the form itself as well as all child controls (in the dialog template) have been drawn as the user would expect to see them.
Background
This is a pretty basic technique; novice WinForms coders should be able to implement it.
An understanding of the startup sequence of a Form (a.k.a. window, a.k.a. dialog) is useful: http://msdn.microsoft.com/en-us/library/86faxx0d%28VS.80%29.aspx.
Most of these events have direct Windows message (WM_*
) analogs. However, .NET adds the System.Windows.Forms.Form.Shown
event — which does not have a corresponding Windows message — and that event is the basis for a relatively clean way to do post-Load()
processing. (MSDN docs on the Shown()
event: read here).
Complicating the issue is the asynchronous, not-totally-predictable nature of messages. When a window is created (and thus its children are created), the exact sequence of the various windows’ messages varies from instance to instance. Certainly, each window’s messages occur in the same sequence every time, but the sequence of the parent/child messages is unpredictable, creating a race condition. The most unfortunate result of this being that sometimes a dialog will render properly, sometimes it won’t. Removing this uncertainty — ensuring predictability — is a big part of this solution.
Finally, it’s very important to perform your blocking processing after the form and all children are fully rendered. Blocking the UI thread (and message queue) mid-render, results in some pretty partial ugly UI that looks like your app crashed!
Notice how the form’s frame and unclipped client area have rendered but certain child controls’ client areas still show the UI «below» the form. Also notice how the listbox
has rendered but the other controls (GroupBox
es, ComboBox
es) have not (I haven’t investigated why that is).
Here’s how it should look fully rendered:
Solution: Before .NET
(If you wrote Windows code before .NET — with or without MFC — this should look familiar.)
Here’s a simplified sequence of the messages generated upon window creation:
WM_CREATE (window) or WM_INITDIALOG (dialogbox) ... WM_SHOWWINDOW ... WM_ACTIVATE (wParam has WA_* state)
In those days, I did something like this:
#define WMUSER_FIRSTACTIVE (WM_USER+1) bool m_bSeenFirstActivation = false; virtual void DoPostLoadProcessing(); LRESULT WndProc(msg, wparam, lparam) { switch(msg) { case WM_ACTIVATE: if((wparam==WA_ACTIVE) && !m_bSeenFirstActivation) { m_bSeenFirstActivation = true; PostMessage(m_hWnd, WMUSER_FIRSTACTIVE); } break; case WMUSER_FIRSTACTIVE: DoPostLoadProcessing(); // Derived classes override this break; } }
The theory was that, by posting a message to myself after receiving the initial activation message, I could be confident that:
- The dialog had been fully rendered, and
- The post-load processing is performed asynchronously and on the dialog’s UI thread:
- Using
PostMessage()
ensures it’s asynchronous. The posted message is added to the end of the queue and gets processed after all pending (UI-related) messages are processed. - Doing stuff in the dialog’s UI thread is important — many controls get very upset if you try to manipulate them from a thread other than the UI thread.
- Using
And, sometimes I did this:
#define IDT_FIRSTACTIVE 0x100 bool m_bSeenFirstActivation = false; virtual void DoPostLoadProcessing(); LRESULT WndProc(msg, wparam, lparam) { switch(msg) { case WM_ACTIVATE: if((wparam==WA_ACTIVE) && !m_bSeenFirstActivation) { m_bSeenFirstActivation = true; SetTimer(m_hWnd, IDT_FIRSTACTIVE, 50, NULL); PostMessage(m_hWnd, WMUSER_FIRSTACTIVE); } break; case WM_TIMER: if(wParam == IDT_FIRSTACTIVE) { KillTimer(m_hWnd, IDT_FIRSTACTIVE); DoPostLoadProcessing(); // Derived classes override this } break; } }
The theory here is essentially the same: Set a quick (50ms) timer in the initial activation. The WM_TIMER
message occurs asynchronously and with some extra delay. The timer is immediately killed (we only wanted the first timer message), then the derived class’ DoPostLoadProcessing()
is called. (Yeah, I know that timers < 55ms are useless on a PC.)
Both techniques work pretty well, and could still be used in .NET, though they’re messy.
Solution: Doing It in .NET
The Basics
.NET’s addition of the Shown()
event simplifies things greatly. Now, in theory, all you’d need to do is handle the Shown()
event and do your processing there:
void MyForm_Shown(object sender, EventArgs e) { // Do blocking stuff here }
Simple, right? Well, almost. It turns out that the Shown()
event gets fired before all the form’s child controls have fully rendered, so you still have the race condition. My solution to that is to call Application.DoEvents()
to clear out the message queue before doing any additional post-processing:
void MyForm_Shown(object sender, EventArgs e) { Application.DoEvents(); // Do blocking stuff here }
A More Complete Solution
The problem with the basic solution above is that you must remember to call Application.DoEvents()
in each form’s Shown()
event handler. While this is admittedly a minor nuisance, I’ve chosen to take the solution one step further by implementing a base dialog class that handles the Shown()
event, calls DoEvents()
, then invokes an event of its own:
public class BaseForm : Form { public delegate void LoadCompletedEventHandler(); public event LoadCompletedEventHandler LoadCompleted; public BaseForm() { this.Shown += new EventHandler(BaseForm_Shown); } void BaseForm_Shown(object sender, EventArgs e) { Application.DoEvents(); if (LoadCompleted != null) LoadCompleted(); } }
And, derived forms simply implement a LoadCompleted()
handler:
this.LoadCompleted += new FormLoadCompletedDemo.BaseForm.LoadCompletedEventHandler( this.MyFormUsingBase_LoadCompleted); ... private void MyFormUsingBase_LoadCompleted() { // Do blocking stuff here }
and… bonus!: LoadCompleted()
appears in Visual Studio’s Properties/Events pane:
(I named the event LoadCompleted
so that it would appear immediately after the Load
event in the events pane, making it easier to find.)
With that, you can do all your long-duration stuff in LoadCompleted()
and be confident that the basic UI will be fully rendered while the user waits. Of course, you should still follow good UI practices such as showing a WaitCursor
, maybe disabling the controls until they’re usable (a useful visual cue to the user), and perhaps even showing a progressbar for really long waits (e.g.: show a marquee progressbar during a SQL call that takes 5+ seconds).
Demo Project
The attached VS2008/C# project demonstrates the behavior and the solution. It implements a form with four buttons:
All four buttons do the same thing, which is pop up a child dialog containing:
- A
listbox
that gets populated with 50K items. This population blocks the UI thread for a couple of seconds, which allows the app to demonstrate the solutions to the problem. - A few other controls, principally
ComboBox
es. For whatever reason,ComboBox
es are particularly prone to incomplete rendering due to blocking code.
Each child form sets the WaitCursor
in its Load()
event as a visual feedback that things are happening.
However, each button causes a different form-loading behavior:
- Do processing in Load event — the
listbox
is loaded in the form’sLoad()
event handler, resulting in the form not appearing until thelistbox
is fully loaded (bad). - Open Form Without DoEvents — the
listbox
is loaded in the form’sShown()
event handler, butApplication.DoEvents()
is not called, resulting in the form appearing partially rendered untillistbox
-load completes (very bad). - Open Form *with* DoEvents — the
listbox
is loaded in the form’sShown()
event handler andApplication.DoEvents()
is called, resulting in the form appearing fully rendered untillistbox
-load completes (good!!!). - Open Form derived from BaseForm — Same as Open Form *with* DoEvents, but implemented using a base class and custom event.
Conclusion
Like so many things in Windows (and in life!), the solution to this problem is pretty simple, but figuring it out takes a bit of trial and error. I hope that my solution outlined above saves you some time and helps you create more responsive UIs.
History
- 12th February, 2010: Initial version
System.Windows.Forms.Application.DoEvents()
Here are the examples of the csharp api class System.Windows.Forms.Application.DoEvents() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
200 Examples
1. Example
Project: Krypton
Source File: DragTargetNavigatorTransfer.cs
public override bool PerformDrop(Point screenPt, PageDragEndData data) { // Transfer the dragged pages into our navigator instance KryptonPage page = ProcessDragEndData(_navigator, data); // Make the last page transfer the newly selected page of the navigator if (page != null) { // If the navigator is allowed to have a selected page then select it if (_navigator.AllowTabSelect) _navigator.SelectedPage = page; // Need to layout so the new cell has been added as a child control and // therefore can receive the focus we want to give it immediately afterwards _navigator.PerformLayout(); if (!_navigator.IsDisposed) { // Without this DoEvents() call the dropping of multiple pages in a complex arrangement causes an exception for // a complex reason that is hard to work out (i.e. I'm not entirely sure). Something to do with using select to // change activation is causing the source workspace control to dispose to earlier. Application.DoEvents(); _navigator.Select(); } } return true; }
2. Example
Project: Krypton
Source File: DragTargetWorkspaceCellEdge.cs
public override bool PerformDrop(Point screenPt, PageDragEndData data) { // We n/n ..... /n //View Source file for more details /n }
3. Example
Project: Krypton
Source File: DragTargetWorkspaceCellTransfer.cs
public override bool PerformDrop(Point screenPt, PageDragEndData data) { // Transfer the dragged pages into the existing cell KryptonPage page = ProcessDragEndData(Workspace, _cell, data); // Make the last page transfer the newly selected page of the cell if (page != null) { // Does the cell allow the selection of tabs? if (_cell.AllowTabSelect) _cell.SelectedPage = page; if (!_cell.IsDisposed) { // Without this DoEvents() call the dropping of multiple pages in a complex arrangement causes an exception for // a complex reason that is hard to work out (i.e. I'm not entirely sure). Something to do with using select to // change activation is causing the source workspace control to dispose to earlier. Application.DoEvents(); _cell.Select(); } } return true; }
4. Example
Project: Krypton
Source File: DragTargetWorkspaceEdge.cs
public override bool PerformDrop(Point screenPt, PageDragEndData data) { // Tran/n ..... /n //View Source file for more details /n }
5. Example
Project: dp2
Source File: AmazonSearchForm.cs
void search_Idle(object sender, EventArgs e) { Application.DoEvents(); // TODO: ???? }
6. Example
Project: dp2
Source File: CardPrintForm.cs
void document_SetProgress(object sender, SetProgressEventArgs e) { Application.DoEvents(); if (e.Value == -1) { this.estimate.SetRange(e.Start, e.End); this.stop.SetProgressRange(e.Start, e.End); this.progressBar_records.Minimum = (int)e.Start; this.progressBar_records.Maximum = (int)e.End; } else { if ((this.m_lCount++ % 10) == 1) this.stop.SetMessage("???? " + ProgressEstimate.Format(this.estimate.Estimate(e.Value)) + " ????? " + ProgressEstimate.Format(this.estimate.delta_passed)); this.stop.SetProgressValue(e.Value); // this.stop.SetMessage(e.Value.ToString() + " - " + (((double)e.Value / (double)e.End) * 100).ToString() + "%"); this.progressBar_records.Value = (int)e.Value; } }
7. Example
Project: dp2
Source File: ExternalChannel.cs
void Channel_Idle(object sender, IdleEventArgs e) { // e.bDoEvents = this._doEvents; // 2016/1/26 if (this._doEvents) Application.DoEvents(); }
8. Example
Project: dp2
Source File: EntityRegisterBase.cs
void channel_Idle(object sender, IdleEventArgs e) { Application.DoEvents(); }
9. Example
Project: NSMB-Editor
Source File: ProgressWindow.cs
public void setValue(int val) { progressBar1.Value = val; Application.DoEvents(); }
10. Example
Project: NSMB-Editor
Source File: ProgressWindow.cs
public void SetCurrentAction(string current) { currentAction.Text = current; Application.DoEvents(); }
11. Example
Project: NSMB-Editor
Source File: ProgressWindow.cs
public void WriteLine(string line) { textBox1.AppendText(line+"\r\n"); Application.DoEvents(); }
12. Example
Project: Eddie
Source File: WindowReport.cs
public void SetStep(string step, string text, int perc) { lblStep.Text = step; pgrStep.Value = perc; txtBody.Text = text; cmdCopyClipboard.Enabled = (perc == 100); cmdSave.Enabled = (perc == 100); // For refresh, especially Mono-Linux Invalidate(); Update(); Refresh(); Application.DoEvents(); }
13. Example
Project: DotSpatial
Source File: TimedProgressMeter.cs
public void SendProgress() { if (Silent) return; if (ProgressHandler == null) return; ProgressHandler.Progress(Key, _prog, Key + ", " + _prog + "% Complete."); Application.DoEvents(); // Allow the form to update a status bar if necessary. }
14. Example
Project: DotSpatial
Source File: SymbologyStatusStrip.cs
private void UpdateProgress(string key, int percent, string message) { if (ProgressBar != null) ProgressBar.Value = percent; if (ProgressLabel != null) ProgressLabel.Text = message; // hack: I think there is a bug somewhere if we need to call DoEvents at the end of this event handler. Application.DoEvents(); }
15. Example
Project: EvilFOCA
Source File: FormSplash.cs
private void FormSplash_FormClosing(object sender, FormClosingEventArgs e) { Application.DoEvents(); }
16. Example
Project: InnovatorAdmin
Source File: ConnectionEditor.cs
private void exploreButton_Click(object sender, EventArgs e) { try { exploreButton.Text = "Opening Browser..."; Application.DoEvents(); ((ConnectionData)_bs.Current).Explore(); } catch (Exception ex) { Utils.HandleError(ex); } finally { exploreButton.Text = "Explore"; } }
17. Example
Project: NiVirtualCam
Source File: frm_Main.cs
private void FrmMainShown(object sender, EventArgs e) { this.lbl_wait.Dock = DockStyle.Fill; this.Enabled = false; Application.DoEvents(); this.broadcaster.SendBitmap(Resources.PleaseWait); this.Init(); if (this.isIdle && this.cb_device.SelectedIndex != -1 && this.cb_type.SelectedIndex != -1) { if (this.Start()) { this.iNoClient = 0; this.halt_timer.Start(); } else { this.broadcaster.ClearScreen(); } } else { this.broadcaster.ClearScreen(); } if (!this.isIdle) { if (this.IsAutoRun) { this.Visible = false; } } this.lbl_wait.Visible = false; this.Enabled = true; Application.DoEvents(); }
18. Example
Project: tesvsnip
Source File: StringsEditor.cs
private void FitColumns() { Application.DoEvents(); // handle outstanding events then do column sizing this.listStrings.AutoFitColumnHeaders(); }
19. Example
Project: falloutsnip
Source File: StringsEditor.cs
private void FitColumns() { Application.DoEvents(); // handle outstanding events then do column sizing this.listStrings.AutoFitColumnHeaders(); }
20. Example
Project: gitextensions
Source File: FormSettings.cs
private void settingsTreeViewUserControl1_SettingsPageSelected(object sender, SettingsPageSelectedEventArgs e) { panelCurrentSettingsPage.Controls.Clear(); var settingsPage = e.SettingsPage; if (settingsPage != null && settingsPage.GuiControl != null) { panelCurrentSettingsPage.Controls.Add(settingsPage.GuiControl); e.SettingsPage.GuiControl.Dock = DockStyle.Fill; string title = e.SettingsPage.GetTitle(); if (e.SettingsPage is PluginSettingsPage) { title = "Plugin: " + title; } this.Text = _translatedTitle + " - " + title; Application.DoEvents(); Cursor.Current = Cursors.WaitCursor; settingsPage.OnPageShown(); Cursor.Current = Cursors.Default; bool isInstantSavePage = settingsPage.IsInstantSavePage; labelInstantSaveNotice.Visible = isInstantSavePage; buttonOk.Enabled = true; buttonCancel.Enabled = true; if (e.IsTriggeredByGoto) { settingsPage.GuiControl.Focus(); } } else { this.Text = _translatedTitle; } }
21. Example
Project: MaterialWinforms
Source File: BackGroundDim.cs
void FormToDim_LocationChanged(object sender, EventArgs e) { Location = ((Form)sender).Location; Application.DoEvents(); }
22. Example
Project: FunctionHacker
Source File: formProgress.cs
private void formProgress_Load(object sender, EventArgs e) { Application.DoEvents(); }
23. Example
Project: HaSuite
Source File: Initialization.cs
private void InitializeWzFiles(string wzPath, WzMapleVersion fileVersion) { Prog/n ..... /n //View Source file for more details /n }
24. Example
Project: HaSuite
Source File: HaCreatorStateManager.cs
void ribbon_HaRepackerClicked() { WaitWindow ww = new WaitWindow("Opening HaRepacker..."); ww.Show(); Application.DoEvents(); HaRepacker.Program.WzMan = new HaRepackerLib.WzFileManager(); bool firstRun = HaRepacker.Program.PrepareApplication(false); HaRepacker.GUI.MainForm mf = new HaRepacker.GUI.MainForm(null, false, firstRun); mf.unloadAllToolStripMenuItem.Visible = false; mf.reloadAllToolStripMenuItem.Visible = false; foreach (KeyValuePair<string, WzFile> entry in Program.WzManager.wzFiles) mf.Interop_AddLoadedWzFileToManager(entry.Value); ww.EndWait(); lock (multiBoard) { mf.ShowDialog(); } HaRepacker.Program.EndApplication(false, false); }
25. Example
Project: KeeThief
Source File: StatusLoggerForm.cs
public bool SetProgress(uint uPercent) { if(uPercent != m_uLastPercent) { m_pbProgress.Value = (int)uPercent; m_uLastPercent = uPercent; Application.DoEvents(); } return !m_bCancelled; }
26. Example
Project: KeeThief
Source File: StatusLoggerForm.cs
public bool ContinueWork() { Application.DoEvents(); return !m_bCancelled; }
27. Example
Project: KeeThief
Source File: StatusProgressForm.cs
public bool ContinueWork() { Application.DoEvents(); return !m_bCancelled; }
28. Example
Project: Irony
Source File: fmGrammarExplorer.cs
private void ClearParserOutput() { lblSrcLineCount.Text = string.Empty; lblSrcTokenCount.Text = ""; lblParseTime.Text = ""; lblParseErrorCount.Text = ""; lstTokens.Items.Clear(); gridCompileErrors.Rows.Clear(); gridParserTrace.Rows.Clear(); lstTokens.Items.Clear(); tvParseTree.Nodes.Clear(); tvAst.Nodes.Clear(); Application.DoEvents(); }
29. Example
Project: Irony
Source File: fmGrammarExplorer.cs
private void ShowCompileStats() { if (_parseTree == null) return; lblSrcLineCount.Text = string.Empty; if (_parseTree.Tokens.Count > 0) lblSrcLineCount.Text = (_parseTree.Tokens[_parseTree.Tokens.Count - 1].Location.Line + 1).ToString(); lblSrcTokenCount.Text = _parseTree.Tokens.Count.ToString(); lblParseTime.Text = _parseTree.ParseTimeMilliseconds.ToString(); lblParseErrorCount.Text = _parseTree.ParserMessages.Count.ToString(); Application.DoEvents(); //Note: this time is "pure" parse time; actual delay after cliking "Compile" includes time to fill ParseTree, AstTree controls }
30. Example
Project: NLog
Source File: RichTextBoxTargetTests.cs
[Test] public void AutoScrollTest() { try { RichTextBoxTarget target = new RichTextBoxTarget() { ControlName = "Control1", Layout = "${level} ${logger} ${message}", ShowMinimized = true, ToolWindow = false, AutoScroll = true, }; var form = target.TargetForm; SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace); for (int i = 0; i < 100; ++i) { logger.Info("Test"); Application.DoEvents(); Assert.AreEqual(target.TargetRichTextBox.SelectionStart, target.TargetRichTextBox.TextLength); Assert.AreEqual(target.TargetRichTextBox.SelectionLength, 0); } } finally { LogManager.Configuration = null; } }
31. Example
Project: NLog
Source File: RichTextBoxTargetTests.cs
[Test] public void MaxLinesTest() { try { RichTextBoxTarget target = new RichTextBoxTarget() { ControlName = "Control1", Layout = "${message}", ShowMinimized = true, ToolWindow = false, AutoScroll = true, }; Assert.AreEqual(0, target.MaxLines); target.MaxLines = 7; var form = target.TargetForm; SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace); for (int i = 0; i < 100; ++i) { logger.Info("Test {0}", i); } Application.DoEvents(); string expectedText = "Test 93\nTest 94\nTest 95\nTest 96\nTest 97\nTest 98\nTest 99\n"; Assert.AreEqual(expectedText, target.TargetRichTextBox.Text); } finally { LogManager.Configuration = null; } }
32. Example
Project: Switcheroo
Source File: LockKeyResetter.cs
public void Dispose() { if (capslock) { // press caps lock KeyboardKey capslockKey = new KeyboardKey(Keys.CapsLock); capslockKey.PressAndRelease(); Application.DoEvents(); if ((capslockKey.State & 0x01) != 0x01) throw new Exception("Cannot enable caps lock."); } for (int i = MODIFIER_KEYS.Length-1; i >= 0; i--) { if (simpleModifiers[i]) { new KeyboardKey(MODIFIER_KEYS[i]).Press(); } } }
33. Example
Project: Irony
Source File: fmGrammarExplorer.cs
private void ClearParserOutput() { lblSrcLineCount.Text = string.Empty; lblSrcTokenCount.Text = ""; lblParseTime.Text = ""; lblParseErrorCount.Text = ""; lstTokens.Items.Clear(); gridCompileErrors.Rows.Clear(); gridParserTrace.Rows.Clear(); lstTokens.Items.Clear(); tvParseTree.Nodes.Clear(); tvAst.Nodes.Clear(); Application.DoEvents(); }
34. Example
Project: Irony
Source File: fmGrammarExplorer.cs
private void ShowCompileStats() { if (_parseTree == null) return; lblSrcLineCount.Text = string.Empty; if (_parseTree.Tokens.Count > 0) lblSrcLineCount.Text = (_parseTree.Tokens[_parseTree.Tokens.Count - 1].Location.Line + 1).ToString(); lblSrcTokenCount.Text = _parseTree.Tokens.Count.ToString(); lblParseTime.Text = _parseTree.ParseTime.ToString(); lblParseErrorCount.Text = _parseTree.ParserMessages.Count.ToString(); Application.DoEvents(); //Note: this time is "pure" parse time; actual delay after cliking "Compile" includes time to fill ParseTree, AstTree controls }
35. Example
Project: Bulk-Crap-Uninstaller
Source File: PropertiesWindow.cs
private void OnSelectedTabChanged(object sender, EventArgs e) { if (tabControl1.SelectedTab == null) return; UseWaitCursor = true; Application.DoEvents(); dataGridView1.DataSource = Functions.Properties.GetInfo(tabControl1.SelectedTab.Tag as ApplicationUninstallerEntry, CurrentlyVisiblePage); // Make first column shorter, since it contains much less text. Default FillWeight is around 34 var firstColumn = dataGridView1.Columns.GetFirstColumn(new DataGridViewElementStates()); if (firstColumn != null) { firstColumn.FillWeight = 35f; dataGridView1.Sort(firstColumn, ListSortDirection.Ascending); } Text = _titleBeginning + tabControl1.SelectedTab.Text; UseWaitCursor = false; }
36. Example
Project: Switcheroo
Source File: LockKeyResetter.cs
public void Dispose() { if (capslock) { // press caps lock KeyboardKey capslockKey = new KeyboardKey(Keys.CapsLock); capslockKey.PressAndRelease(); Application.DoEvents(); if ((capslockKey.State & 0x01) != 0x01) throw new Exception("Cannot enable caps lock."); } for (int i = MODIFIER_KEYS.Length-1; i >= 0; i--) { if (simpleModifiers[i]) { new KeyboardKey(MODIFIER_KEYS[i]).Press(); } } }
37. Example
Project: LiveSplit
Source File: fmGrammarExplorer.cs
private void ClearParserOutput() { lblSrcLineCount.Text = string.Empty; lblSrcTokenCount.Text = ""; lblParseTime.Text = ""; lblParseErrorCount.Text = ""; lstTokens.Items.Clear(); gridCompileErrors.Rows.Clear(); gridParserTrace.Rows.Clear(); lstTokens.Items.Clear(); tvParseTree.Nodes.Clear(); tvAst.Nodes.Clear(); Application.DoEvents(); }
38. Example
Project: LiveSplit
Source File: fmGrammarExplorer.cs
private void ShowCompileStats() { if (_parseTree == null) return; lblSrcLineCount.Text = string.Empty; if (_parseTree.Tokens.Count > 0) lblSrcLineCount.Text = (_parseTree.Tokens[_parseTree.Tokens.Count - 1].Location.Line + 1).ToString(); lblSrcTokenCount.Text = _parseTree.Tokens.Count.ToString(); lblParseTime.Text = _parseTree.ParseTimeMilliseconds.ToString(); lblParseErrorCount.Text = _parseTree.ParserMessages.Count.ToString(); Application.DoEvents(); //Note: this time is "pure" parse time; actual delay after cliking "Compile" includes time to fill ParseTree, AstTree controls }
39. Example
Project: PokemonGo-Bot
Source File: EvolvingDialog.cs
public void RunAnimation( PokemonId source, PokemonId target) { var sourceImage = PokeImgManager.GetPokemonVeryLargeImage(source); var targetImage = PokeImgManager.GetPokemonVeryLargeImage(target); pictureBox1.Image = sourceImage; pictureBox2.Visible =false; progressBar1.Value = 0; pictureBox1.Location = new Point(26, 222); for (var i = 0; i < 44;i++){ Application.DoEvents(); progressBar1.Value += progressBar1.Maximum/(48); RandomHelper.RandomSleep(550); var x = pictureBox1.Location.X; var y = pictureBox1.Location.Y - 5; pictureBox1.Location = new Point(x,y); } pictureBox1.Image = targetImage; for (var i = 0; i < 8;i++){ Application.DoEvents(); progressBar1.Value += progressBar1.Maximum/(48)/2; RandomHelper.RandomSleep(275); var x = pictureBox1.Location.X; var y = pictureBox1.Location.Y + 27; pictureBox1.Location = new Point(x,y); } progressBar1.Value = progressBar1.Maximum; for (var i = 0; i < 8;i++){ Application.DoEvents(); RandomHelper.RandomSleep(275); } }
40. Example
Project: AutoCADCodePack
Source File: Test.cs
[CommandMethod("DetectSelfIntersection")] public static void DetectSelfIntersection() // mod 20130202 { ObjectId[] ids = QuickSelection.SelectAll("LWPOLYLINE").ToArray(); ProgressMeter meter = new ProgressMeter(); meter.Start("Detecting..."); meter.SetLimit(ids.Length); var results = ids.QWhere(x => { bool result = (x as Polyline).IsSelfIntersecting(); meter.MeterProgress(); System.Windows.Forms.Application.DoEvents(); return result; }).ToList(); meter.Stop(); if (results.Count() > 0) { Interaction.WriteLine("{0} detected.", results.Count()); Interaction.ZoomHighlightView(results); } else { Interaction.WriteLine("0 detected."); } }
41. Example
Project: FileHelpers
Source File: frmTimingAdvanced.cs
private void AdvanceProgress() { pb.Position++; pb.Text = "Test " + pb.Position.ToString() + " de " + pb.PositionMax.ToString(); Application.DoEvents(); }
42. Example
Project: MassEffectModder
Source File: Installer.cs
public void buttonsDefault(int gameId) { if (gameId != 3) { checkBoxPreEnablePack.Visible = false; labelME3DLCPack.Visible = false; checkBoxPackDLC.Visible = false; labelStatusPackDLC.Visible = false; labelMERepackZlib.Visible = false; checkBoxRepackZlib.Visible = false; labelStatusRepackZlib.Visible = false; buttonUnpackDLC.Visible = false; } if (gameId == 3) { checkBoxPreEnableRepack.Visible = false; labelMERepackZlib.Visible = false; labelME3DLCPack.Visible = false; checkBoxRepackZlib.Visible = false; labelStatusRepackZlib.Visible = false; labelME3DLCPack.Visible = false; checkBoxPackDLC.Visible = false; labelStatusPackDLC.Visible = false; } Application.DoEvents(); }
43. Example
Project: MassEffectModder
Source File: Installer.cs
public void clearPreCheckStatus() { labelPreMods.Text = ""; labelPreGamePath.Text = ""; labelPrePath.Text = ""; labelPreAccess.Text = ""; labelPreSpace.Text = ""; labelPreVanilla.Text = ""; labelStatusRepackZlib.Text = ""; labelStatusPackDLC.Text = ""; checkBoxPreMods.Checked = false; checkBoxPrePath.Checked = false; checkBoxPreAccess.Checked = false; checkBoxPreSpace.Checked = false; checkBoxPreVanilla.Checked = false; Application.DoEvents(); }
44. Example
Project: MassEffectModder
Source File: Installer.cs
private void buttonsEnable(bool enabled) { buttonExit.Enabled = enabled; buttonNormal.Enabled = enabled; buttonPreChangePath.Enabled = enabled; checkBoxPreEnableRepack.Enabled = enabled; checkBoxPreEnablePack.Enabled = enabled; if (updateMode) { checkBoxOptionVanilla.Enabled = false; checkBoxOptionSkipScan.Enabled = false; buttonUnpackDLC.Enabled = false; } else { checkBoxOptionVanilla.Enabled = enabled; checkBoxOptionSkipScan.Enabled = enabled; buttonUnpackDLC.Enabled = enabled; } checkBoxOptionFaster.Enabled = enabled; Application.DoEvents(); }
45. Example
Project: MassEffectModder
Source File: Installer.cs
public void updateLabelPreVanilla(string text) { labelPreVanilla.Text = text; Application.DoEvents(); }
46. Example
Project: MassEffectModder
Source File: Installer.cs
public void updateStatusPrepare(string text) { labelPreVanilla.Text = text; Application.DoEvents(); }
47. Example
Project: MassEffectModder
Source File: Installer.cs
public void updateStatusScan(string text) { labelStatusScan.Text = text; Application.DoEvents(); }
48. Example
Project: MassEffectModder
Source File: Installer.cs
public void updateStatusMipMaps(string text) { labelStatusMipMaps.Text = text; Application.DoEvents(); }
49. Example
Project: MassEffectModder
Source File: Installer.cs
public void updateStatusTextures(string text) { labelStatusTextures.Text = text; Application.DoEvents(); }
50. Example
Project: MassEffectModder
Source File: Installer.cs
public void updateStatusStore(string text) { labelStatusStore.Text = text; Application.DoEvents(); }