A
download Application.cs
Language: C#
License: GPL
Copyright: (C) 2003 Southern Storm Software, Pty Ltd.
LOC: 506
Project Info
DotGNU Portable.NET(dotgnu-pnet)
Server: Savannah GNU
Type: cvs
...etlib\System.Windows.Forms\
   .cvsignore
   AccessibleEvents.cs
   AccessibleNavigation.cs
   AccessibleObject.cs
   AccessibleRole.cs
   AccessibleSelection.cs
   AccessibleStates.cs
   ActivationGesture.cs
   ActivationState.cs
   AmbientProperties.cs
   AnchorStyles.cs
   Appearance.cs
   Application.cs
   ApplicationContext.cs
   ArrangeDirection.cs
   ArrangeStartingPosition.cs
   BaseCollection.cs
   Binding.cs
   BindingContext.cs
   BindingManagerBase.cs
   BindingMemberInfo.cs
   BindingsCollection.cs
   BootMode.cs
   Border3DSide.cs
   Border3DStyle.cs
   BorderStyle.cs
   BoundsSpecified.cs
   Button.cs
   ButtonBase.cs
   ButtonBorderStyle.cs
   ButtonBoxLayout.cs
   ButtonState.cs
   CancelEventArgs.cs
   CancelEventHandler.cs
   CaptionButton.cs
   CharacterCasing.cs
   CheckBox.cs
   CheckListBox.cs
   CheckState.cs
   Clipboard.cs
   ColorDepth.cs
   ColorDialog.cs
   ColumnClickEventArgs.cs
   ColumnClickEventHandler.cs
   ColumnHeader.cs
   ColumnHeaderStyle.cs
   ComboBox.cs
   ComboBoxStyle.cs
   CommonDialog.cs
   ContainerControl.cs
   ...entsResizedEventArgs.cs
   ...sResizedEventHandler.cs
   ContextMenu.cs
   Control.cs
   ...olBindingsCollection.cs
   ControlEventArgs.cs
   ControlEventHandler.cs
   ControlPaint.cs
   ControlStyles.cs
   ControlToolkitMgr.cs
   ConvertEventArgs.cs
   ConvertEventHandler.cs
   CreateParams.cs
   CurrencyManager.cs
   Cursor.cs
   CursorConverter.cs
   Cursors.cs
   DataFormats.cs
   DataGrid.cs
   DataGridBoolColumn.cs
   DataGridCell.cs
   DataGridColumnStyle.cs
   DataGridLineStyle.cs
   ...ParentRowsLabelStyle.cs
   ...mnWidthTypeConverter.cs
   DataGridTableStyle.cs
   DataGridTextBox.cs
   DataGridTextBoxColumn.cs
   DataObject.cs
   DateBoldEventArgs.cs
   DateBoldEventHandler.cs
   DateRangeEventArgs.cs
   DateRangeEventHandler.cs
   DateTimePickerFormat.cs
   Day.cs
   DialogResult.cs
   DockStyle.cs
   DomainUpDown.cs
   DragAction.cs
   DragDropEffects.cs
   DragEventArgs.cs
   DragEventHandler.cs
   DrawItemEventArgs.cs
   DrawItemEventHandler.cs
   DrawItemState.cs
   DrawMode.cs
   ErrorBlinkStyle.cs
   ErrorIconAlignment.cs
   ErrorProvider.cs
   EventId.cs
   FeatureSupport.cs
   FileDialog.cs
   FlatStyle.cs
   FolderBrowserDialog.cs
   FontDialog.cs
   Form.cs
   FormBorderStyle.cs
   Forms.build
   FormStartPosition.cs
   FormWindowState.cs
   FrameStyle.cs
   GiveFeedbackEventArgs.cs
   ...FeedbackEventHandler.cs
   ...lumnStylesCollection.cs
   GridItem.cs
   GridItemCollection.cs
   GridItemType.cs
   GridLayout.cs
   ...ableStylesCollection.cs
   GroupBox.cs
   HBoxLayout.cs
   Help.cs
   HelpEventArgs.cs
   HelpEventHandler.cs
   HelpNavigator.cs
   HelpProvider.cs
   HorizontalAlignment.cs
   HScrollBar.cs
   IBindableComponent.cs
   IButtonControl.cs
   ICommandExecutor.cs
   ...ponentEditorPageSite.cs
   IContainerControl.cs
   ...gNotificationService.cs
   IDataGridEditingService.cs
   IDataObject.cs
   IDropTarget.cs
   IFeatureSupport.cs
   IFileReaderService.cs
   ImageIndexConverter.cs
   ImageList.cs
   ImageListStreamer.cs
   ImeMode.cs
   IMessageFilter.cs
   InputLanguage.cs
   ...uageChangedEventArgs.cs
   ...eChangedEventHandler.cs
   ...ageChangingEventArgs.cs
   ...ChangingEventHandler.cs
   InvalidateEventArgs.cs
   InvalidateEventHandler.cs
   IRecommendedSize.cs
   ItemActivation.cs
   ItemBoundsPortion.cs
   ItemChangedEventArgs.cs
   ItemChangedEventHandler.cs
   ItemCheckEventArgs.cs
   ItemCheckEventHandler.cs
   ItemDragEventArgs.cs
   ItemDragEventHandler.cs
   IWin32Window.cs
   IWindowTarget.cs
   KeyEventArgs.cs
   KeyEventHandler.cs
   KeyPressEventArgs.cs
   KeyPressEventHandler.cs
   Keys.cs
   Label.cs
   LabelEditEventArgs.cs
   LabelEditEventHandler.cs
   LayoutEventArgs.cs
   LayoutEventHandler.cs
   LeftRightAlignment.cs
   LinkArea.cs
   LinkBehavior.cs
   LinkClickedEventArgs.cs
   LinkClickedEventHandler.cs
   LinkLabel.cs
   ...LinkClickedEventArgs.cs
   ...kClickedEventHandler.cs
   LinkState.cs
   ListBindingConverter.cs
   ListBox.cs
   ListControl.cs
   ListView.cs
   ListViewAlignment.cs
   ListViewItem.cs
   ListViewItemConverter.cs
   ...ViewSubItemConverter.cs
   MainMenu.cs
   Makefile.am
   MdiClient.cs
   MdiLayout.cs
   MeasureItemEventArgs.cs
   MeasureItemEventHandler.cs
   Menu.cs
   MenuGlyph.cs
   MenuItem.cs
   MenuMerge.cs
   Message.cs
   MessageBox.cs
   MessageBoxButtons.cs
   MessageBoxDefaultButton.cs
   MessageBoxIcon.cs
   MessageBoxOptions.cs
   MethodInvoker.cs
   MonthCalendar.cs
   MouseButtons.cs
   MouseEventArgs.cs
   MouseEventHandler.cs
   NativeWindow.cs
   NavigateEventArgs.cs
   NavigateEventHandler.cs
   NodeLabelEditEventArgs.cs
   ...abelEditEventHandler.cs
   NotifyIcon.cs
   NumericUpDown.cs
   OpenFileDialog.cs
   Orientation.cs
   OSFeature.cs
   OwnerDrawPropertyBag.cs
   PaintEventArgs.cs
   PaintEventHandler.cs
   Panel.cs
   PictureBox.cs
   PictureBoxSizeMode.cs
   PopupControl.cs
   PrintDialog.cs
   ProgressBar.cs
   PropertySort.cs
   ...yTabChangedEventArgs.cs
   ...bChangedEventHandler.cs
   ...alueChangedEventArgs.cs
   ...eChangedEventHandler.cs
   ...ccessibilityHelpArgs.cs
   ...lityHelpEventHandler.cs
   ...ontinueDragEventArgs.cs
   ...inueDragEventHandler.cs
   RadioButton.cs
   RichTextBox.cs
   RichTextBoxFinds.cs
   RichTextBoxScrollBars.cs
   ...oxSelectionAttribute.cs
   ...extBoxSelectionTypes.cs
   RichTextBoxStreamType.cs
   ...tBoxWordPunctuations.cs
   RightToLeft.cs
   S.cs
   SaveFileDialog.cs
   Screen.cs
   ScrollableControl.cs
   ScrollBar.cs
   ScrollBars.cs
   ScrollButton.cs
   ScrollEventArgs.cs
   ScrollEventHandler.cs
   ScrollEventType.cs
   SecurityIDType.cs
   ...ItemChangedEventArgs.cs
   ...mChangedEventHandler.cs
   SelectionMode.cs
   Shortcut.cs
   SizeGripStyle.cs
   SortOrder.cs
   Splitter.cs
   SplitterEventArgs.cs
   SplitterEventHandler.cs
   StatusBar.cs
   ...BarDrawItemEventArgs.cs
   ...DrawItemEventHandler.cs
   StatusBarPanel.cs
   StatusBarPanelAutoSize.cs
   ...sBarPanelBorderStyle.cs
   ...rPanelClickEventArgs.cs
   ...nelClickEventHandler.cs
   StatusBarPanelStyle.cs
   StructFormat.cs
   SystemInformation.cs
   TabAlignment.cs
   TabAppearance.cs
   TabControl.cs
   TabDrawMode.cs
   TabPage.cs
   TabSizeMode.cs
   TextBox.cs
   TextBoxBase.cs
   TickStyle.cs
   Timer.cs
   TODOAttribute.cs
   ToolBar.cs
   ToolBarAppearance.cs
   ToolBarButton.cs
   ...ButtonClickEventArgs.cs
   ...tonClickEventHandler.cs
   ToolBarButtonStyle.cs
   ToolBarTextAlign.cs
   ToolTip.cs
   TrackBar.cs
   TreeNode.cs
   TreeNodeCollection.cs
   TreeView.cs
   TreeViewAction.cs
   TreeViewCancelEventArgs.cs
   ...ewCancelEventHandler.cs
   TreeViewEventArgs.cs
   TreeViewEventHandler.cs
   TriangleDirection.cs
   UICues.cs
   UICuesEventArgs.cs
   UICuesEventHandler.cs
   UpDownBase.cs
   UpDownEventArgs.cs
   UpDownEventHandler.cs
   UserControl.cs
   VBoxLayout.cs
   View.cs
   VScrollBar.cs
   Win32Constants.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
