1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
//! # `DoEvents` Function
//!
//! Yields execution so that the operating system can process other events and messages.
//!
//! ## Syntax
//!
//! ```vb
//! DoEvents()
//! ```
//!
//! ## Parameters
//!
//! None.
//!
//! ## Return Value
//!
//! Returns an `Integer` representing the number of open forms in stand-alone versions of
//! Visual Basic. Returns 0 in all other applications.
//!
//! ## Remarks
//!
//! The `DoEvents` function temporarily yields execution to the operating system, allowing
//! it to process other events such as user input, timers, and system messages. This is
//! essential for keeping an application responsive during long-running operations.
//!
//! **Important Characteristics:**
//!
//! - Yields control to the operating system
//! - Allows message queue processing
//! - Prevents UI from appearing frozen during long operations
//! - Can cause reentrancy issues if not used carefully
//! - Slows down operations slightly due to context switching
//! - Returns number of open forms (VB6 stand-alone only)
//! - In most contexts, return value is ignored
//! - Does not create a new thread or async operation
//! - Processes Windows messages in the queue
//! - Can trigger event handlers and user interactions
//!
//! ## When to Use `DoEvents`
//!
//! - Long-running loops that process data
//! - File operations on large files
//! - Network operations that may take time
//! - Batch processing operations
//! - Any operation that could make UI unresponsive
//!
//! ## When NOT to Use `DoEvents`
//!
//! - In event handlers that could be re-entered
//! - When reentrancy could cause data corruption
//! - In critical sections or transaction code
//! - When better alternatives exist (timers, threading)
//!
//! ## Examples
//!
//! ### Basic Usage
//!
//! ```vb
//! ' Process large dataset while keeping UI responsive
//! Dim i As Long
//! For i = 1 To 100000
//! ProcessRecord i
//!
//! ' Yield every 100 iterations
//! If i Mod 100 = 0 Then
//! DoEvents
//! End If
//! Next i
//!
//! ' Simple DoEvents call
//! DoEvents
//!
//! ' Check return value (rarely used)
//! Dim formCount As Integer
//! formCount = DoEvents()
//! ```
//!
//! ### Progress Bar Update
//!
//! ```vb
//! Sub ProcessWithProgress()
//! Dim i As Long
//! Dim total As Long
//!
//! total = 10000
//! ProgressBar1.Min = 0
//! ProgressBar1.Max = total
//!
//! For i = 1 To total
//! ProcessItem i
//!
//! ' Update progress bar
//! ProgressBar1.Value = i
//! lblStatus.Caption = "Processing " & i & " of " & total
//!
//! ' Allow UI to refresh
//! DoEvents
//! Next i
//!
//! MsgBox "Processing complete!"
//! End Sub
//! ```
//!
//! ### File Processing
//!
//! ```vb
//! Sub ProcessLargeFile(filePath As String)
//! Dim fileNum As Integer
//! Dim line As String
//! Dim lineCount As Long
//!
//! fileNum = FreeFile
//! Open filePath For Input As #fileNum
//!
//! lineCount = 0
//! Do Until EOF(fileNum)
//! Line Input #fileNum, line
//! ProcessLine line
//! lineCount = lineCount + 1
//!
//! ' Yield every 100 lines
//! If lineCount Mod 100 = 0 Then
//! DoEvents
//! End If
//! Loop
//!
//! Close #fileNum
//! End Sub
//! ```
//!
//! ## Common Patterns
//!
//! ### Cancellable Long Operation
//!
//! ```vb
//! Private cancelOperation As Boolean
//!
//! Sub PerformCancellableOperation()
//! Dim i As Long
//! cancelOperation = False
//! cmdCancel.Enabled = True
//!
//! For i = 1 To 100000
//! If cancelOperation Then
//! MsgBox "Operation cancelled"
//! Exit For
//! End If
//!
//! ProcessItem i
//!
//! If i Mod 100 = 0 Then
//! DoEvents ' Allows cancel button to be clicked
//! End If
//! Next i
//!
//! cmdCancel.Enabled = False
//! End Sub
//!
//! Private Sub cmdCancel_Click()
//! cancelOperation = True
//! End Sub
//! ```
//!
//! ### Batch Import with Status
//!
//! ```vb
//! Sub ImportRecords(records As Variant)
//! Dim i As Long
//! Dim startTime As Double
//!
//! startTime = Timer
//!
//! For i = LBound(records) To UBound(records)
//! ImportRecord records(i)
//!
//! ' Update status every 50 records
//! If i Mod 50 = 0 Then
//! lblStatus.Caption = "Imported " & i & " records..."
//! DoEvents
//! End If
//! Next i
//!
//! lblStatus.Caption = "Import complete: " & UBound(records) - LBound(records) + 1 & _
//! " records in " & Format(Timer - startTime, "0.00") & " seconds"
//! End Sub
//! ```
//!
//! ### Prevent UI Freeze During Calculation
//!
//! ```vb
//! Function CalculateComplexResult(data As Variant) As Double
//! Dim i As Long
//! Dim result As Double
//! Dim iterations As Long
//!
//! iterations = 0
//! result = 0
//!
//! For i = LBound(data) To UBound(data)
//! result = result + PerformComplexCalculation(data(i))
//! iterations = iterations + 1
//!
//! ' Yield periodically
//! If iterations Mod 500 = 0 Then
//! DoEvents
//! End If
//! Next i
//!
//! CalculateComplexResult = result
//! End Function
//! ```
//!
//! ### Database Batch Update
//!
//! ```vb
//! Sub UpdateRecordsBatch(rs As ADODB.Recordset)
//! Dim count As Long
//!
//! count = 0
//! Do Until rs.EOF
//! rs("Status") = "Processed"
//! rs("ProcessDate") = Date
//! rs.Update
//!
//! count = count + 1
//! If count Mod 25 = 0 Then
//! lblProgress.Caption = count & " records updated"
//! DoEvents
//! End If
//!
//! rs.MoveNext
//! Loop
//! End Sub
//! ```
//!
//! ### Search Operation with Live Results
//!
//! ```vb
//! Sub SearchFiles(rootPath As String, searchTerm As String)
//! Dim fileName As String
//! Dim matchCount As Long
//!
//! matchCount = 0
//! lstResults.Clear
//!
//! fileName = Dir(rootPath & "\*.*")
//! Do While fileName <> ""
//! If InStr(1, fileName, searchTerm, vbTextCompare) > 0 Then
//! lstResults.AddItem fileName
//! matchCount = matchCount + 1
//! End If
//!
//! fileName = Dir
//! DoEvents ' Keep UI responsive, allow viewing results
//! Loop
//!
//! lblStatus.Caption = matchCount & " matches found"
//! End Sub
//! ```
//!
//! ### Report Generation
//!
//! ```vb
//! Sub GenerateReport(data As Collection)
//! Dim item As Variant
//! Dim lineNum As Long
//!
//! lineNum = 0
//!
//! For Each item In data
//! WriteReportLine item
//! lineNum = lineNum + 1
//!
//! If lineNum Mod 20 = 0 Then
//! lblProgress.Caption = "Generated " & lineNum & " lines..."
//! DoEvents
//! End If
//! Next item
//! End Sub
//! ```
//!
//! ### Animation or Visual Feedback
//!
//! ```vb
//! Sub ShowProcessingAnimation()
//! Dim i As Integer
//!
//! For i = 1 To 100
//! ' Update visual indicator
//! shpIndicator.Left = i * 50
//! DoEvents
//!
//! ' Simulate work
//! Sleep 10
//! Next i
//! End Sub
//! ```
//!
//! ### Multi-Step Process
//!
//! ```vb
//! Sub MultiStepProcess()
//! lblStatus.Caption = "Step 1: Loading data..."
//! DoEvents
//! LoadData
//!
//! lblStatus.Caption = "Step 2: Processing data..."
//! DoEvents
//! ProcessData
//!
//! lblStatus.Caption = "Step 3: Saving results..."
//! DoEvents
//! SaveResults
//!
//! lblStatus.Caption = "Complete!"
//! DoEvents
//! End Sub
//! ```
//!
//! ## Advanced Usage
//!
//! ### Prevent Reentrancy
//!
//! ```vb
//! Private isProcessing As Boolean
//!
//! Sub SafeProcessWithDoEvents()
//! ' Prevent re-entry
//! If isProcessing Then
//! MsgBox "Already processing"
//! Exit Sub
//! End If
//!
//! isProcessing = True
//!
//! Dim i As Long
//! For i = 1 To 10000
//! ProcessItem i
//!
//! If i Mod 100 = 0 Then
//! DoEvents
//! End If
//! Next i
//!
//! isProcessing = False
//! End Sub
//! ```
//!
//! ### Throttled `DoEvents`
//!
//! ```vb
//! Sub ProcessWithThrottledDoEvents()
//! Dim i As Long
//! Dim lastDoEvents As Double
//! Dim doEventsInterval As Double
//!
//! doEventsInterval = 0.1 ' 100ms
//! lastDoEvents = Timer
//!
//! For i = 1 To 100000
//! ProcessItem i
//!
//! ' DoEvents based on time, not iteration count
//! If Timer - lastDoEvents > doEventsInterval Then
//! DoEvents
//! lastDoEvents = Timer
//! End If
//! Next i
//! End Sub
//! ```
//!
//! ### Disable Controls During Processing
//!
//! ```vb
//! Sub ProcessWithDisabledControls()
//! ' Disable controls to prevent reentrancy
//! DisableControls
//!
//! Dim i As Long
//! For i = 1 To 10000
//! ProcessItem i
//!
//! If i Mod 100 = 0 Then
//! UpdateProgress i
//! DoEvents ' Safe because controls are disabled
//! End If
//! Next i
//!
//! EnableControls
//! End Sub
//!
//! Sub DisableControls()
//! Dim ctrl As Control
//! For Each ctrl In Me.Controls
//! If TypeOf ctrl Is CommandButton Then
//! ctrl.Enabled = False
//! End If
//! Next ctrl
//! End Sub
//!
//! Sub EnableControls()
//! Dim ctrl As Control
//! For Each ctrl In Me.Controls
//! If TypeOf ctrl Is CommandButton Then
//! ctrl.Enabled = True
//! End If
//! Next ctrl
//! End Sub
//! ```
//!
//! ### Background Processing Simulation
//!
//! ```vb
//! ' Simulates background processing using DoEvents
//! Private processingComplete As Boolean
//!
//! Sub StartBackgroundTask()
//! processingComplete = False
//!
//! ' Start the "background" task
//! ProcessInBackground
//!
//! ' Show modal dialog that waits
//! Do Until processingComplete
//! DoEvents
//! Sleep 10 ' Small delay to reduce CPU usage
//! Loop
//!
//! MsgBox "Background task complete"
//! End Sub
//!
//! Sub ProcessInBackground()
//! Dim i As Long
//! For i = 1 To 10000
//! ProcessItem i
//!
//! If i Mod 100 = 0 Then
//! DoEvents
//! End If
//! Next i
//!
//! processingComplete = True
//! End Sub
//! ```
//!
//! ### Smart `DoEvents` with CPU Management
//!
//! ```vb
//! Sub ProcessWithCPUManagement()
//! Dim i As Long
//! Dim processingTime As Double
//! Dim doEventsTime As Double
//!
//! For i = 1 To 100000
//! processingTime = Timer
//! ProcessItem i
//! processingTime = Timer - processingTime
//!
//! ' DoEvents if processing takes significant time
//! If processingTime > 0.05 Then ' More than 50ms
//! doEventsTime = Timer
//! DoEvents
//! doEventsTime = Timer - doEventsTime
//!
//! ' Adjust strategy if DoEvents takes too long
//! If doEventsTime > processingTime * 0.1 Then
//! ' DoEvents overhead is too high, reduce frequency
//! ' (implementation-specific logic here)
//! End If
//! End If
//! Next i
//! End Sub
//! ```
//!
//! ### Export with User Interaction
//!
//! ```vb
//! Sub ExportDataWithOptions()
//! Dim i As Long
//! Dim exportCount As Long
//!
//! exportCount = 0
//!
//! For i = 1 To RecordCount
//! If chkIncludeDeleted.Value = vbChecked Or Not IsDeleted(i) Then
//! ExportRecord i
//! exportCount = exportCount + 1
//! End If
//!
//! ' Update UI and allow user to change options
//! If i Mod 50 = 0 Then
//! lblProgress.Caption = exportCount & " records exported"
//! DoEvents
//! ' User can check/uncheck options, affecting subsequent exports
//! End If
//! Next i
//! End Sub
//! ```
//!
//! ## Error Handling
//!
//! ```vb
//! Sub ProcessWithErrorHandling()
//! On Error GoTo ErrorHandler
//!
//! Dim i As Long
//! For i = 1 To 10000
//! ProcessItem i
//!
//! If i Mod 100 = 0 Then
//! DoEvents
//! End If
//! Next i
//!
//! Exit Sub
//!
//! ErrorHandler:
//! ' DoEvents can trigger errors if event handlers fail
//! MsgBox "Error during processing: " & Err.Description
//! Resume Next
//! End Sub
//! ```
//!
//! ### Common Errors
//!
//! - **Error 11** (Division by zero): Can occur if `DoEvents` allows user to clear data
//! - **Error 91** (Object variable not set): If `DoEvents` allows object to be destroyed
//! - **Reentrancy errors**: If `DoEvents` allows same code to be called recursively
//!
//! ## Performance Considerations
//!
//! - `DoEvents` has overhead (context switching, message processing)
//! - Call too frequently: significant performance impact
//! - Call too infrequently: UI appears frozen
//! - Typical guideline: every 50-100 iterations or every 100ms
//! - For very fast loops, use time-based checking instead of iteration-based
//! - Consider alternatives for truly asynchronous operations
//! - `Sleep()` between `DoEvents` can reduce CPU usage in wait loops
//!
//! ## Best Practices
//!
//! ### Call Periodically, Not Every Iteration
//!
//! ```vb
//! ' Good - DoEvents every 100 iterations
//! For i = 1 To 100000
//! ProcessItem i
//! If i Mod 100 = 0 Then DoEvents
//! Next i
//!
//! ' Bad - DoEvents every iteration (slow)
//! For i = 1 To 100000
//! ProcessItem i
//! DoEvents ' Too frequent!
//! Next i
//! ```
//!
//! ### Protect Against Reentrancy
//!
//! ```vb
//! ' Good - Use flag to prevent reentrancy
//! Private isProcessing As Boolean
//!
//! Sub Process()
//! If isProcessing Then Exit Sub
//! isProcessing = True
//! ' ... processing with DoEvents ...
//! isProcessing = False
//! End Sub
//!
//! ' Bad - No protection
//! Sub Process()
//! ' ... processing with DoEvents ...
//! ' Can be called again through DoEvents
//! End Sub
//! ```
//!
//! ### Disable User Input When Needed
//!
//! ```vb
//! ' Good - Disable controls that could cause problems
//! cmdProcess.Enabled = False
//! For i = 1 To 10000
//! ProcessItem i
//! If i Mod 100 = 0 Then DoEvents
//! Next i
//! cmdProcess.Enabled = True
//! ```
//!
//! ### Consider Alternatives
//!
//! ```vb
//! ' For very long operations, consider:
//! ' 1. Timer control for asynchronous processing
//! ' 2. Threading (in modern applications)
//! ' 3. Breaking into smaller chunks with callbacks
//! ' 4. Progress forms with asynchronous updates
//! ```
//!
//! ## Comparison with Other Approaches
//!
//! ### `DoEvents` vs Timer Control
//!
//! ```vb
//! ' DoEvents - Synchronous, blocks until complete
//! For i = 1 To 10000
//! ProcessItem i
//! If i Mod 100 = 0 Then DoEvents
//! Next i
//!
//! ' Timer - Asynchronous, processes in chunks
//! Private currentIndex As Long
//!
//! Private Sub Timer1_Timer()
//! Dim i As Long
//! For i = currentIndex To currentIndex + 99
//! If i > 10000 Then
//! Timer1.Enabled = False
//! Exit Sub
//! End If
//! ProcessItem i
//! Next i
//! currentIndex = i
//! End Sub
//! ```
//!
//! ### `DoEvents` vs `Application.Wait` (Excel VBA)
//!
//! ```vb
//! ' DoEvents - Yields immediately
//! DoEvents
//!
//! ' Application.Wait - Yields for specific duration
//! Application.Wait Now + TimeValue("00:00:01")
//! ```
//!
//! ## Limitations
//!
//! - Does not create true multithreading
//! - Can cause reentrancy issues
//! - Performance overhead from context switching
//! - Return value rarely useful in modern applications
//! - No control over which events are processed
//! - Can make debugging more difficult
//! - Not available in all VBA hosts (e.g., some Office apps)
//! - Cannot cancel or prioritize specific events
//!
//! ## Related Functions
//!
//! - `Sleep`: Pauses execution for specified milliseconds (Windows API)
//! - `Timer`: Returns seconds since midnight (for timing operations)
//! - `Now`: Returns current date and time
//! - `Wait`: Application-specific wait method (Excel VBA)
//! - **Timer Control**: Asynchronous event-based processing
//! - **Threading APIs**: True multithreading (advanced)
use cratestate;
use crateVBVariant;
use VBResult;
/// Implement VB6's `DoEvents` function.
///
/// Yields execution to the OS and returns the number of open forms (always 0).