-
Notifications
You must be signed in to change notification settings - Fork 951
/
Application.cs
1272 lines (1128 loc) · 45.3 KB
/
Application.cs
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
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.ComponentModel;
using System.Drawing;
using System.Globalization;
using System.Reflection;
using System.Text;
using System.Windows.Forms.VisualStyles;
using Microsoft.Office;
using Microsoft.Win32;
using Directory = System.IO.Directory;
namespace System.Windows.Forms;
/// <summary>
/// Provides <see langword="static"/> methods and properties to manage an application, such as methods to run and quit an application,
/// to process Windows messages, and properties to get information about an application.
/// This class cannot be inherited.
/// </summary>
public sealed partial class Application
{
/// <summary>
/// Hash table for our event list
/// </summary>
private static EventHandlerList? s_eventHandlers;
private static Font? s_defaultFont;
private static Font? s_defaultFontScaled;
private static string? s_startupPath;
private static string? s_executablePath;
private static object? s_appFileVersion;
private static Type? s_mainType;
private static string? s_companyName;
private static string? s_productName;
private static string? s_productVersion;
private static string? s_safeTopLevelCaptionSuffix;
private static bool s_comCtlSupportsVisualStylesInitialized;
private static bool s_comCtlSupportsVisualStyles;
private static FormCollection? s_forms;
private static readonly object s_internalSyncObject = new();
private static bool s_useWaitCursor;
/// <summary>
/// Events the user can hook into
/// </summary>
private static readonly object s_eventApplicationExit = new();
private static readonly object s_eventThreadExit = new();
// Defines a new callback delegate type
[EditorBrowsable(EditorBrowsableState.Advanced)]
public delegate bool MessageLoopCallback();
// Used to avoid recursive exit
private static bool s_exiting;
private static bool s_parkingWindowCreated;
/// <summary>
/// This class is static, there is no need to ever create it.
/// </summary>
private Application()
{
}
/// <summary>
/// Determines if the caller should be allowed to quit the application. This will return false,
/// for example, if being called from a windows forms control being hosted within a web browser. The
/// windows forms control should not attempt to quit the application.
/// </summary>
public static bool AllowQuit => ThreadContext.GetAllowQuit();
/// <summary>
/// Typically, you shouldn't need to use this directly - use RenderWithVisualStyles instead.
/// </summary>
internal static bool ComCtlSupportsVisualStyles
{
get
{
if (!s_comCtlSupportsVisualStylesInitialized)
{
s_comCtlSupportsVisualStyles = InitializeComCtlSupportsVisualStyles();
s_comCtlSupportsVisualStylesInitialized = true;
}
return s_comCtlSupportsVisualStyles;
}
}
private static unsafe bool InitializeComCtlSupportsVisualStyles()
{
if (UseVisualStyles)
{
// At this point, we may not have loaded ComCtl6 yet, but it will eventually be loaded,
// so we return true here. This works because UseVisualStyles, once set, cannot be
// turned off.
return true;
}
// To see if we are comctl6, we look for a function that is exposed only from comctl6
// we do not call DllGetVersion or any direct p/invoke, because the binding will be
// cached.
//
// GetModuleHandle returns a handle to a mapped module without incrementing its
// reference count.
var hModule = PInvoke.GetModuleHandle(Libraries.Comctl32);
fixed (byte* ptr = "ImageList_WriteEx\0"u8)
{
if (!hModule.IsNull)
{
return PInvoke.GetProcAddress(hModule, (PCSTR)ptr) != 0;
}
}
// Load comctl since GetModuleHandle failed to find it
nint ninthModule = PInvoke.LoadComctl32(StartupPath);
if (ninthModule == 0)
{
return false;
}
fixed (byte* ptr = "ImageList_WriteEx\0"u8)
{
return PInvoke.GetProcAddress(hModule, (PCSTR)ptr) != 0;
}
}
/// <summary>
/// Gets the registry key for the application data that is shared among all users.
/// </summary>
public static RegistryKey CommonAppDataRegistry
=> Registry.LocalMachine.CreateSubKey(CommonAppDataRegistryKeyName);
internal static string CommonAppDataRegistryKeyName
=> $"Software\\{CompanyName}\\{ProductName}\\{ProductVersion}";
/// <summary>
/// Gets the path for the application data that is shared among all users.
/// </summary>
/// <remarks>
/// <para>
/// Don't obsolete these. GetDataPath isn't on SystemInformation, and it provides
/// the Windows logo required adornments to the directory (Company\Product\Version).
/// </para>
/// </remarks>
public static string CommonAppDataPath
=> GetDataPath(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData));
/// <summary>
/// Gets the company name associated with the application.
/// </summary>
public static string? CompanyName
{
get
{
lock (s_internalSyncObject)
{
if (s_companyName is null)
{
// Custom attribute
Assembly? entryAssembly = Assembly.GetEntryAssembly();
if (entryAssembly is not null)
{
object[] attrs = entryAssembly.GetCustomAttributes(typeof(AssemblyCompanyAttribute), false);
if (attrs is not null && attrs.Length > 0)
{
s_companyName = ((AssemblyCompanyAttribute)attrs[0]).Company;
}
}
// Win32 version
if (s_companyName is null || s_companyName.Length == 0)
{
s_companyName = GetAppFileVersionInfo().CompanyName;
if (s_companyName is not null)
{
s_companyName = s_companyName.Trim();
}
}
// fake it with a namespace
// won't work with MC++ see GetAppMainType.
if (s_companyName is null || s_companyName.Length == 0)
{
Type? type = GetAppMainType();
if (type is not null)
{
string? ns = type.Namespace;
if (!string.IsNullOrEmpty(ns))
{
int firstDot = ns.IndexOf('.');
if (firstDot != -1)
{
s_companyName = ns[..firstDot];
}
else
{
s_companyName = ns;
}
}
else
{
// last ditch... no namespace, use product name...
s_companyName = ProductName;
}
}
}
}
}
return s_companyName;
}
}
/// <summary>
/// Gets or sets the locale information for the current thread.
/// </summary>
public static CultureInfo CurrentCulture
{
get => Thread.CurrentThread.CurrentCulture;
set => Thread.CurrentThread.CurrentCulture = value;
}
/// <summary>
/// Gets or sets the current input language for the current thread.
/// </summary>
public static InputLanguage CurrentInputLanguage
{
get => InputLanguage.CurrentInputLanguage;
set => InputLanguage.CurrentInputLanguage = value;
}
internal static bool CustomThreadExceptionHandlerAttached
=> ThreadContext.FromCurrent().CustomThreadExceptionHandlerAttached;
internal static Font? DefaultFont => s_defaultFontScaled ?? s_defaultFont;
/// <summary>
/// Gets the path for the executable file that started the application.
/// </summary>
public static string ExecutablePath =>
s_executablePath ??= PInvoke.GetModuleFileNameLongPath(HINSTANCE.Null);
/// <summary>
/// Gets the current <see cref="HighDpiMode"/> mode for the process.
/// </summary>
/// <value>One of the enumeration values that indicates the high DPI mode.</value>
public static HighDpiMode HighDpiMode => ScaleHelper.GetThreadHighDpiMode();
/// <summary>
/// Gets the path for the application data specific to a local, non-roaming user.
/// </summary>
/// <remarks>
/// <para>Don't obsolete these. GetDataPath isn't on SystemInformation, and it provides
/// the Windows logo required adornments to the directory (Company\Product\Version)</para>
/// </remarks>
public static string LocalUserAppDataPath
=> GetDataPath(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData));
/// <summary>
/// Determines if a message loop exists on this thread.
/// </summary>
public static bool MessageLoop
=> ThreadContext.FromCurrent().GetMessageLoop();
/// <summary>
/// Gets the forms collection associated with this application.
/// </summary>
public static FormCollection OpenForms => s_forms ??= [];
/// <summary>
/// Gets
/// the product name associated with this application.
/// </summary>
public static string? ProductName
{
get
{
lock (s_internalSyncObject)
{
if (s_productName is null)
{
// Custom attribute
Assembly? entryAssembly = Assembly.GetEntryAssembly();
if (entryAssembly is not null)
{
object[] attrs = entryAssembly.GetCustomAttributes(typeof(AssemblyProductAttribute), false);
if (attrs is not null && attrs.Length > 0)
{
s_productName = ((AssemblyProductAttribute)attrs[0]).Product;
}
}
// Win32 version info
if (s_productName is null || s_productName.Length == 0)
{
s_productName = GetAppFileVersionInfo().ProductName;
if (s_productName is not null)
{
s_productName = s_productName.Trim();
}
}
// fake it with namespace
// won't work with MC++ see GetAppMainType.
if (s_productName is null || s_productName.Length == 0)
{
Type? type = GetAppMainType();
if (type is not null)
{
string? ns = type.Namespace;
if (!string.IsNullOrEmpty(ns))
{
int lastDot = ns.LastIndexOf('.');
if (lastDot != -1 && lastDot < ns.Length - 1)
{
s_productName = ns[(lastDot + 1)..];
}
else
{
s_productName = ns;
}
}
else
{
// last ditch... use the main type
s_productName = type.Name;
}
}
}
}
}
return s_productName;
}
}
/// <summary>
/// Gets the product version associated with this application.
/// </summary>
public static string ProductVersion
{
get
{
lock (s_internalSyncObject)
{
if (s_productVersion is null)
{
// Custom attribute
Assembly? entryAssembly = Assembly.GetEntryAssembly();
if (entryAssembly is not null)
{
object[] attrs = entryAssembly.GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), false);
if (attrs is not null && attrs.Length > 0)
{
s_productVersion = ((AssemblyInformationalVersionAttribute)attrs[0]).InformationalVersion;
}
}
// Win32 version info
if (s_productVersion is null || s_productVersion.Length == 0)
{
s_productVersion = GetAppFileVersionInfo().ProductVersion;
if (s_productVersion is not null)
{
s_productVersion = s_productVersion.Trim();
}
}
// fake it
if (s_productVersion is null || s_productVersion.Length == 0)
{
s_productVersion = "1.0.0.0";
}
}
}
return s_productVersion;
}
}
// Allows the hosting environment to register a callback
[EditorBrowsable(EditorBrowsableState.Advanced)]
public static void RegisterMessageLoop(MessageLoopCallback? callback)
=> ThreadContext.FromCurrent().RegisterMessageLoop(callback);
/// <summary>
/// Magic property that answers a simple question - are my controls currently going to render with
/// visual styles? If you are doing visual styles rendering, use this to be consistent with the rest
/// of the controls in your app.
/// </summary>
public static bool RenderWithVisualStyles
=> ComCtlSupportsVisualStyles && VisualStyleRenderer.IsSupported;
/// <summary>
/// Gets or sets the format string to apply to top level window captions
/// when they are displayed with a warning banner.
/// </summary>
public static string SafeTopLevelCaptionFormat
{
get
{
s_safeTopLevelCaptionSuffix ??= SR.SafeTopLevelCaptionFormat; // 0 - original, 1 - zone, 2 - site
return s_safeTopLevelCaptionSuffix;
}
set
{
value ??= string.Empty;
s_safeTopLevelCaptionSuffix = value;
}
}
/// <summary>
/// Gets the path for the executable file that started the application.
/// </summary>
public static string StartupPath
{
get
{
// StringBuilder sb = UnsafeNativeMethods.GetModuleFileNameLongPath(NativeMethods.NullHandleRef);
// startupPath = Path.GetDirectoryName(sb.ToString());
s_startupPath ??= AppContext.BaseDirectory;
return s_startupPath;
}
}
// Allows the hosting environment to unregister a callback
[EditorBrowsable(EditorBrowsableState.Advanced)]
public static void UnregisterMessageLoop()
=> ThreadContext.FromCurrent().RegisterMessageLoop(null);
/// <summary>
/// Gets or sets whether the wait cursor is used for all open forms of the application.
/// </summary>
public static bool UseWaitCursor
{
get => s_useWaitCursor;
set
{
lock (FormCollection.CollectionSyncRoot)
{
s_useWaitCursor = value;
// Set the WaitCursor of all forms.
foreach (Form f in OpenForms)
{
f.UseWaitCursor = s_useWaitCursor;
}
}
}
}
/// <summary>
/// Gets the path for the application data specific to the roaming user.
/// </summary>
/// <remarks>
/// <para>Don't obsolete these. GetDataPath isn't on SystemInformation, and it provides
/// the Windows logo required adornments to the directory (Company\Product\Version)</para>
/// </remarks>
public static string UserAppDataPath
=> GetDataPath(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
/// <summary>
/// Gets the registry key of
/// the application data specific to the roaming user.
/// </summary>
public static RegistryKey UserAppDataRegistry
=> Registry.CurrentUser.CreateSubKey($"Software\\{CompanyName}\\{ProductName}\\{ProductVersion}");
/// <summary>
/// Gets a value that indicates whether visual styles are enabled for the application.
/// </summary>
/// <value><see langword="true" /> if visual styles are enabled; otherwise, <see langword="false" />.</value>
/// <remarks>
/// <para>
/// The visual styles can be enabled by calling <see cref="EnableVisualStyles"/>.
/// The visual styles will not be enabled if the OS does not support them, or theming is disabled at the OS level.
/// </para>
/// </remarks>
public static bool UseVisualStyles { get; private set; }
/// <remarks>
/// <para>
/// Don't never ever change this name, since the window class and partner teams
/// dependent on this. Changing this will introduce breaking changes.
/// If there is some reason need to change this, notify any partner teams affected.
/// </para>
/// </remarks>
internal static string WindowsFormsVersion => "WindowsForms10";
internal static string WindowMessagesVersion => "WindowsForms12";
/// <summary>
/// Use this property to determine how visual styles will be applied to this application.
/// This property is meaningful only if visual styles are supported on the current
/// platform (VisualStyleInformation.SupportedByOS is true).
///
/// This property can be set only to one of the S.W.F.VisualStyles.VisualStyleState enum values.
/// </summary>
public static VisualStyleState VisualStyleState
{
get
{
if (!VisualStyleInformation.IsSupportedByOS)
{
return VisualStyleState.NoneEnabled;
}
VisualStyleState vState = (VisualStyleState)PInvoke.GetThemeAppProperties();
return vState;
}
set
{
if (VisualStyleInformation.IsSupportedByOS)
{
PInvoke.SetThemeAppProperties((SET_THEME_APP_PROPERTIES_FLAGS)value);
// 248887 we need to send a WM_THEMECHANGED to the top level windows of this application.
// We do it this way to ensure that we get all top level windows -- whether we created them or not.
PInvoke.EnumWindows(SendThemeChanged);
}
}
}
/// <summary>
/// This helper broadcasts out a WM_THEMECHANGED to appropriate top level windows of this app.
/// </summary>
private static unsafe BOOL SendThemeChanged(HWND hwnd)
{
uint processId;
PInvoke.GetWindowThreadProcessId(hwnd, &processId);
if (processId == PInvoke.GetCurrentProcessId() && PInvoke.IsWindowVisible(hwnd))
{
SendThemeChangedRecursive(hwnd);
PInvoke.RedrawWindow(
hwnd,
lprcUpdate: (RECT*)null,
HRGN.Null,
REDRAW_WINDOW_FLAGS.RDW_INVALIDATE
| REDRAW_WINDOW_FLAGS.RDW_FRAME
| REDRAW_WINDOW_FLAGS.RDW_ERASE
| REDRAW_WINDOW_FLAGS.RDW_ALLCHILDREN);
}
return true;
}
/// <summary>
/// This helper broadcasts out a WM_THEMECHANGED this window and all children.
/// It is assumed at this point that the handle belongs to the current process
/// and has a visible top level window.
/// </summary>
private static BOOL SendThemeChangedRecursive(HWND handle)
{
// First send to all children.
PInvoke.EnumChildWindows(handle, SendThemeChangedRecursive);
// Then send to ourself.
PInvoke.SendMessage(handle, PInvoke.WM_THEMECHANGED);
return true;
}
/// <summary>
/// Occurs when the application is about to shut down.
/// </summary>
public static event EventHandler? ApplicationExit
{
add => AddEventHandler(s_eventApplicationExit, value);
remove => RemoveEventHandler(s_eventApplicationExit, value);
}
private static void AddEventHandler(object key, Delegate? value)
{
lock (s_internalSyncObject)
{
s_eventHandlers ??= new EventHandlerList();
s_eventHandlers.AddHandler(key, value);
}
}
private static void RemoveEventHandler(object key, Delegate? value)
{
lock (s_internalSyncObject)
{
if (s_eventHandlers is null)
{
return;
}
s_eventHandlers.RemoveHandler(key, value);
}
}
/// <summary>
/// Adds a message filter to monitor Windows messages as they are routed to their
/// destinations.
/// </summary>
public static void AddMessageFilter(IMessageFilter? value)
=> ThreadContext.FromCurrent().AddMessageFilter(value);
/// <summary>
/// Processes all message filters for given message
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public static bool FilterMessage(ref Message message)
{
// Create copy of MSG structure
MSG msg = message;
bool processed = ThreadContext.FromCurrent().ProcessFilters(ref msg, out bool modified);
if (modified)
{
message.HWnd = msg.hwnd;
message.MsgInternal = (MessageId)msg.message;
message.WParamInternal = msg.wParam;
message.LParamInternal = msg.lParam;
}
return processed;
}
/// <summary>
/// Occurs when the application has finished processing and is about to enter the
/// idle state.
/// </summary>
public static event EventHandler? Idle
{
add
{
ThreadContext current = ThreadContext.FromCurrent();
lock (current)
{
current._idleHandler += value;
current.EnsureReadyForIdle();
}
}
remove
{
ThreadContext current = ThreadContext.FromCurrent();
lock (current)
{
current._idleHandler -= value;
}
}
}
/// <summary>
/// Occurs when the application is about to enter a modal state
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public static event EventHandler? EnterThreadModal
{
add
{
ThreadContext current = ThreadContext.FromCurrent();
lock (current)
{
current._enterModalHandler += value;
}
}
remove
{
ThreadContext current = ThreadContext.FromCurrent();
lock (current)
{
current._enterModalHandler -= value;
}
}
}
/// <summary>
/// Occurs when the application is about to leave a modal state
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public static event EventHandler? LeaveThreadModal
{
add
{
ThreadContext current = ThreadContext.FromCurrent();
lock (current)
{
current._leaveModalHandler += value;
}
}
remove
{
ThreadContext current = ThreadContext.FromCurrent();
lock (current)
{
current._leaveModalHandler -= value;
}
}
}
/// <summary>
/// Occurs when an untrapped thread exception is thrown.
/// </summary>
public static event ThreadExceptionEventHandler? ThreadException
{
add
{
ThreadContext current = ThreadContext.FromCurrent();
lock (current)
{
current._threadExceptionHandler = value;
}
}
remove
{
ThreadContext current = ThreadContext.FromCurrent();
lock (current)
{
current._threadExceptionHandler -= value;
}
}
}
/// <summary>
/// Occurs when a thread is about to shut down. When the main thread for an
/// application is about to be shut down, this event will be raised first,
/// followed by an <see cref="ApplicationExit"/> event.
/// </summary>
public static event EventHandler? ThreadExit
{
add => AddEventHandler(s_eventThreadExit, value);
remove => RemoveEventHandler(s_eventThreadExit, value);
}
/// <summary>
/// Called immediately before we begin pumping messages for a modal message loop.
/// Does not actually start a message pump; that's the caller's responsibility.
/// </summary>
internal static void BeginModalMessageLoop()
=> ThreadContext.FromCurrent().BeginModalMessageLoop(null);
/// <summary>
/// Processes all Windows messages currently in the message queue.
/// </summary>
public static void DoEvents()
=> ThreadContext.FromCurrent().RunMessageLoop(msoloop.DoEvents, null);
internal static void DoEventsModal()
=> ThreadContext.FromCurrent().RunMessageLoop(msoloop.DoEventsModal, null);
/// <summary>
/// Enables visual styles for all subsequent <see cref="Run()"/> and <see cref="Control.CreateHandle"/> calls.
/// Uses the default theming manifest file shipped with the redist.
/// </summary>
[UnconditionalSuppressMessage("SingleFile", "IL3002", Justification = "Single-file case is handled")]
public static void EnableVisualStyles()
{
// Pull manifest from our resources
Module module = typeof(Application).Module;
var moduleHandle = PInvoke.GetModuleHandle(module.Name);
if (moduleHandle != 0)
{
// We have a native module, point to our native embedded manifest resource.
// CSC embeds DLL manifests as native resource ID 2
UseVisualStyles = ThemingScope.CreateActivationContext(moduleHandle, nativeResourceManifestID: 2);
}
else
{
// We couldn't grab the module handle, likely we're running from a single file package.
// Extract the manifest from managed resources.
using Stream? stream = module.Assembly.GetManifestResourceStream(
"System.Windows.Forms.XPThemes.manifest");
if (stream is not null)
{
UseVisualStyles = ThemingScope.CreateActivationContext(stream);
}
}
Debug.Assert(UseVisualStyles, "Enable Visual Styles failed");
s_comCtlSupportsVisualStylesInitialized = false;
}
/// <summary>
/// Called immediately after we stop pumping messages for a modal message loop.
/// Does not actually end the message pump itself.
/// </summary>
internal static void EndModalMessageLoop()
=> ThreadContext.FromCurrent().EndModalMessageLoop(null);
/// <summary>
/// Overload of <see cref="Exit(CancelEventArgs)"/> that does not care about e.Cancel.
/// </summary>
public static void Exit() => Exit(null);
/// <summary>
/// Informs all message pumps that they are to terminate and then closes all
/// application windows after the messages have been processed. e.Cancel indicates
/// whether any of the open forms canceled the exit call.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public static void Exit(CancelEventArgs? e)
{
lock (s_internalSyncObject)
{
if (s_exiting)
{
// Recursive call to Exit
if (e is not null)
{
e.Cancel = false;
}
return;
}
s_exiting = true;
try
{
// Raise the FormClosing and FormClosed events for each open form
if (s_forms?.Count > 0)
{
HashSet<Form> processedForms = new(s_forms.Count);
int version = s_forms.AddVersion;
// We need to iterate in backward order to not violate MDI closing events rules
for (int i = s_forms.Count - 1; i > -1; i--)
{
Form? form = s_forms[i];
if (form is null || processedForms.Contains(form))
{
continue;
}
processedForms.Add(form);
// Here user can remove existing forms or add new
if (form.RaiseFormClosingOnAppExit())
{
// A form refused to close
if (e is not null)
{
e.Cancel = true;
}
processedForms.Clear();
return;
}
if (version != s_forms.AddVersion) // A new form was added, we need to iterate again
{
version = s_forms.AddVersion;
i = s_forms.Count;
}
else
{
i = Math.Min(i, s_forms.Count); // Form can be removed from the collection, we need to check it
}
}
processedForms.Clear();
while (s_forms.Count > 0)
{
// We need to iterate in backward order to not violate MDI closing events rules
Form? form = s_forms[^1];
if (form is not null)
{
// OnFormClosed removes the form from the FormCollection
form.RaiseFormClosedOnAppExit();
}
else
{
s_forms.RemoveAt(s_forms.Count - 1);
}
}
}
ThreadContext.ExitApplication();
if (e is not null)
{
e.Cancel = false;
}
}
finally
{
s_exiting = false;
}
}
}
/// <summary>
/// Exits the message loop on the current thread and closes all windows on the thread.
/// </summary>
public static void ExitThread()
{
ThreadContext context = ThreadContext.FromCurrent();
if (context.ApplicationContext is not null)
{
context.ApplicationContext.ExitThread();
}
else
{
context.Dispose(true);
}
}
// When a Form receives a WM_ACTIVATE message, it calls this method so we can do the
// appropriate MsoComponentManager activation magic
internal static void FormActivated(bool modal, bool activated)
{
if (modal)
{
return;
}
ThreadContext.FromCurrent().FormActivated(activated);
}
/// <summary>
/// Retrieves the FileVersionInfo associated with the main module for
/// the application.
/// </summary>
[UnconditionalSuppressMessage("SingleFile", "IL3002", Justification = "Single-file case is handled")]
private static FileVersionInfo GetAppFileVersionInfo()
{
lock (s_internalSyncObject)
{
if (s_appFileVersion is null)
{
Type? type = GetAppMainType();
if (type is not null && type.Assembly.Location.Length > 0)
{
s_appFileVersion = FileVersionInfo.GetVersionInfo(type.Module.FullyQualifiedName);
}
else
{
s_appFileVersion = FileVersionInfo.GetVersionInfo(ExecutablePath);
}
}
}
return (FileVersionInfo)s_appFileVersion;
}
/// <summary>
/// Retrieves the Type that contains the "Main" method.
/// </summary>
private static Type? GetAppMainType()
{
lock (s_internalSyncObject)
{
if (s_mainType is null)
{
Assembly? exe = Assembly.GetEntryAssembly();
// Get Main type...This doesn't work in MC++ because Main is a global function and not
// a class static method (it doesn't belong to a Type).
if (exe is not null)
{
s_mainType = exe.EntryPoint?.ReflectedType;
}
}
}
return s_mainType;
}
/// <summary>
/// Locates a thread context given a window handle.
/// </summary>
internal static unsafe ThreadContext GetContextForHandle<T>(T handle) where T : IHandle<HWND>
{
ThreadContext? threadContext = ThreadContext.FromId(PInvoke.GetWindowThreadProcessId(handle.Handle, null));
Debug.Assert(
threadContext is not null,
"No thread context for handle. This is expected if you saw a previous assert about the handle being invalid.");
GC.KeepAlive(handle);
return threadContext;
}
/// <summary>
/// Returns a string that is the combination of the basePath + CompanyName + ProductName + ProductVersion. This
/// will also create the directory if it doesn't exist.
/// </summary>
private static string GetDataPath(string basePath)
{
string path = Path.Join(basePath, CompanyName, ProductName, ProductVersion);
lock (s_internalSyncObject)
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
}
return path;
}