/*
 * Application.cs - Implementation of the
 *			"System.Windows.Forms.Application" class.
 *
 * Copyright (C) 2003  Southern Storm Software, Pty Ltd.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

namespace System.Windows.Forms
{

using Microsoft.Win32;
using System.Globalization;
using System.Threading;
using System.Reflection;
using System.IO;
using System.Drawing.Toolkit;

public sealed class Application
{
	// Internal state.
	private static Request requests;
	private static Request lastRequest;

	// Cannot instantiate this class.
	private Application() {}

#if !CONFIG_COMPACT_FORMS

	// Internal state.
	[ThreadStatic] private static InputLanguage inputLanguage;
	private static String safeTopLevelCaptionFormat = "{0}";

	// Determine if it is possible to quit this application.
	public static bool AllowQuit
			{
				get
				{
					// Returns false for applet usage, which we don't have yet.
					return true;
				}
			}

#if CONFIG_WIN32_SPECIFICS

	// Get a registry key for a data path.
	private static RegistryKey GetAppDataRegistry(RegistryKey hive)
			{
				String key = "Software\\" + CompanyName + "\\" +
							 ProductName + "\\" + ProductVersion;
				return hive.CreateSubKey(key);
			}

	// Get the common registry key for data shared between all users.
	public static RegistryKey CommonAppDataRegistry
			{
				get
				{
					return GetAppDataRegistry(Registry.LocalMachine);
				}
			}

#endif

#if !ECMA_COMPAT

	// Get a data path based on a special folder name.
	private static String GetAppDataPath(Environment.SpecialFolder folder)
			{
				String path = Environment.GetFolderPath(folder);
				path += Path.DirectorySeparatorChar.ToString() +
						CompanyName +
						Path.DirectorySeparatorChar.ToString() +
						ProductName +
						Path.DirectorySeparatorChar.ToString() +
						ProductVersion;
				if(!Directory.Exists(path))
				{
					Directory.CreateDirectory(path);
				}
				return path;
			}

	// Get the common data path for data shared between all users.
	public static String CommonAppDataPath
			{
				get
				{
					return GetAppDataPath
						(Environment.SpecialFolder.CommonApplicationData);
				}
			}

	// Get the local user application data path.
	public static String LocalUserAppDataPath
			{
				get
				{
					return GetAppDataPath
						(Environment.SpecialFolder.LocalApplicationData);
				}
			}

	// Get the user application data path.
	public static String UserAppDataPath
			{
				get
				{
					return GetAppDataPath
						(Environment.SpecialFolder.ApplicationData);
				}
			}

	// Get the company name for this application
	public static String CompanyName
			{
				get
				{
					Assembly assembly = Assembly.GetEntryAssembly();
					Object[] attrs = assembly.GetCustomAttributes
						(typeof(AssemblyCompanyAttribute), false);
					if(attrs != null && attrs.Length > 0)
					{
						return ((AssemblyCompanyAttribute)(attrs[0])).Company;
					}
					return assembly.GetName().Name;
				}
			}

	// Get the product name associated with this application.
	public static String ProductName
			{
				get
				{
					Assembly assembly = Assembly.GetEntryAssembly();
					Object[] attrs = assembly.GetCustomAttributes
						(typeof(AssemblyProductAttribute), false);
					if(attrs != null && attrs.Length > 0)
					{
						return ((AssemblyProductAttribute)(attrs[0])).Product;
					}
					return assembly.GetName().Name;
				}
			}

	// Get the product version associated with this application.
	public static String ProductVersion
			{
				get
				{
					Assembly assembly = Assembly.GetEntryAssembly();
					Object[] attrs = assembly.GetCustomAttributes
						(typeof(AssemblyInformationalVersionAttribute), false);
					if(attrs != null && attrs.Length > 0)
					{
						return ((AssemblyInformationalVersionAttribute)
							(attrs[0])).InformationalVersion;
					}
					return assembly.GetName().Version.ToString();
				}
			}

#endif // !ECMA_COMPAT

	// Get or set the culture for the current thread.
	public static CultureInfo CurrentCulture
			{
				get
				{
					return CultureInfo.CurrentCulture;
				}
				set
				{
				#if !ECMA_COMPAT
					Thread.CurrentThread.CurrentCulture = value;
				#endif
				}
			}

	// Get or set the input language for the current thread.
	public static InputLanguage CurrentInputLanguage
			{
				get
				{
					return inputLanguage;
				}
				set
				{
					inputLanguage = value;
				}
			}

	// Get the executable path for this application.
	public static String ExecutablePath
			{
				get
				{
					return (Environment.GetCommandLineArgs())[0];
				}
			}

	// Determine if a message loop exists on this thread.
	public static bool MessageLoop
			{
				get
				{
					return true;
				}
			}

	// Get or set the top-level warning caption format.
	public static String SafeTopLevelCaptionFormat
			{
				get
				{
					return safeTopLevelCaptionFormat;
				}
				set
				{
					safeTopLevelCaptionFormat = value;
				}
			}

	// Get the startup path for the executable.
	public static String StartupPath
			{
				get
				{
					return Path.GetDirectoryName(ExecutablePath);
				}
			}

#if CONFIG_WIN32_SPECIFICS

	// Get the registry key for user-specific data.
	public static RegistryKey UserAppDataRegistry
			{
				get
				{
					return GetAppDataRegistry(Registry.CurrentUser);
				}
			}

#endif

	// Add a message filter.
	public static void AddMessageFilter(IMessageFilter value)
			{
				// We don't use message filters in this implementation.
			}

	// Enable Windows XP visual styles.
	public static void EnableVisualStyles()
			{
				// Not used in this implementation.
			}

	// Exit the message loop on the current thread and close all windows.
	public static void ExitThread()
			{
				// We only allow one message loop in this implementation,
				// so "ExitThread" is the same as "Exit".
				Exit();
			}

#if !ECMA_COMPAT

	// Initialize OLE on the current thread.
	public static ApartmentState OleRequired()
			{
				// Not used in this implementation.
				return ApartmentState.Unknown;
			}

#endif

	// Raise the thread exception event.
	public static void OnThreadException(Exception t)
			{
				if(ThreadException != null)
				{
					ThreadException(null, new ThreadExceptionEventArgs(t));
				}
			}

	// Remove a message filter.
	public static void RemoveMessageFilter(IMessageFilter value)
			{
				// We don't use message filters in this implementation.
			}

	// Event that is raised when the application is about to exit.
	public static event EventHandler ApplicationExit;

	// Event that is raised when the message loop is entering the idle state.
	public static event EventHandler Idle;

	// Event that is raised for an untrapped thread exception.
	public static event ThreadExceptionEventHandler ThreadException;

	// Event that is raised when the current thread is about to exit.
	public static event EventHandler ThreadExit;

#endif // !CONFIG_COMPACT_FORMS

	// The thread that is running the main message loop.
	private static Thread mainThread;

	// Process all events that are currently in the message queue.
	public static void DoEvents()
			{
				bool isMainThread;
				Thread thread = Thread.CurrentThread;
				Request request;

				// Determine if we are the main thread.
				lock(typeof(Application))
				{
					isMainThread = (mainThread == thread);
				}

				// Process pending events.
				if(isMainThread)
				{
					ToolkitManager.Toolkit.ProcessEvents(false);
				}

				// Process requests that were sent via "SendRequest".
				while((request = NextRequest(thread, false)) != null)
				{
					request.Execute();
				}
			}

	// Tell the application to exit.
	public static void Exit()
			{
				lock(typeof(Application))
				{
					if(mainThread != null ||
					   Thread.CurrentThread == null)
					{
						ToolkitManager.Toolkit.Quit();
					}
				}
			}

	// Exit from the current thread when the main form closes.
	private static void ContextExit(Object sender, EventArgs e)
			{
			#if !CONFIG_COMPACT_FORMS
				ExitThread();
			#else
				Exit();
			#endif
			}

	// Inner version of "Run".  In this implementation we only allow a
	// message loop to be running on one of the threads.
	private static void RunMessageLoop(ApplicationContext context)
			{
				Form mainForm = context.MainForm;
				EventHandler handler;
				Request request;
				Thread thread = Thread.CurrentThread;
				bool isMainThread;

				// Connect the context's ThreadExit event to our "ExitThread".
				handler = new EventHandler(ContextExit);
				context.ThreadExit += handler;

				// Show the main form on-screen.
				if(mainForm != null)
				{
					mainForm.Show();
					mainForm.SelectNextControl (null, true, true, true, false);
					Form.activeForm = mainForm;
				}

				// Make sure that we are the only message loop.
				lock(typeof(Application))
				{
					if(mainThread != null)
					{
						isMainThread = false;
					}
					else
					{
						mainThread = thread;
						isMainThread = true;
					}
				}

				// Run the main message processing loop.
				if(isMainThread)
				{
					IToolkit toolkit = ToolkitManager.Toolkit;
					try
					{
						for(;;)
						{
							try {
								// Process events in the queue.
								if(!toolkit.ProcessEvents(false))
								{
								#if !CONFIG_COMPACT_FORMS
									// There were no events, so raise "Idle".
									if(Idle != null)
									{
										Idle(null, EventArgs.Empty);
									}
								#endif
		
									// Block until an event, or quit, arrives.
									if(!toolkit.ProcessEvents(true))
									{
										break;
									}
								}
		
								// Process requests sent via "SendRequest".
								while((request = NextRequest(thread, false))
											!= null)
								{
									request.Execute();
								}
							}
							catch( Exception e ) {
								Application.OnThreadException( e );
							}
						}
					}
					finally
					{
						// Reset the "mainThread" variable because there
						// is no message loop any more.
						lock(typeof(Application))
						{
							mainThread = null;
						}
					}
				}
				else
				{
					// This is not the main thread, so only process
					// requests that were sent via "SendRequest".
					while((request = NextRequest(thread, true)) != null)
					{
						request.Execute();
					}
				}

				// Disconnect from the context's "ThreadExit" event.
				context.ThreadExit -= handler;
				Form.activeForm = null;

			#if !CONFIG_COMPACT_FORMS

				// Raise the "ThreadExit" event.
				if(ThreadExit != null)
				{
					ThreadExit(null, EventArgs.Empty);
				}

				// Raise the "ApplicationExit" event.
				if(ApplicationExit != null)
				{
					ApplicationExit(null, EventArgs.Empty);
				}

			#endif
			}

	// Run an inner message loop until the dialog result is set on a form.
	internal static void InnerMessageLoop(Form form)
			{
				Request request;
				Thread thread = Thread.CurrentThread;
				bool isMainThread;
				bool resetMainThread;

				// Determine if we are running on the main thread or not.
				lock(typeof(Application))
				{
					if(mainThread == null)
					{
						// The main message loop hasn't started yet.
						// This might happen with MessageBox dialogs.
						mainThread = thread;
						isMainThread = true;
						resetMainThread = true;
					}
					else
					{
						isMainThread = (mainThread == thread);
						resetMainThread = false;
					}
				}

				// Run the main message processing loop.
				if(isMainThread)
				{
					IToolkit toolkit = ToolkitManager.Toolkit;
					try
					{
						while(!(form.dialogResultIsSet) && form.Visible)
						{
							// Process events in the queue.
							if(!toolkit.ProcessEvents(false))
							{
							#if !CONFIG_COMPACT_FORMS
								// There were no events, so raise "Idle".
								if(Idle != null)
								{
									Idle(null, EventArgs.Empty);
								}
							#endif
	
								// Block until an event, or quit, arrives.
								if(!toolkit.ProcessEvents(true))
								{
									break;
								}
							}
	
							// Process requests sent via "SendRequest".
							while((request = NextRequest(thread, false))
										!= null)
							{
								request.Execute();
							}
						}
					}
					finally
					{
						// Reset the "mainThread" variable because there
						// is no message loop any more.
						lock(typeof(Application))
						{
							if(resetMainThread)
							{
								mainThread = null;
							}
						}
					}
				}
				else
				{
					// This is not the main thread, so only process
					// requests that were sent via "SendRequest".
					while(!(form.dialogResultIsSet) && form.Visible)
					{
						if((request = NextRequest(thread, true)) != null)
						{
							request.Execute();
						}
						else
						{
							break;
						}
					}
				}
			}

	// Make the specified form visible and run the main loop.
	// The loop will exit when "Exit" is called.
	public static void Run(Form mainForm)
			{
				RunMessageLoop(new ApplicationContext(mainForm));
			}

#if !CONFIG_COMPACT_FORMS

	// Run the main message loop on this thread.
	public static void Run()
			{
				RunMessageLoop(new ApplicationContext());
			}

	// Run the main message loop for an application context.
	public static void Run(ApplicationContext context)
			{
				if(context == null)
				{
					context = new ApplicationContext();
				}
				RunMessageLoop(context);
			}

#endif // !CONFIG_COMPACT_FORMS

	// Information about a request to be executed in a specific thread.
	// This is used to help implement the "Control.Invoke" method.
	internal abstract class Request
	{
		public Request next;
		public Thread thread;

		// Execute the request.
		public abstract void Execute();

	}; // class Request

	// Send a request to a particular thread's message queue.
	internal static void SendRequest(Request request, Thread thread)
			{
				Object obj = typeof(Application);
				request.thread = thread;
				lock(obj)
				{
					// Add the request to the queue.
					request.next = null;
					if(requests != null)
					{
						lastRequest.next = request;
					}
					else
					{
						requests = request;
					}
					lastRequest = request;

					// Wake up all threads that are blocking in "NextRequest".
					Monitor.PulseAll(obj);

					// Wake up the thread that will receive the request,
					// as it may be blocking inside "ProcessEvents".
					ToolkitManager.Toolkit.Wakeup(thread);
				}
			}

	// Get the next pending request for a particular thread.
	private static Request NextRequest(Thread thread, bool block)
			{
				Object obj = typeof(Application);
				Request request, prev;
				lock(obj)
				{
					for(;;)
					{
						// See if there is a request on the queue for us.
						prev = null;
						request = requests;
						while(request != null)
						{
							if(request.thread == thread)
							{
								if(prev != null)
								{
									prev.next = request.next;
								}
								else
								{
									requests = request.next;
								}
								if(request.next == null)
								{
									lastRequest = prev;
								}
								else
								{
									request.next = null;
								}
								break;
							}
							prev = request;
							request = request.next;
						}

						// Bail out if we got something or we aren't blocking.
						if(request != null || !block)
						{
							break;
						}

						// Wait to be signalled by "SendRequest".
						Monitor.Wait(obj);
					}
				}
				return request;
			}

}; // class Application

}; // namespace System.Windows.Forms

About Koders | Resources | Downloads | Support | Black Duck | Terms of Service | DMCA | Privacy Policy | Contact Us