-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathApplication.cs
1358 lines (1207 loc) · 52.5 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.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Forms.VisualStyles;
using Microsoft.Win32;
using static Interop;
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 object();
private static bool s_useWaitCursor;
private static bool s_useEverettThreadAffinity;
private static bool s_checkedThreadAffinity;
private const string EverettThreadAffinityValue = "EnableSystemEventsThreadAffinityCompatibility";
/// <summary>
/// Events the user can hook into
/// </summary>
private static readonly object s_eventApplicationExit = new object();
private static readonly object s_eventThreadExit = new object();
// Constant string used in Application.Restart()
private const string IEEXEC = "ieexec.exe";
// Defines a new callback delegate type
[EditorBrowsable(EditorBrowsableState.Advanced)]
public delegate bool MessageLoopCallback();
// Used to avoid recursive exit
private static bool s_exiting;
/// <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.FromCurrent().GetAllowQuit();
/// <summary>
/// Returns True if it is OK to continue idle processing. Typically called in an Application.Idle event handler.
/// </summary>
internal static bool CanContinueIdle
=> ThreadContext.FromCurrent().ComponentManager.FContinueIdle().IsTrue();
/// <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 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.
IntPtr hModule = Kernel32.GetModuleHandleW(Libraries.Comctl32);
if (hModule != IntPtr.Zero)
{
return Kernel32.GetProcAddress(hModule, "ImageList_WriteEx") != IntPtr.Zero;
}
// Load comctl since GetModuleHandle failed to find it
hModule = Kernel32.LoadComctl32(StartupPath);
if (hModule == IntPtr.Zero)
{
return false;
}
return Kernel32.GetProcAddress(hModule, "ImageList_WriteEx") != IntPtr.Zero;
}
/// <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}";
internal static bool UseEverettThreadAffinity
{
get
{
if (!s_checkedThreadAffinity)
{
s_checkedThreadAffinity = true;
try
{
// We need access to be able to read from the registry here. We're not creating a
// registry key, nor are we returning information from the registry to the user.
RegistryKey key = Registry.LocalMachine.OpenSubKey(CommonAppDataRegistryKeyName);
if (key is not null)
{
object value = key.GetValue(EverettThreadAffinityValue);
key.Close();
if (value is not null && (int)value != 0)
{
s_useEverettThreadAffinity = true;
}
}
}
catch (Security.SecurityException)
{
// Can't read the key: use default value (false)
}
catch (InvalidCastException)
{
// Key is of wrong type: use default value (false)
}
}
return s_useEverettThreadAffinity;
}
}
/// <summary>
/// Gets the path for the application data that is shared among all users.
/// </summary>
/// <remarks>
/// Don't obsolete these. GetDataPath isn't on SystemInformation, and it provides
/// the Windows logo required adornments to the directory (Company\Product\Version)
/// </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 t = GetAppMainType();
if (t is not null)
{
string ns = t.Namespace;
if (!string.IsNullOrEmpty(ns))
{
int firstDot = ns.IndexOf('.');
if (firstDot != -1)
{
s_companyName = ns.Substring(0, 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
{
get
{
if (s_executablePath is null)
{
StringBuilder sb = UnsafeNativeMethods.GetModuleFileNameLongPath(NativeMethods.NullHandleRef);
s_executablePath = Path.GetFullPath(sb.ToString());
}
return s_executablePath;
}
}
/// <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
=> DpiHelper.GetWinformsApplicationDpiAwareness();
/// <summary>
/// Gets the path for the application data specific to a local, non-roaming user.
/// </summary>
/// <remarks>
/// Don't obsolete these. GetDataPath isn't on SystemInformation, and it provides
/// the Windows logo required adornments to the directory (Company\Product\Version)
/// </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 ?? (s_forms = new FormCollection());
/// <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 t = GetAppMainType();
if (t is not null)
{
string ns = t.Namespace;
if (!string.IsNullOrEmpty(ns))
{
int lastDot = ns.LastIndexOf('.');
if (lastDot != -1 && lastDot < ns.Length - 1)
{
s_productName = ns.Substring(lastDot + 1);
}
else
{
s_productName = ns;
}
}
else
{
// last ditch... use the main type
s_productName = t.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
{
if (s_safeTopLevelCaptionSuffix is null)
{
s_safeTopLevelCaptionSuffix = SR.SafeTopLevelCaptionFormat; // 0 - original, 1 - zone, 2 - site
}
return s_safeTopLevelCaptionSuffix;
}
set
{
if (value is null)
{
value = string.Empty;
}
s_safeTopLevelCaptionSuffix = value;
}
}
/// <summary>
/// Gets the path for the executable file that started the application.
/// </summary>
public static string StartupPath
{
get
{
if (s_startupPath is null)
{
// 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>
/// Don't obsolete these. GetDataPath isn't on SystemInformation, and it provides
/// the Windows logo required adornments to the directory (Company\Product\Version)
/// </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>
/// 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.
/// </remarks>
public static bool UseVisualStyles { get; private set; }
/// <remarks>
/// 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.
/// </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)UxTheme.GetThemeAppProperties();
return vState;
}
set
{
if (VisualStyleInformation.IsSupportedByOS)
{
UxTheme.SetThemeAppProperties((UxTheme.STAP)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.
User32.EnumWindows(SendThemeChanged);
}
}
}
/// <summary>
/// This helper broadcasts out a WM_THEMECHANGED to appropriate top level windows of this app.
/// </summary>
private unsafe static BOOL SendThemeChanged(IntPtr handle)
{
uint thisPID = Kernel32.GetCurrentProcessId();
User32.GetWindowThreadProcessId(handle, out uint processId);
if (processId == thisPID && User32.IsWindowVisible(handle).IsTrue())
{
SendThemeChangedRecursive(handle);
User32.RedrawWindow(
handle,
null,
IntPtr.Zero,
User32.RDW.INVALIDATE | User32.RDW.FRAME | User32.RDW.ERASE | User32.RDW.ALLCHILDREN);
}
return BOOL.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(IntPtr handle)
{
// First send to all children...
User32.EnumChildWindows(handle, Application.SendThemeChangedRecursive);
// Then do myself.
User32.SendMessageW(handle, User32.WM.THEMECHANGED);
return BOOL.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)
{
if (s_eventHandlers is null)
{
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
User32.MSG msg = message;
bool processed = ThreadContext.FromCurrent().ProcessFilters(ref msg, out bool modified);
if (modified)
{
message.HWnd = msg.hwnd;
message.Msg = (int)msg.message;
message.WParam = msg.wParam;
message.LParam = 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;
// This just ensures that the component manager is hooked up. We
// need it for idle time processing.
object o = current.ComponentManager;
}
}
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(Mso.msoloop.DoEvents, null);
internal static void DoEventsModal()
=> ThreadContext.FromCurrent().RunMessageLoop(Mso.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>
public static void EnableVisualStyles()
{
// Pull manifest from our resources
Module module = typeof(Application).Module;
IntPtr moduleHandle = Kernel32.GetModuleHandleW(module.Name);
if (moduleHandle != IntPtr.Zero)
{
// 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");
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 cancelled 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 is not null)
{
foreach (Form f in s_forms)
{
if (f.RaiseFormClosingOnAppExit())
{
// A form refused to close
if (e is not null)
{
e.Cancel = true;
}
return;
}
}
while (s_forms.Count > 0)
{
// OnFormClosed removes the form from the FormCollection
s_forms[0].RaiseFormClosedOnAppExit();
}
}
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>
private static FileVersionInfo GetAppFileVersionInfo()
{
lock (s_internalSyncObject)
{
if (s_appFileVersion is null)
{
Type t = GetAppMainType();
if (t is not null)
{
s_appFileVersion = FileVersionInfo.GetVersionInfo(t.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>