[MWF] Don't try to remove non-child control (#19818)
[mono.git] / mcs / class / Managed.Windows.Forms / System.Windows.Forms / Control.cs
1 // Permission is hereby granted, free of charge, to any person obtaining
2 // a copy of this software and associated documentation files (the
3 // "Software"), to deal in the Software without restriction, including
4 // without limitation the rights to use, copy, modify, merge, publish,
5 // distribute, sublicense, and/or sell copies of the Software, and to
6 // permit persons to whom the Software is furnished to do so, subject to
7 // the following conditions:
8 // 
9 // The above copyright notice and this permission notice shall be
10 // included in all copies or substantial portions of the Software.
11 // 
12 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
13 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
15 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
16 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
17 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
18 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
19 //
20 // Copyright (c) 2004-2006 Novell, Inc.
21 //
22 // Authors:
23 //      Peter Bartok            pbartok@novell.com
24 //
25 // Partially based on work by:
26 //      Aleksey Ryabchuk        ryabchuk@yahoo.com
27 //      Alexandre Pigolkine     pigolkine@gmx.de
28 //      Dennis Hayes            dennish@raytek.com
29 //      Jaak Simm               jaaksimm@firm.ee
30 //      John Sohn               jsohn@columbus.rr.com
31 //
32
33 #undef DebugRecreate
34 #undef DebugFocus
35 #undef DebugMessages
36
37 using System;
38 using System.ComponentModel;
39 using System.ComponentModel.Design;
40 using System.ComponentModel.Design.Serialization;
41 using System.Collections;
42 using System.Diagnostics;
43 using System.Drawing;
44 using System.Drawing.Drawing2D;
45 using System.Reflection;
46 using System.Runtime.InteropServices;
47 using System.Security;
48 using System.Threading;
49
50 namespace System.Windows.Forms
51 {
52         [ComVisible(true)]
53         [ClassInterface (ClassInterfaceType.AutoDispatch)]
54         [Designer("System.Windows.Forms.Design.ControlDesigner, " + Consts.AssemblySystem_Design, "System.ComponentModel.Design.IDesigner")]
55         [DefaultProperty("Text")]
56         [DefaultEvent("Click")]
57         [DesignerSerializer("System.Windows.Forms.Design.ControlCodeDomSerializer, " + Consts.AssemblySystem_Design, "System.ComponentModel.Design.Serialization.CodeDomSerializer, " + Consts.AssemblySystem_Design)]
58         [ToolboxItemFilter("System.Windows.Forms")]
59         public class Control : Component, ISynchronizeInvoke, IWin32Window
60                 , IBindableComponent, IDropTarget, IBounds
61         {
62                 #region Local Variables
63
64                 // Basic
65                 internal Rectangle              bounds;                 // bounding rectangle for control (client area + decorations)
66                 Rectangle               explicit_bounds; // explicitly set bounds
67                 internal object                 creator_thread;         // thread that created the control
68                 internal                ControlNativeWindow     window;                 // object for native window handle
69                 private                 IWindowTarget window_target;
70                 string                  name; // for object naming
71
72                 // State
73                 bool                    is_created; // true if OnCreateControl has been sent
74                 internal bool           has_focus;              // true if control has focus
75                 internal bool           is_visible;             // true if control is visible
76                 internal bool           is_entered;             // is the mouse inside the control?
77                 internal bool           is_enabled;             // true if control is enabled (usable/not grayed out)
78                 bool                    is_accessible; // true if the control is visible to accessibility applications
79                 bool                    is_captured; // tracks if the control has captured the mouse
80                 internal bool                   is_toplevel;            // tracks if the control is a toplevel window
81                 bool                    is_recreating; // tracks if the handle for the control is being recreated
82                 bool                    causes_validation; // tracks if validation is executed on changes
83                 bool                    is_focusing; // tracks if Focus has been called on the control and has not yet finished
84                 int                     tab_index; // position in tab order of siblings
85                 bool                    tab_stop; // is the control a tab stop?
86                 bool                    is_disposed; // has the window already been disposed?
87                 bool                    is_disposing; // is the window getting disposed?
88                 Size                    client_size; // size of the client area (window excluding decorations)
89                 Rectangle               client_rect; // rectangle with the client area (window excluding decorations)
90                 ControlStyles           control_style; // rather win32-specific, style bits for control
91                 ImeMode                 ime_mode;
92                 object                  control_tag; // object that contains data about our control
93                 internal int                    mouse_clicks;           // Counter for mouse clicks
94                 Cursor                  cursor; // Cursor for the window
95                 internal bool                   allow_drop;             // true if the control accepts droping objects on it   
96                 Region                  clip_region; // User-specified clip region for the window
97
98                 // Visuals
99                 internal Color                  foreground_color;       // foreground color for control
100                 internal Color                  background_color;       // background color for control
101                 Image                   background_image; // background image for control
102                 internal Font                   font;                   // font for control
103                 string                  text; // window/title text for control
104                 internal                BorderStyle             border_style;           // Border style of control
105                 bool                    show_keyboard_cues; // Current keyboard cues 
106                 internal bool           show_focus_cues; // Current focus cues 
107                 internal bool           force_double_buffer;    // Always doublebuffer regardless of ControlStyle
108
109                 // Layout
110                 internal enum LayoutType {
111                         Anchor,
112                         Dock
113                 }
114                 Layout.LayoutEngine layout_engine;
115                 internal int layout_suspended;
116                 bool layout_pending; // true if our parent needs to re-layout us
117                 internal AnchorStyles anchor_style; // anchoring requirements for our control
118                 internal DockStyle dock_style; // docking requirements for our control
119                 LayoutType layout_type;
120                 private bool recalculate_distances = true;  // Delay anchor calculations
121
122                 // Please leave the next 2 as internal until DefaultLayout (2.0) is rewritten
123                 internal int                    dist_right; // distance to the right border of the parent
124                 internal int                    dist_bottom; // distance to the bottom border of the parent
125
126                 // to be categorized...
127                 ControlCollection       child_controls; // our children
128                 Control                 parent; // our parent control
129                 BindingContext          binding_context;
130                 RightToLeft             right_to_left; // drawing direction for control
131                 ContextMenu             context_menu; // Context menu associated with the control
132                 internal bool           use_compatible_text_rendering;
133                 private bool            use_wait_cursor;
134
135                 //accessibility
136                 string accessible_name;
137                 string accessible_description;
138                 string accessible_default_action;
139                 AccessibleRole accessible_role = AccessibleRole.Default;
140                 AccessibleObject accessibility_object; // object that contains accessibility information about our control
141
142                 // double buffering
143                 DoubleBuffer            backbuffer;
144
145                 ControlBindingsCollection data_bindings;
146
147                 static bool verify_thread_handle;
148                 Padding padding;
149                 ImageLayout backgroundimage_layout;
150                 Size maximum_size;
151                 Size minimum_size;
152                 Padding margin;
153                 private ContextMenuStrip context_menu_strip;
154                 private bool nested_layout = false;
155                 Point auto_scroll_offset;
156                 private AutoSizeMode auto_size_mode;
157                 private bool suppressing_key_press;
158
159                 #endregion      // Local Variables
160
161                 #region Private Classes
162                 // This helper class allows us to dispatch messages to Control.WndProc
163                 internal class ControlNativeWindow : NativeWindow {
164                         private Control owner;
165
166                         public ControlNativeWindow(Control control) : base() {
167                                 this.owner=control;
168                         }
169
170
171                         public Control Owner {
172                                 get {
173                                         return owner;
174                                 }
175                         }
176
177                         protected override void OnHandleChange()
178                         {
179                                 this.owner.WindowTarget.OnHandleChange(this.owner.Handle);
180                         }
181
182                         static internal Control ControlFromHandle(IntPtr hWnd) {
183                                 ControlNativeWindow     window;
184
185                                 window = (ControlNativeWindow)NativeWindow.FromHandle (hWnd);
186                                 if (window != null) {
187                                         return window.owner;
188                                 }
189
190                                 return null;
191                         }
192
193                         static internal Control ControlFromChildHandle (IntPtr handle) {
194                                 ControlNativeWindow     window;
195
196                                 Hwnd hwnd = Hwnd.ObjectFromHandle (handle);
197                                 while (hwnd != null) {
198                                         window = (ControlNativeWindow)NativeWindow.FromHandle (handle);
199                                         if (window != null) {
200                                                 return window.owner;
201                                         }
202                                         hwnd = hwnd.Parent;
203                                 }
204
205                                 return null;
206                         }
207
208                         protected override void WndProc(ref Message m) {
209                                 owner.WindowTarget.OnMessage(ref m);
210                         }
211                 }
212
213                 private class ControlWindowTarget : IWindowTarget
214                 {
215                         private Control control;
216
217                         public ControlWindowTarget(Control control)
218                         {
219                                 this.control = control;
220                         }
221
222                         public void OnHandleChange(IntPtr newHandle) 
223                         {
224                         }
225
226                         public void OnMessage(ref Message m) 
227                         {
228                                 control.WndProc(ref m);
229                         }
230                 }
231                 #endregion
232                 
233                 #region Public Classes
234                 [ComVisible(true)]
235                 public class ControlAccessibleObject : AccessibleObject {
236                         IntPtr handle;
237
238                         #region ControlAccessibleObject Constructors
239                         public ControlAccessibleObject(Control ownerControl)
240                                 : base (ownerControl)
241                         {
242                                 if (ownerControl == null)
243                                         throw new ArgumentNullException ("owner");
244
245                                 handle = ownerControl.Handle;
246                         }
247                         #endregion      // ControlAccessibleObject Constructors
248
249                         #region ControlAccessibleObject Public Instance Properties
250                         public override string DefaultAction {
251                                 get {
252                                         return base.DefaultAction;
253                                 }
254                         }
255
256                         public override string Description {
257                                 get {
258                                         return base.Description;
259                                 }
260                         }
261
262                         public IntPtr Handle {
263                                 get {
264                                         return handle;
265                                 }
266
267                                 set {
268                                         // We don't want to let them set it
269                                 }
270                         }
271
272                         public override string Help {
273                                 get {
274                                         return base.Help;
275                                 }
276                         }
277
278                         public override string KeyboardShortcut {
279                                 get {
280                                         return base.KeyboardShortcut;
281                                 }
282                         }
283
284                         public override string Name {
285                                 get {
286                                         return base.Name;
287                                 }
288
289                                 set {
290                                         base.Name = value;
291                                 }
292                         }
293
294                         public Control Owner {
295                                 get {
296                                         return base.owner;
297                                 }
298                         }
299
300                         public override AccessibleObject Parent {
301                                 get {
302                                         return base.Parent;
303                                 }
304                         }
305
306
307                         public override AccessibleRole Role {
308                                 get {
309                                         return base.Role;
310                                 }
311                         }
312                         #endregion      // ControlAccessibleObject Public Instance Properties
313
314                         #region ControlAccessibleObject Public Instance Methods
315                         public override int GetHelpTopic (out string fileName)
316                         {
317                                 return base.GetHelpTopic (out fileName);
318                         }
319
320                         [MonoTODO ("Stub, does nothing")]
321                         public void NotifyClients (AccessibleEvents accEvent)
322                         {
323                         }
324
325                         [MonoTODO ("Stub, does nothing")]
326                         public void NotifyClients (AccessibleEvents accEvent, int childID)
327                         {
328                         }
329
330                         [MonoTODO ("Stub, does nothing")]
331                         public void NotifyClients (AccessibleEvents accEvent, int objectID, int childID)
332                         {
333                         }
334
335                         public override string ToString() {
336                                 return "ControlAccessibleObject: Owner = " + owner.ToString() + ", Text: " + owner.text;
337                         }
338
339                         #endregion      // ControlAccessibleObject Public Instance Methods
340                 }
341
342                 private class DoubleBuffer : IDisposable
343                 {
344                         public Region InvalidRegion;
345                         private Stack real_graphics;
346                         private object back_buffer;
347                         private Control parent;
348                         private bool pending_disposal;
349                         
350                         public DoubleBuffer (Control parent) {
351                                 this.parent = parent;
352                                 real_graphics = new Stack ();
353                                 int width = parent.Width;
354                                 int height = parent.Height;
355
356                                 if (width < 1) width = 1;
357                                 if (height < 1) height = 1;
358
359                                 XplatUI.CreateOffscreenDrawable (parent.Handle, width, height, out back_buffer);
360                                 Invalidate ();
361                         }
362                         
363                         public void Blit (PaintEventArgs pe) {
364                                 Graphics buffered_graphics;
365                                 buffered_graphics = XplatUI.GetOffscreenGraphics (back_buffer);
366                                 XplatUI.BlitFromOffscreen (parent.Handle, pe.Graphics, back_buffer, buffered_graphics, pe.ClipRectangle);
367                                 buffered_graphics.Dispose ();
368                         }
369                         
370                         public void Start (PaintEventArgs pe) {
371                                 // We need to get the graphics for every paint.
372                                 real_graphics.Push(pe.SetGraphics (XplatUI.GetOffscreenGraphics (back_buffer)));
373                         }
374
375                         public void End (PaintEventArgs pe) {
376                                 Graphics buffered_graphics;
377                                 buffered_graphics = pe.SetGraphics ((Graphics) real_graphics.Pop ());
378
379                                 if (pending_disposal) 
380                                         Dispose ();
381                                 else {
382                                         XplatUI.BlitFromOffscreen (parent.Handle, pe.Graphics, back_buffer, buffered_graphics, pe.ClipRectangle);
383                                         InvalidRegion.Exclude (pe.ClipRectangle);
384                                 }
385                                 buffered_graphics.Dispose ();
386                         }
387                         
388                         public void Invalidate ()
389                         {
390                                 if (InvalidRegion != null)
391                                         InvalidRegion.Dispose ();
392                                 InvalidRegion = new Region (parent.ClientRectangle);
393                         }
394                         
395                         public void Dispose () {
396                                 if (real_graphics.Count > 0) {
397                                         pending_disposal = true;
398                                         return;
399                                 }
400                                 
401                                 XplatUI.DestroyOffscreenDrawable (back_buffer);
402
403                                 if (InvalidRegion != null)
404                                         InvalidRegion.Dispose ();
405                                 InvalidRegion = null;
406                                 back_buffer = null;
407                                 GC.SuppressFinalize (this);
408                         }
409
410                         #region IDisposable Members
411                         void IDisposable.Dispose () {
412                                 Dispose ();
413                         }
414                         #endregion
415                         
416                         ~DoubleBuffer () {
417                                 Dispose ();
418                         }
419                 }
420
421                 [ListBindable (false)]
422                 [ComVisible (false)]
423                 public class ControlCollection : Layout.ArrangedElementCollection, IList, ICollection, ICloneable, IEnumerable {
424                         #region ControlCollection Local Variables
425                         ArrayList impl_list;
426                         Control [] all_controls;
427                         Control owner;
428                         #endregion // ControlCollection Local Variables
429
430                         #region ControlCollection Public Constructor
431                         public ControlCollection (Control owner)
432                         {
433                                 this.owner = owner;
434                         }
435                         #endregion
436
437                         #region ControlCollection Public Instance Properties
438
439
440                         public Control Owner {
441                                 get { return this.owner; }
442                         }
443                         
444                         public virtual Control this[string key] {
445                                 get { 
446                                         int index = IndexOfKey (key);
447                                         
448                                         if (index >= 0)
449                                                 return this[index];
450                                                 
451                                         return null;
452                                 }
453                         }
454                         
455                         new public virtual Control this[int index] {
456                                 get {
457                                         if (index < 0 || index >= list.Count) {
458                                                 throw new ArgumentOutOfRangeException("index", index, "ControlCollection does not have that many controls");
459                                         }
460                                         return (Control)list[index];
461                                 }
462                                 
463                                 
464                         }
465
466                         #endregion // ControlCollection Public Instance Properties
467                         
468                         #region ControlCollection Instance Methods
469
470                         public virtual void Add (Control value)
471                         {
472                                 if (value == null)
473                                         return;
474
475                                 Form form_value = value as Form;
476                                 Form form_owner = owner as Form;
477                                 bool owner_permits_toplevels = (owner is MdiClient) || (form_owner != null && form_owner.IsMdiContainer);
478                                 bool child_is_toplevel = value.GetTopLevel();
479                                 bool child_is_mdichild = form_value != null && form_value.IsMdiChild;
480
481                                 if (child_is_toplevel && !(owner_permits_toplevels && child_is_mdichild))
482                                         throw new ArgumentException("Cannot add a top level control to a control.", "value");
483                                 
484                                 if (child_is_mdichild && form_value.MdiParent != null && form_value.MdiParent != owner && form_value.MdiParent != owner.Parent) {
485                                         throw new ArgumentException ("Form cannot be added to the Controls collection that has a valid MDI parent.", "value");
486                                 }
487                                 
488                                 value.recalculate_distances = true;
489                                 
490                                 if (Contains (value)) {
491                                         owner.PerformLayout();
492                                         return;
493                                 }
494
495                                 if (value.tab_index == -1) {
496                                         int     end;
497                                         int     index;
498                                         int     use;
499
500                                         use = 0;
501                                         end = owner.child_controls.Count;
502                                         for (int i = 0; i < end; i++) {
503                                                 index = owner.child_controls[i].tab_index;
504                                                 if (index >= use) {
505                                                         use = index + 1;
506                                                 }
507                                         }
508                                         value.tab_index = use;
509                                 }
510
511                                 if (value.parent != null) {
512                                         value.parent.Controls.Remove(value);
513                                 }
514
515                                 all_controls = null;
516                                 list.Add (value);
517
518                                 value.ChangeParent(owner);
519
520                                 value.InitLayout();
521
522                                 if (owner.Visible)
523                                         owner.UpdateChildrenZOrder();
524                                 owner.PerformLayout(value, "Parent");
525                                 owner.OnControlAdded(new ControlEventArgs(value));
526                         }
527                         
528                         internal void AddToList (Control c)
529                         {
530                                 all_controls = null;
531                                 list.Add (c);
532                         }
533
534                         internal virtual void AddImplicit (Control control)
535                         {
536                                 if (impl_list == null)
537                                         impl_list = new ArrayList ();
538
539                                 if (AllContains (control)) {
540                                         owner.PerformLayout ();
541                                         return;
542                                 }
543
544                                 if (control.parent != null) {
545                                         control.parent.Controls.Remove(control);
546                                 }
547
548                                 all_controls = null;
549                                 impl_list.Add (control);
550
551                                 control.ChangeParent (owner);
552                                 control.InitLayout ();
553                                 if (owner.Visible)
554                                         owner.UpdateChildrenZOrder ();
555                                 
556                                 // If we are adding a new control that isn't
557                                 // visible, don't trigger a layout
558                                 if (control.VisibleInternal)
559                                         owner.PerformLayout (control, "Parent");
560                         }
561                         [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
562                         public virtual void AddRange (Control[] controls)
563                         {
564                                 if (controls == null)
565                                         throw new ArgumentNullException ("controls");
566
567                                 owner.SuspendLayout ();
568
569                                 try {
570                                         for (int i = 0; i < controls.Length; i++) 
571                                                 Add (controls[i]);
572                                 } finally {
573                                         owner.ResumeLayout ();
574                                 }
575                         }
576
577                         internal virtual void AddRangeImplicit (Control [] controls)
578                         {
579                                 if (controls == null)
580                                         throw new ArgumentNullException ("controls");
581
582                                 owner.SuspendLayout ();
583
584                                 try {
585                                         for (int i = 0; i < controls.Length; i++)
586                                                 AddImplicit (controls [i]);
587                                 } finally {
588                                         owner.ResumeLayout (false);
589                                 }
590                         }
591
592                         new 
593                         public virtual void Clear ()
594                         {
595                                 all_controls = null;
596
597                                 // MS sends remove events in reverse order
598                                 while (list.Count > 0) {
599                                         Remove((Control)list[list.Count - 1]);
600                                 }
601                         }
602
603                         internal virtual void ClearImplicit ()
604                         {
605                                 if (impl_list == null)
606                                         return;
607                                 all_controls = null;
608                                 impl_list.Clear ();
609                         }
610
611                         public bool Contains (Control control)
612                         {
613                                 return list.Contains (control);
614                         }
615
616                         internal bool ImplicitContains (Control value) {
617                                 if (impl_list == null)
618                                         return false;
619
620                                 return impl_list.Contains (value);
621                         }
622
623                         internal bool AllContains (Control value) {
624                                 return Contains (value) || ImplicitContains (value);
625                         }
626
627
628                         public virtual bool ContainsKey (string key)
629                         {
630                                 return IndexOfKey (key) >= 0;
631                         }
632
633
634                         // LAMESPEC: MSDN says AE, MS implementation throws ANE
635                         public Control[] Find (string key, bool searchAllChildren)
636                         {
637                                 if (string.IsNullOrEmpty (key))
638                                         throw new ArgumentNullException ("key");
639                                         
640                                 ArrayList al = new ArrayList ();
641                                 
642                                 foreach (Control c in list) {
643                                         if (c.Name.Equals (key, StringComparison.CurrentCultureIgnoreCase))
644                                                 al.Add (c);
645                                                 
646                                         if (searchAllChildren)
647                                                 al.AddRange (c.Controls.Find (key, true));
648                                 }
649                                 
650                                 return (Control[])al.ToArray (typeof (Control));
651                         }
652
653                         public int GetChildIndex(Control child) {
654                                 return GetChildIndex(child, false);
655                         }
656
657                         public virtual int GetChildIndex(Control child, bool throwException) {
658                                 int index;
659
660                                 index=list.IndexOf(child);
661
662                                 if (index==-1 && throwException) {
663                                         throw new ArgumentException("Not a child control", "child");
664                                 }
665                                 return index;
666                         }
667
668                         public override IEnumerator
669                         GetEnumerator () {
670                                 return new ControlCollectionEnumerator (list);
671                         }
672
673                         internal IEnumerator GetAllEnumerator () {
674                                 Control [] res = GetAllControls ();
675                                 return res.GetEnumerator ();
676                         }
677
678                         internal ArrayList ImplicitControls {
679                                 get { return impl_list; }
680                         }
681                         
682                         internal Control [] GetAllControls () {
683                                 if (all_controls != null)
684                                         return all_controls;
685
686                                 if (impl_list == null) {
687                                         all_controls = (Control []) list.ToArray (typeof (Control));
688                                         return all_controls;
689                                 }
690                                 
691                                 all_controls = new Control [list.Count + impl_list.Count];
692                                 impl_list.CopyTo (all_controls);
693                                 list.CopyTo (all_controls, impl_list.Count);
694
695                                 return all_controls;
696                         }
697
698                         public int IndexOf (Control control)
699                         {
700                                 return list.IndexOf (control);
701                         }
702
703                         public virtual int IndexOfKey (string key)
704                         {
705                                 if (string.IsNullOrEmpty (key))
706                                         return -1;
707                                         
708                                 for (int i = 0; i < list.Count; i++)
709                                         if (((Control)list[i]).Name.Equals (key, StringComparison.CurrentCultureIgnoreCase))
710                                                 return i;
711                                                 
712                                 return -1;
713                         }
714
715                         public virtual void Remove (Control value)
716                         {
717                                 if (value == null || !list.Contains(value))
718                                         return;
719
720                                 all_controls = null;
721                                 list.Remove(value);
722
723                                 owner.PerformLayout(value, "Parent");
724                                 owner.OnControlRemoved(new ControlEventArgs(value));
725
726                                 ContainerControl container = owner.InternalGetContainerControl ();
727                                 if (container != null) { 
728                                         // Inform any container controls about the loss of a child control
729                                         // so that they can update their active control
730                                         container.ChildControlRemoved (value);
731                                 }
732
733                                 value.ChangeParent(null);
734
735                                 owner.UpdateChildrenZOrder();
736                         }
737
738                         internal virtual void RemoveImplicit (Control control)
739                         {
740                                 if (impl_list != null) {
741                                         all_controls = null;
742                                         impl_list.Remove (control);
743                                         owner.PerformLayout (control, "Parent");
744                                         owner.OnControlRemoved (new ControlEventArgs (control));
745                                 }
746                                 control.ChangeParent (null);
747                                 owner.UpdateChildrenZOrder ();
748                         }
749
750                         public void RemoveAt (int index)
751                         {
752                                 if (index < 0 || index >= list.Count)
753                                         throw new ArgumentOutOfRangeException("index", index, "ControlCollection does not have that many controls");
754
755                                 Remove ((Control) list [index]);
756                         }
757
758                         public virtual void RemoveByKey (string key)
759                         {
760                                 int index = IndexOfKey (key);
761                                 
762                                 if (index >= 0)
763                                         RemoveAt (index);
764                         }
765
766                         public virtual void SetChildIndex(Control child, int newIndex)
767                         {
768                                 if (child == null)
769                                         throw new ArgumentNullException ("child");
770
771                                 int     old_index;
772
773                                 old_index=list.IndexOf(child);
774                                 if (old_index==-1) {
775                                         throw new ArgumentException("Not a child control", "child");
776                                 }
777
778                                 if (old_index==newIndex) {
779                                         return;
780                                 }
781
782                                 all_controls = null;
783                                 list.RemoveAt(old_index);
784
785                                 if (newIndex>list.Count) {
786                                         list.Add(child);
787                                 } else {
788                                         list.Insert(newIndex, child);
789                                 }
790                                 child.UpdateZOrder();
791                                 owner.PerformLayout();
792                         }
793
794                         #endregion // ControlCollection Private Instance Methods
795
796                         #region ControlCollection Interface Properties
797
798                         #endregion // ControlCollection Interface Properties
799
800                         #region ControlCollection Interface Methods
801
802                         int IList.Add (object control)
803                         {
804                                 if (!(control is Control))
805                                         throw new ArgumentException ("Object of type Control required", "control");
806
807                                 if (control == null)
808                                         throw new ArgumentException ("control", "Cannot add null controls");
809
810                                 this.Add ((Control)control);
811                                 return this.IndexOf ((Control)control);
812                         }
813
814                         void IList.Remove (object control)
815                         {
816                                 if (!(control is Control))
817                                         throw new ArgumentException ("Object of type Control required", "control");
818
819                                 this.Remove ((Control)control);
820                         }
821
822                         Object ICloneable.Clone ()
823                         {
824                                 ControlCollection clone = new ControlCollection (this.owner);
825                                 clone.list = (ArrayList)list.Clone ();          // FIXME: Do we need this?
826                                 return clone;
827                         }
828
829                         #endregion // ControlCollection Interface Methods
830                 
831                         internal class ControlCollectionEnumerator : IEnumerator
832                         {
833                                 private ArrayList list;
834                                 int position = -1;
835                                 
836                                 public ControlCollectionEnumerator (ArrayList collection)
837                                 {
838                                         list = collection;
839                                 }
840                                 
841                                 #region IEnumerator Members
842                                 public object Current {
843                                         get {
844                                                 try {
845                                                         return list[position];
846                                                 } catch (IndexOutOfRangeException) {
847                                                         throw new InvalidOperationException ();
848                                                 }
849                                         }
850                                 }
851
852                                 public bool MoveNext ()
853                                 {
854                                         position++;
855                                         return (position < list.Count);
856                                 }
857
858                                 public void Reset ()
859                                 {
860                                         position = -1;
861                                 }
862
863                                 #endregion
864                         }
865                 }
866                 #endregion      // ControlCollection Class
867                 
868                 #region Public Constructors
869                 public Control ()
870                 {
871                         if (WindowsFormsSynchronizationContext.AutoInstall)
872                                 if (!(SynchronizationContext.Current is WindowsFormsSynchronizationContext))
873                                         SynchronizationContext.SetSynchronizationContext (new WindowsFormsSynchronizationContext ());
874
875                         layout_type = LayoutType.Anchor;
876                         anchor_style = AnchorStyles.Top | AnchorStyles.Left;
877
878                         is_created = false;
879                         is_visible = true;
880                         is_captured = false;
881                         is_disposed = false;
882                         is_enabled = true;
883                         is_entered = false;
884                         layout_pending = false;
885                         is_toplevel = false;
886                         causes_validation = true;
887                         has_focus = false;
888                         layout_suspended = 0;
889                         mouse_clicks = 1;
890                         tab_index = -1;
891                         cursor = null;
892                         right_to_left = RightToLeft.Inherit;
893                         border_style = BorderStyle.None;
894                         background_color = Color.Empty;
895                         dist_right = 0;
896                         dist_bottom = 0;
897                         tab_stop = true;
898                         ime_mode = ImeMode.Inherit;
899                         use_compatible_text_rendering = true;
900                         show_keyboard_cues = false;
901                         show_focus_cues = SystemInformation.MenuAccessKeysUnderlined;
902                         use_wait_cursor = false;
903
904                         backgroundimage_layout = ImageLayout.Tile;
905                         use_compatible_text_rendering = Application.use_compatible_text_rendering;
906                         padding = this.DefaultPadding;
907                         maximum_size = new Size();
908                         minimum_size = new Size();
909                         margin = this.DefaultMargin;
910                         auto_size_mode = AutoSizeMode.GrowOnly;
911
912                         control_style = ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | 
913                                         ControlStyles.Selectable | ControlStyles.StandardClick | 
914                                         ControlStyles.StandardDoubleClick;
915                         control_style |= ControlStyles.UseTextForAccessibility;
916
917                         parent = null;
918                         background_image = null;
919                         text = string.Empty;
920                         name = string.Empty;
921
922                         window_target = new ControlWindowTarget(this);
923                         window = new ControlNativeWindow(this);
924                         child_controls = CreateControlsInstance();
925                         
926                         bounds.Size = DefaultSize;
927                         client_size = ClientSizeFromSize (bounds.Size);
928                         client_rect = new Rectangle (Point.Empty, client_size);
929                         explicit_bounds = bounds;
930                 }
931
932                 public Control (Control parent, string text) : this()
933                 {
934                         Text=text;
935                         Parent=parent;
936                 }
937
938                 public Control (Control parent, string text, int left, int top, int width, int height) : this()
939                 {
940                         Parent=parent;
941                         SetBounds(left, top, width, height, BoundsSpecified.All);
942                         Text=text;
943                 }
944
945                 public Control (string text) : this()
946                 {
947                         Text=text;
948                 }
949
950                 public Control (string text, int left, int top, int width, int height) : this()
951                 {
952                         SetBounds(left, top, width, height, BoundsSpecified.All);
953                         Text=text;
954                 }
955
956                 private delegate void RemoveDelegate(object c);
957
958                 protected override void Dispose (bool disposing)
959                 {
960                         if (!is_disposed && disposing) {
961                                 is_disposing = true;
962                                 Capture = false;
963
964                                 DisposeBackBuffer ();
965
966                                 if (this.InvokeRequired) {
967                                         if (Application.MessageLoop && IsHandleCreated) {
968                                                 this.BeginInvokeInternal(new MethodInvoker(DestroyHandle), null);
969                                         }
970                                 } else {
971                                         DestroyHandle();
972                                 }
973
974                                 if (parent != null)
975                                         parent.Controls.Remove(this);
976
977                                 Control [] children = child_controls.GetAllControls ();
978                                 for (int i=0; i<children.Length; i++) {
979                                         children[i].parent = null;      // Need to set to null or our child will try and remove from ourselves and crash
980                                         children[i].Dispose();
981                                 }
982                         }
983                         is_disposed = true;
984                         base.Dispose(disposing);
985                 }
986                 #endregion      // Public Constructors
987
988                 #region Internal Properties
989
990                 internal Rectangle PaddingClientRectangle
991                 {
992                         get {
993                                 return new Rectangle (
994                                         ClientRectangle.Left   + padding.Left,
995                                         ClientRectangle.Top    + padding.Top, 
996                                         ClientRectangle.Width  - padding.Horizontal, 
997                                         ClientRectangle.Height - padding.Vertical);
998                         }
999                 }
1000
1001                 private MenuTracker active_tracker;
1002                 
1003                 internal MenuTracker ActiveTracker {
1004                         get { return active_tracker; }
1005                         set {
1006                                 if (value == active_tracker)
1007                                         return;
1008
1009                                 Capture = value != null;
1010                                 active_tracker = value;
1011                         }
1012                 }
1013
1014                 // Control is currently selected, like Focused, except maintains state
1015                 // when Form loses focus
1016                 internal bool InternalSelected {
1017                         get {
1018                                 IContainerControl container;
1019                         
1020                                 container = GetContainerControl();
1021                                 
1022                                 if (container != null && container.ActiveControl == this)
1023                                         return true;
1024                                         
1025                                 return false;
1026                         }
1027                 }
1028
1029                 // Looks for focus in child controls
1030                 // and also in the implicit ones
1031                 internal bool InternalContainsFocus {
1032                         get {
1033                                 IntPtr focused_window;
1034
1035                                 focused_window = XplatUI.GetFocus();
1036                                 if (IsHandleCreated) {
1037                                         if (focused_window == Handle)
1038                                                 return true;
1039
1040                                         foreach (Control child_control in child_controls.GetAllControls ())
1041                                                 if (child_control.InternalContainsFocus)
1042                                                         return true;
1043                                 }
1044
1045                                 return false;
1046                         }
1047                 }
1048                 
1049                 // Mouse is currently within the control's bounds
1050                 internal bool Entered {
1051                         get { return this.is_entered; }
1052                 }
1053
1054                 internal bool VisibleInternal {
1055                         get { return is_visible; }
1056                 }
1057
1058                 internal LayoutType ControlLayoutType {
1059                         get { return layout_type; }
1060                 }
1061
1062                 internal BorderStyle InternalBorderStyle {
1063                         get {
1064                                 return border_style;
1065                         }
1066
1067                         set {
1068                                 if (!Enum.IsDefined (typeof (BorderStyle), value))
1069                                         throw new InvalidEnumArgumentException (string.Format("Enum argument value '{0}' is not valid for BorderStyle", value));
1070
1071                                 if (border_style != value) {
1072                                         border_style = value;
1073
1074                                         if (IsHandleCreated) {
1075                                                 XplatUI.SetBorderStyle (window.Handle, (FormBorderStyle)border_style);
1076                                                 RecreateHandle ();
1077                                                 Refresh ();
1078                                         } else
1079                                                 client_size = ClientSizeFromSize (bounds.Size);
1080                                 }
1081                         }
1082                 }
1083                 
1084                 internal Size InternalClientSize { set { this.client_size = value; } }
1085                 internal virtual bool ActivateOnShow { get { return true; } }
1086                 internal Rectangle ExplicitBounds { get { return this.explicit_bounds; } set { this.explicit_bounds = value; } }
1087
1088                 internal bool ValidationFailed { 
1089                         get { 
1090                                 ContainerControl c = InternalGetContainerControl ();
1091                                 if (c != null)
1092                                         return c.validation_failed;
1093                                 return false;
1094                         }
1095                         set { 
1096                                 ContainerControl c = InternalGetContainerControl ();
1097                                 if (c != null)
1098                                         c.validation_failed = value; 
1099                         }
1100                 }
1101                 #endregion      // Internal Properties
1102
1103                 #region Private & Internal Methods
1104                 
1105                 void IDropTarget.OnDragDrop (DragEventArgs drgEvent)
1106                 {
1107                         OnDragDrop (drgEvent);
1108                 }
1109                 
1110                 void IDropTarget.OnDragEnter (DragEventArgs drgEvent)
1111                 {
1112                         OnDragEnter (drgEvent);
1113                 }
1114                 
1115                 void IDropTarget.OnDragLeave (EventArgs e)
1116                 {
1117                         OnDragLeave (e);
1118                 }
1119
1120                 void IDropTarget.OnDragOver (DragEventArgs drgEvent)
1121                 {
1122                         OnDragOver (drgEvent);
1123                 }
1124
1125                 internal IAsyncResult BeginInvokeInternal (Delegate method, object [] args) {
1126                         return BeginInvokeInternal (method, args, FindControlToInvokeOn ());
1127                 }
1128
1129                 internal IAsyncResult BeginInvokeInternal (Delegate method, object [] args, Control control) {
1130                         AsyncMethodResult       result;
1131                         AsyncMethodData         data;
1132
1133                         result = new AsyncMethodResult ();
1134                         data = new AsyncMethodData ();
1135
1136                         data.Handle = control.GetInvokableHandle ();
1137                         data.Method = method;
1138                         data.Args = args;
1139                         data.Result = result;
1140
1141                         if (!ExecutionContext.IsFlowSuppressed ()) {
1142                                 data.Context = ExecutionContext.Capture ();
1143                         }
1144
1145                         XplatUI.SendAsyncMethod (data);
1146                         return result;
1147                 }
1148
1149                 // The CheckForIllegalCrossThreadCalls in the #if 2.0 of
1150                 // Control.Handle throws an exception when we are trying
1151                 // to get the Handle to properly invoke on.  This avoids that.
1152                 private IntPtr GetInvokableHandle ()
1153                 {
1154                         if (!IsHandleCreated)
1155                                 CreateHandle ();
1156
1157                         return window.Handle;
1158                 }
1159
1160                 internal void PointToClient (ref int x, ref int y) {
1161                         XplatUI.ScreenToClient (Handle, ref x, ref y);
1162                 }
1163
1164                 internal void PointToScreen (ref int x, ref int y) {
1165                         XplatUI.ClientToScreen (Handle, ref x, ref y);
1166                 }
1167
1168                 internal bool IsRecreating {
1169                         get {
1170                                 return is_recreating;
1171                         }
1172                 }
1173
1174                 internal Graphics DeviceContext {
1175                         get { return Hwnd.GraphicsContext; }
1176                 }
1177
1178                 // An internal way to have a fixed height
1179                 // Basically for DataTimePicker 2.0
1180                 internal virtual int OverrideHeight (int height)
1181                 {
1182                         return height;
1183                 }
1184                 
1185                 private void ProcessActiveTracker (ref Message m)
1186                 {
1187                         bool is_up = ((Msg) m.Msg == Msg.WM_LBUTTONUP) ||
1188                                                  ((Msg) m.Msg == Msg.WM_RBUTTONUP);
1189                         
1190                         MouseButtons mb = FromParamToMouseButtons ((int) m.WParam.ToInt32 ());
1191                         
1192                         // We add in the button that was released (not sent in WParam)
1193                         if (is_up) {
1194                                 switch ((Msg)m.Msg) {
1195                                 case Msg.WM_LBUTTONUP:
1196                                         mb |= MouseButtons.Left;
1197                                         break;
1198                                 case Msg.WM_RBUTTONUP:
1199                                         mb |= MouseButtons.Right;
1200                                         break;
1201                                 }
1202                         }
1203                         
1204                         MouseEventArgs args = new MouseEventArgs (
1205                                 mb,
1206                                 mouse_clicks,
1207                                 Control.MousePosition.X,
1208                                 Control.MousePosition.Y,
1209                                 0);
1210
1211                         if (is_up) {
1212                                 active_tracker.OnMouseUp (args);
1213                                 mouse_clicks = 1;
1214                         } else {
1215                                 if (!active_tracker.OnMouseDown (args)) {
1216                                         Control control = GetRealChildAtPoint (Cursor.Position);
1217                                         if (control != null) {
1218                                                 Point pt = control.PointToClient (Cursor.Position);
1219                                                 XplatUI.SendMessage (control.Handle, 
1220                                                         (Msg)m.Msg, 
1221                                                         m.WParam, 
1222                                                         MakeParam (pt.X, pt.Y));
1223                                         }
1224                                 }
1225                         }
1226                 }
1227
1228                 private Control FindControlToInvokeOn ()
1229                 {
1230                         Control p = this;
1231                         do {
1232                                 if (p.IsHandleCreated)
1233                                         break;
1234                                 p = p.parent;
1235                         } while (p != null);
1236
1237                         if (p == null || !p.IsHandleCreated)
1238                                 throw new InvalidOperationException ("Cannot call Invoke or BeginInvoke on a control until the window handle is created");
1239                         
1240                         return p;
1241                 }
1242
1243                 private void InvalidateBackBuffer () {
1244                         if (backbuffer != null)
1245                                 backbuffer.Invalidate ();
1246                 }
1247
1248                 private DoubleBuffer GetBackBuffer () {
1249                         if (backbuffer == null)
1250                                 backbuffer = new DoubleBuffer (this);
1251                         return backbuffer;
1252                 }
1253
1254                 private void DisposeBackBuffer () {
1255                         if (backbuffer != null) {
1256                                 backbuffer.Dispose ();
1257                                 backbuffer = null;
1258                         }
1259                 }
1260
1261                 internal static void SetChildColor(Control parent) {
1262                         Control child;
1263
1264                         for (int i=0; i < parent.child_controls.Count; i++) {
1265                                 child=parent.child_controls[i];
1266                                 if (child.child_controls.Count>0) {
1267                                         SetChildColor(child);
1268                                 }
1269                         }
1270                 }
1271
1272                 internal bool Select(Control control) {
1273                         IContainerControl       container;
1274
1275                         if (control == null) {
1276                                 return false;
1277                         }
1278
1279                         container = GetContainerControl();
1280                         if (container != null && (Control)container != control) {
1281                                 container.ActiveControl = control;
1282                                 if (container.ActiveControl == control && !control.has_focus && control.IsHandleCreated)
1283                                         XplatUI.SetFocus(control.window.Handle);
1284                         }
1285                         else if (control.IsHandleCreated) {
1286                                 XplatUI.SetFocus(control.window.Handle);
1287                         }
1288                         return true;
1289                 }
1290
1291                 internal virtual void DoDefaultAction() {
1292                         // Only here to be overriden by our actual controls; this is needed by the accessibility class
1293                 }
1294
1295                 internal static IntPtr MakeParam (int low, int high){
1296                         return new IntPtr (high << 16 | low & 0xffff);
1297                 }
1298
1299                 internal static int LowOrder (int param) {
1300                         return ((int)(short)(param & 0xffff));
1301                 }
1302
1303                 internal static int HighOrder (long param) {
1304                         return ((int)(short)(param >> 16));
1305                 }
1306
1307                 // This method exists so controls overriding OnPaintBackground can have default background painting done
1308                 internal virtual void PaintControlBackground (PaintEventArgs pevent) {
1309
1310                         bool tbstyle_flat = ((CreateParams.Style & (int) ToolBarStyles.TBSTYLE_FLAT) != 0);
1311
1312                         // If we have transparent background
1313                         if (((BackColor.A != 0xff) && GetStyle(ControlStyles.SupportsTransparentBackColor)) || tbstyle_flat) {
1314                                 if (parent != null) {
1315                                         PaintEventArgs  parent_pe;
1316                                         GraphicsState   state;
1317
1318                                         parent_pe = new PaintEventArgs(pevent.Graphics, new Rectangle(pevent.ClipRectangle.X + Left, pevent.ClipRectangle.Y + Top, pevent.ClipRectangle.Width, pevent.ClipRectangle.Height));
1319
1320                                         state = parent_pe.Graphics.Save();
1321                                         parent_pe.Graphics.TranslateTransform(-Left, -Top);
1322                                         parent.OnPaintBackground(parent_pe);
1323                                         parent_pe.Graphics.Restore(state);
1324
1325                                         state = parent_pe.Graphics.Save();
1326                                         parent_pe.Graphics.TranslateTransform(-Left, -Top);
1327                                         parent.OnPaint(parent_pe);
1328                                         parent_pe.Graphics.Restore(state);
1329                                         parent_pe.SetGraphics(null);
1330                                 }
1331                         }
1332
1333                         if ((clip_region != null) && (XplatUI.UserClipWontExposeParent)) {
1334                                 if (parent != null) {
1335                                         PaintEventArgs  parent_pe;
1336                                         Region          region;
1337                                         GraphicsState   state;
1338                                         Hwnd            hwnd;
1339
1340                                         hwnd = Hwnd.ObjectFromHandle(Handle);
1341
1342                                         if (hwnd != null) {
1343                                                 parent_pe = new PaintEventArgs(pevent.Graphics, new Rectangle(pevent.ClipRectangle.X + Left, pevent.ClipRectangle.Y + Top, pevent.ClipRectangle.Width, pevent.ClipRectangle.Height));
1344
1345                                                 region = new Region ();
1346                                                 region.MakeEmpty();
1347                                                 region.Union(ClientRectangle);
1348
1349                                                 foreach (Rectangle r in hwnd.ClipRectangles) {
1350                                                         region.Union (r);
1351                                                 }
1352
1353                                                 state = parent_pe.Graphics.Save();
1354                                                 parent_pe.Graphics.Clip = region;
1355
1356                                                 parent_pe.Graphics.TranslateTransform(-Left, -Top);
1357                                                 parent.OnPaintBackground(parent_pe);
1358                                                 parent_pe.Graphics.Restore(state);
1359
1360                                                 state = parent_pe.Graphics.Save();
1361                                                 parent_pe.Graphics.Clip = region;
1362
1363                                                 parent_pe.Graphics.TranslateTransform(-Left, -Top);
1364                                                 parent.OnPaint(parent_pe);
1365                                                 parent_pe.Graphics.Restore(state);
1366                                                 parent_pe.SetGraphics(null);
1367
1368                                                 region.Intersect(clip_region);
1369                                                 pevent.Graphics.Clip = region;
1370                                         }
1371                                 }
1372                         }
1373
1374                         if (background_image == null) {
1375                                 if (!tbstyle_flat) {
1376                                         Rectangle paintRect = pevent.ClipRectangle;
1377                                         Brush pen = ThemeEngine.Current.ResPool.GetSolidBrush(BackColor);
1378                                         pevent.Graphics.FillRectangle(pen, paintRect);
1379                                 }
1380                                 return;
1381                         }
1382
1383                         DrawBackgroundImage (pevent.Graphics);
1384                 }
1385
1386                 void DrawBackgroundImage (Graphics g) {
1387                         Rectangle drawing_rectangle = new Rectangle ();
1388                         g.FillRectangle (ThemeEngine.Current.ResPool.GetSolidBrush (BackColor), ClientRectangle);
1389                                 
1390                         switch (backgroundimage_layout)
1391                         {
1392                         case ImageLayout.Tile:
1393                                 using (TextureBrush b = new TextureBrush (background_image, WrapMode.Tile)) {
1394                                         g.FillRectangle (b, ClientRectangle);
1395                                 }
1396                                 return;
1397                         case ImageLayout.Center:
1398                                 drawing_rectangle.Location = new Point (ClientSize.Width / 2 - background_image.Width / 2, ClientSize.Height / 2 - background_image.Height / 2);
1399                                 drawing_rectangle.Size = background_image.Size;
1400                                 break;
1401                         case ImageLayout.None:
1402                                 drawing_rectangle.Location = Point.Empty;
1403                                 drawing_rectangle.Size = background_image.Size;
1404                                 break;
1405                         case ImageLayout.Stretch:
1406                                 drawing_rectangle = ClientRectangle;
1407                                 break;
1408                         case ImageLayout.Zoom:
1409                                 drawing_rectangle = ClientRectangle;
1410                                 if ((float)background_image.Width / (float)background_image.Height < (float)drawing_rectangle.Width / (float) drawing_rectangle.Height) {
1411                                         drawing_rectangle.Width = (int) (background_image.Width * ((float)drawing_rectangle.Height / (float)background_image.Height));
1412                                         drawing_rectangle.X = (ClientRectangle.Width - drawing_rectangle.Width) / 2;
1413                                 } else {
1414                                         drawing_rectangle.Height = (int) (background_image.Height * ((float)drawing_rectangle.Width / (float)background_image.Width));
1415                                         drawing_rectangle.Y = (ClientRectangle.Height - drawing_rectangle.Height) / 2;
1416                                 }
1417                                 break;
1418                         default:
1419                                 return;
1420                         }
1421
1422                         g.DrawImage (background_image, drawing_rectangle);
1423
1424                 }
1425
1426                 internal virtual void DndEnter (DragEventArgs e) {
1427                         try {
1428                                 OnDragEnter (e);
1429                         } catch { }
1430                 }
1431
1432                 internal virtual void DndOver (DragEventArgs e) {
1433                         try {
1434                                 OnDragOver (e);
1435                         } catch { }
1436                 }
1437
1438                 internal virtual void DndDrop (DragEventArgs e) {
1439                         try {
1440                                 OnDragDrop (e);
1441                         } catch (Exception exc) {
1442                                 Console.Error.WriteLine ("MWF: Exception while dropping:");
1443                                 Console.Error.WriteLine (exc);
1444                         }
1445                 }
1446
1447                 internal virtual void DndLeave (EventArgs e) {
1448                         try {
1449                                 OnDragLeave (e);
1450                         } catch { }
1451                 }
1452
1453                 internal virtual void DndFeedback(GiveFeedbackEventArgs e) {
1454                         try {
1455                                 OnGiveFeedback(e);
1456                         } catch { }
1457                 }
1458
1459                 internal virtual void DndContinueDrag(QueryContinueDragEventArgs e) {
1460                         try {
1461                                 OnQueryContinueDrag(e);
1462                         } catch { }
1463                 }
1464                 
1465                 internal static MouseButtons FromParamToMouseButtons (long param) {             
1466                         MouseButtons buttons = MouseButtons.None;
1467                                         
1468                         if ((param & (long) MsgButtons.MK_LBUTTON) != 0)
1469                                 buttons |= MouseButtons.Left;
1470
1471                         if ((param & (long)MsgButtons.MK_MBUTTON) != 0)
1472                                 buttons |= MouseButtons.Middle;
1473
1474                         if ((param & (long)MsgButtons.MK_RBUTTON) != 0)
1475                                 buttons |= MouseButtons.Right;
1476                                 
1477                         return buttons;
1478                 }
1479
1480                 internal virtual void FireEnter () {
1481                         OnEnter (EventArgs.Empty);
1482                 }
1483
1484                 internal virtual void FireLeave () {
1485                         OnLeave (EventArgs.Empty);
1486                 }
1487
1488                 internal virtual void FireValidating (CancelEventArgs ce) {
1489                         OnValidating (ce);
1490                 }
1491
1492                 internal virtual void FireValidated () {
1493                         OnValidated (EventArgs.Empty);
1494                 }
1495
1496                 internal virtual bool ProcessControlMnemonic(char charCode) {
1497                         return ProcessMnemonic(charCode);
1498                 }
1499
1500                 private static Control FindFlatForward(Control container, Control start) {
1501                         Control found;
1502                         int     index;
1503                         int     end;
1504                         bool hit;
1505
1506                         found = null;
1507                         end = container.child_controls.Count;
1508                         hit = false;
1509
1510                         if (start != null) {
1511                                 index = start.tab_index;
1512                         } else {
1513                                 index = -1;
1514                         }
1515
1516                         for (int i = 0; i < end; i++) {
1517                                 if (start == container.child_controls[i]) {
1518                                         hit = true;
1519                                         continue;
1520                                 }
1521
1522                                 if (found == null || found.tab_index > container.child_controls[i].tab_index) {
1523                                         if (container.child_controls[i].tab_index > index || (hit && container.child_controls[i].tab_index == index)) {
1524                                                 found = container.child_controls[i];
1525                                         }
1526                                 }
1527                         }
1528                         return found;
1529                 }
1530
1531                 private static Control FindControlForward(Control container, Control start) {
1532                         Control found;
1533
1534                         found = null;
1535
1536                         if (start == null) {
1537                                 return FindFlatForward(container, start);
1538                         }
1539
1540                         if (start.child_controls != null && start.child_controls.Count > 0 && 
1541                                 (start == container || !((start is IContainerControl) &&  start.GetStyle(ControlStyles.ContainerControl)))) {
1542                                 return FindControlForward(start, null);
1543                         }
1544                         else {
1545                                 while (start != container) {
1546                                         found = FindFlatForward(start.parent, start);
1547                                         if (found != null) {
1548                                                 return found;
1549                                         }
1550                                         start = start.parent;
1551                                 }
1552                         }
1553                         return null;
1554                 }
1555
1556                 private static Control FindFlatBackward(Control container, Control start) {
1557                         Control found;
1558                         int     index;
1559                         int     end;
1560                         bool hit;
1561
1562                         found = null;
1563                         end = container.child_controls.Count;
1564                         hit = false;
1565
1566                         if (start != null) {
1567                                 index = start.tab_index;
1568                         } else {
1569                                 index = int.MaxValue;
1570                         }
1571
1572                         for (int i = end - 1; i >= 0; i--) {
1573                                 if (start == container.child_controls[i]) {
1574                                         hit = true;
1575                                         continue;
1576                                 }
1577
1578                                 if (found == null || found.tab_index < container.child_controls[i].tab_index) {
1579                                         if (container.child_controls[i].tab_index < index || (hit && container.child_controls[i].tab_index == index))
1580                                                 found = container.child_controls[i];
1581
1582                                 }
1583                         }
1584                         return found;
1585                 }
1586
1587                 private static Control FindControlBackward(Control container, Control start) {
1588
1589                         Control found = null;
1590
1591                         if (start == null) {
1592                                 found = FindFlatBackward(container, start);
1593                         }
1594                         else if (start != container) {
1595                                 if (start.parent != null) {
1596                                         found = FindFlatBackward(start.parent, start);
1597
1598                                         if (found == null) {
1599                                                 if (start.parent != container)
1600                                                         return start.parent;
1601                                                 return null;
1602                                         }
1603                                 }
1604                         }
1605                 
1606                         if (found == null || start.parent == null)
1607                                 found = start;
1608
1609                         while (found != null && (found == container || (!((found is IContainerControl) && found.GetStyle(ControlStyles.ContainerControl))) &&
1610                                 found.child_controls != null && found.child_controls.Count > 0)) {
1611 //                              while (ctl.child_controls != null && ctl.child_controls.Count > 0 && 
1612 //                                      (ctl == this || (!((ctl is IContainerControl) && ctl.GetStyle(ControlStyles.ContainerControl))))) {
1613                                 found = FindFlatBackward(found, null);
1614                         }
1615
1616                         return found;
1617
1618 /*
1619                         Control found;
1620
1621                         found = null;
1622
1623                         if (start != null) {
1624                                 found = FindFlatBackward(start.parent, start);
1625                                 if (found == null) {
1626                                         if (start.parent != container) {
1627                                                 return start.parent;
1628                                         }
1629                                 }
1630                         }
1631                         if (found == null) {
1632                                 found = FindFlatBackward(container, start);
1633                         }
1634
1635                         if (container != start) {
1636                                 while ((found != null) && (!found.Contains(start)) && found.child_controls != null && found.child_controls.Count > 0 && !(found is IContainerControl)) {// || found.GetStyle(ControlStyles.ContainerControl))) {
1637                                         found = FindControlBackward(found, null);
1638                                          if (found != null) {
1639                                                 return found;
1640                                         }
1641                                 }
1642                         }
1643                         return found;
1644 */                      
1645                 }
1646
1647                 internal virtual void HandleClick(int clicks, MouseEventArgs me) {
1648                         bool standardclick = GetStyle (ControlStyles.StandardClick);
1649                         bool standardclickclick = GetStyle (ControlStyles.StandardDoubleClick);
1650                         if ((clicks > 1) && standardclick && standardclickclick) {
1651                                 OnDoubleClick (me);
1652                                 OnMouseDoubleClick (me);
1653                         } else if (clicks == 1 && standardclick && !ValidationFailed) {
1654                                 OnClick (me);
1655                                 OnMouseClick (me);
1656                         }
1657                 }
1658                 
1659                 internal void CaptureWithConfine (Control ConfineWindow) {
1660                         if (this.IsHandleCreated && !is_captured) {
1661                                 is_captured = true;
1662                                 XplatUI.GrabWindow (this.window.Handle, ConfineWindow.Handle);
1663                         }
1664                 }
1665
1666                 private void CheckDataBindings () {
1667                         if (data_bindings == null)
1668                                 return;
1669
1670                         foreach (Binding binding in data_bindings) {
1671                                 binding.Check ();
1672                         }
1673                 }
1674
1675                 private void ChangeParent(Control new_parent) {
1676                         bool            pre_enabled;
1677                         bool            pre_visible;
1678                         Font            pre_font;
1679                         Color           pre_fore_color;
1680                         Color           pre_back_color;
1681                         RightToLeft     pre_rtl;
1682
1683                         // These properties are inherited from our parent
1684                         // Get them pre parent-change and then send events
1685                         // if they are changed after we have our new parent
1686                         pre_enabled = Enabled;
1687                         pre_visible = Visible;
1688                         pre_font = Font;
1689                         pre_fore_color = ForeColor;
1690                         pre_back_color = BackColor;
1691                         pre_rtl = RightToLeft;
1692                         // MS doesn't seem to send a CursorChangedEvent
1693
1694                         parent = new_parent;
1695
1696                         Form frm = this as Form;
1697                         if (frm != null) {
1698                                 frm.ChangingParent (new_parent);
1699                         } else if (IsHandleCreated) {
1700                                 IntPtr parent_handle = IntPtr.Zero;
1701                                 if (new_parent != null && new_parent.IsHandleCreated)
1702                                         parent_handle = new_parent.Handle;
1703                                 XplatUI.SetParent (Handle, parent_handle);
1704                         }
1705                         
1706                         OnParentChanged(EventArgs.Empty);
1707
1708                         if (pre_enabled != Enabled) {
1709                                 OnEnabledChanged(EventArgs.Empty);
1710                         }
1711
1712                         if (pre_visible != Visible) {
1713                                 OnVisibleChanged(EventArgs.Empty);
1714                         }
1715
1716                         if (pre_font != Font) {
1717                                 OnFontChanged(EventArgs.Empty);
1718                         }
1719
1720                         if (pre_fore_color != ForeColor) {
1721                                 OnForeColorChanged(EventArgs.Empty);
1722                         }
1723
1724                         if (pre_back_color != BackColor) {
1725                                 OnBackColorChanged(EventArgs.Empty);
1726                         }
1727
1728                         if (pre_rtl != RightToLeft) {
1729                                 // MS sneaks a OnCreateControl and OnHandleCreated in here, I guess
1730                                 // because when RTL changes they have to recreate the win32 control
1731                                 // We don't really need that (until someone runs into compatibility issues)
1732                                 OnRightToLeftChanged(EventArgs.Empty);
1733                         }
1734
1735                         if ((new_parent != null) && new_parent.Created && is_visible && !Created) {
1736                                 CreateControl();
1737                         }
1738
1739                         if ((binding_context == null) && Created) {
1740                                 OnBindingContextChanged(EventArgs.Empty);
1741                         }
1742                 }
1743
1744                 // Sometimes we need to do this calculation without it being virtual (constructor)
1745                 internal Size InternalSizeFromClientSize (Size clientSize)
1746                 {
1747                         Rectangle ClientRect;
1748                         Rectangle WindowRect;
1749                         CreateParams cp;
1750
1751                         ClientRect = new Rectangle (0, 0, clientSize.Width, clientSize.Height);
1752                         cp = this.CreateParams;
1753
1754                         if (XplatUI.CalculateWindowRect (ref ClientRect, cp, null, out WindowRect))
1755                                 return new Size (WindowRect.Width, WindowRect.Height);
1756
1757                         return Size.Empty;
1758                 }
1759                 
1760                 internal Size ClientSizeFromSize (Size size)
1761                 {
1762                         // Calling this gives us the difference in Size and ClientSize.
1763                         // We just have to apply that difference to our given size.
1764                         Size client_size = this.InternalSizeFromClientSize (size);
1765                         
1766                         if (client_size == Size.Empty)
1767                                 return Size.Empty;
1768                                 
1769                         return new Size (size.Width - (client_size.Width - size.Width), size.Height - (client_size.Height - size.Height));
1770                 }
1771                 
1772                 internal CreateParams GetCreateParams ()
1773                 {
1774                         return CreateParams;
1775                 }
1776
1777                 internal virtual Size GetPreferredSizeCore (Size proposedSize)
1778                 {
1779                         return this.explicit_bounds.Size;
1780                 }
1781
1782                 private void UpdateDistances() {
1783                         if (parent != null) {
1784                                 if (bounds.Width >= 0)
1785                                         dist_right = parent.ClientSize.Width - bounds.X - bounds.Width;
1786                                 if (bounds.Height >= 0)
1787                                         dist_bottom = parent.ClientSize.Height - bounds.Y - bounds.Height;
1788
1789                                 recalculate_distances = false;
1790                         }
1791                 }
1792                 
1793                 private Cursor GetAvailableCursor ()
1794                 {
1795                         if (Cursor != null && Enabled) {
1796                                 return Cursor;
1797                         }
1798
1799                         if (Parent != null) {
1800                                 return Parent.GetAvailableCursor ();
1801                         }
1802
1803                         return Cursors.Default;
1804                 }
1805                 
1806                 private void UpdateCursor ()
1807                 {
1808                         if (!IsHandleCreated)
1809                                 return;
1810                         
1811                         if (!Enabled) {
1812                                 XplatUI.SetCursor (window.Handle, GetAvailableCursor ().handle);
1813                                 return;
1814                         }
1815
1816                         Point pt = PointToClient (Cursor.Position);
1817
1818                         if (!bounds.Contains (pt) && !Capture)
1819                                 return;
1820
1821                         if (cursor != null || use_wait_cursor) {
1822                                 XplatUI.SetCursor (window.Handle, Cursor.handle);
1823                         } else {
1824                                 XplatUI.SetCursor (window.Handle, GetAvailableCursor ().handle);
1825                         }
1826                 }
1827                 
1828                 private bool UseDoubleBuffering {
1829                         get {
1830                                 if (!ThemeEngine.Current.DoubleBufferingSupported)
1831                                         return false;
1832
1833                                 // Since many of .Net's controls are unmanaged, they are doublebuffered
1834                                 // even though their bits may not be set in managed land.  This allows
1835                                 // us to doublebuffer as well without affecting public style bits.
1836                                 if (force_double_buffer)
1837                                         return true;
1838                                         
1839                                 if (DoubleBuffered)
1840                                         return true;
1841                                 return (control_style & ControlStyles.DoubleBuffer) != 0;
1842                         }
1843                 }
1844
1845                 internal void OnSizeInitializedOrChanged ()
1846                 {
1847                         Form form = this as Form;
1848                         if (form != null && form.WindowManager != null)
1849                                 ThemeEngine.Current.ManagedWindowOnSizeInitializedOrChanged (form);
1850                 }
1851                 #endregion      // Private & Internal Methods
1852
1853                 #region Public Static Properties
1854                 public static Color DefaultBackColor {
1855                         get {
1856                                 return ThemeEngine.Current.DefaultControlBackColor;
1857                         }
1858                 }
1859
1860                 public static Font DefaultFont {
1861                         get {
1862                                 return ThemeEngine.Current.DefaultFont;
1863                         }
1864                 }
1865
1866                 public static Color DefaultForeColor {
1867                         get {
1868                                 return ThemeEngine.Current.DefaultControlForeColor;
1869                         }
1870                 }
1871
1872                 public static Keys ModifierKeys {
1873                         get {
1874                                 return XplatUI.State.ModifierKeys;
1875                         }
1876                 }
1877
1878                 public static MouseButtons MouseButtons {
1879                         get {
1880                                 return XplatUI.State.MouseButtons;
1881                         }
1882                 }
1883
1884                 public static Point MousePosition {
1885                         get {
1886                                 return Cursor.Position;
1887                         }
1888                 }
1889                 
1890                 [EditorBrowsable (EditorBrowsableState.Advanced)]
1891                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
1892                 [Browsable (false)]
1893                 [MonoTODO ("Stub, value is not used")]
1894                 public static bool CheckForIllegalCrossThreadCalls 
1895                 {
1896                         get {
1897                                 return verify_thread_handle;
1898                         }
1899
1900                         set {
1901                                 verify_thread_handle = value;
1902                         }
1903                 }
1904                 #endregion      // Public Static Properties
1905
1906                 #region Public Instance Properties
1907                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1908                 [Browsable(false)]
1909                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1910                 public AccessibleObject AccessibilityObject {
1911                         get {
1912                                 if (accessibility_object==null) {
1913                                         accessibility_object=CreateAccessibilityInstance();
1914                                 }
1915                                 return accessibility_object;
1916                         }
1917                 }
1918
1919                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1920                 [Browsable(false)]
1921                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1922                 public string AccessibleDefaultActionDescription {
1923                         get {
1924                                 return accessible_default_action;
1925                         }
1926
1927                         set {
1928                                 accessible_default_action = value;
1929                         }
1930                 }
1931
1932                 [Localizable(true)]
1933                 [DefaultValue(null)]
1934                 [MWFCategory("Accessibility")]
1935                 public string AccessibleDescription {
1936                         get {
1937                                 return accessible_description;
1938                         }
1939
1940                         set {
1941                                 accessible_description = value;
1942                         }
1943                 }
1944
1945                 [Localizable(true)]
1946                 [DefaultValue(null)]
1947                 [MWFCategory("Accessibility")]
1948                 public string AccessibleName {
1949                         get {
1950                                 return accessible_name;
1951                         }
1952
1953                         set {
1954                                 accessible_name = value;
1955                         }
1956                 }
1957
1958                 [DefaultValue(AccessibleRole.Default)]
1959                 [MWFDescription("Role of the control"), MWFCategory("Accessibility")]
1960                 public AccessibleRole AccessibleRole {
1961                         get {
1962                                 return accessible_role;
1963                         }
1964
1965                         set {
1966                                 accessible_role = value;
1967                         }
1968                 }
1969
1970                 [DefaultValue(false)]
1971                 [MWFCategory("Behavior")]
1972                 public virtual bool AllowDrop {
1973                         get {
1974                                 return allow_drop;
1975                         }
1976
1977                         set {
1978                                 if (allow_drop == value)
1979                                         return;
1980                                 allow_drop = value;
1981                                 if (IsHandleCreated) {
1982                                         UpdateStyles();
1983                                         XplatUI.SetAllowDrop (Handle, value);
1984                                 }
1985                         }
1986                 }
1987
1988                 [Localizable(true)]
1989                 [RefreshProperties(RefreshProperties.Repaint)]
1990                 [DefaultValue(AnchorStyles.Top | AnchorStyles.Left)]
1991                 [MWFCategory("Layout")]
1992                 public virtual AnchorStyles Anchor {
1993                         get {
1994                                 return anchor_style;
1995                         }
1996
1997                         set {
1998                                 layout_type = LayoutType.Anchor;
1999
2000                                 if (anchor_style == value)
2001                                         return;
2002                                         
2003                                 anchor_style=value;
2004                                 dock_style = DockStyle.None;
2005                                 
2006                                 UpdateDistances ();
2007
2008                                 if (parent != null)
2009                                         parent.PerformLayout(this, "Anchor");
2010                         }
2011                 }
2012
2013                 [Browsable (false)]
2014                 [DefaultValue (typeof (Point), "0, 0")]
2015                 [EditorBrowsable (EditorBrowsableState.Advanced)]
2016                 public virtual Point AutoScrollOffset {
2017                         get {
2018                                 return auto_scroll_offset;
2019                         }
2020
2021                         set {
2022                                 this.auto_scroll_offset = value;
2023                         }
2024                 }
2025                         
2026                 // XXX: Implement me!
2027                 bool auto_size;
2028                 
2029                 [RefreshProperties (RefreshProperties.All)]
2030                 [Localizable (true)]
2031                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2032                 [Browsable (false)]
2033                 [EditorBrowsable (EditorBrowsableState.Never)]
2034                 [DefaultValue (false)]
2035                 public virtual bool AutoSize {
2036                         get { return auto_size; }
2037                         set {
2038                                 if (this.auto_size != value) {
2039                                         auto_size = value;
2040                                         
2041                                         // If we're turning this off, reset our size
2042                                         if (!value) {
2043                                                 Size = explicit_bounds.Size;
2044                                         } else {
2045                                                 if (Parent != null)
2046                                                         Parent.PerformLayout (this, "AutoSize");
2047                                         }
2048
2049                                         OnAutoSizeChanged (EventArgs.Empty);
2050                                 }
2051                         }
2052                 }
2053                 
2054                 [AmbientValue ("{Width=0, Height=0}")]
2055                 [MWFCategory("Layout")]
2056                 public virtual Size MaximumSize {
2057                         get {
2058                                 return maximum_size;
2059                         }
2060                         set {
2061                                 if (maximum_size != value) {
2062                                         maximum_size = value;
2063                                         Size = PreferredSize;
2064                                 }
2065                         }
2066                 }
2067
2068                 internal bool ShouldSerializeMaximumSize ()
2069                 {
2070                         return this.MaximumSize != DefaultMaximumSize;
2071                 }
2072
2073                 [MWFCategory("Layout")]
2074                 public virtual Size MinimumSize {
2075                         get {
2076                                 return minimum_size;
2077                         }
2078                         set {
2079                                 if (minimum_size != value) {
2080                                         minimum_size = value;
2081                                         Size = PreferredSize;
2082                                 }
2083                         }
2084                 }
2085
2086                 internal bool ShouldSerializeMinimumSize ()
2087                 {
2088                         return this.MinimumSize != DefaultMinimumSize;
2089                 }
2090
2091                 [DispId(-501)]
2092                 [MWFCategory("Appearance")]
2093                 public virtual Color BackColor {
2094                         get {
2095                                 if (background_color.IsEmpty) {
2096                                         if (parent!=null) {
2097                                                 Color pcolor = parent.BackColor;
2098                                                 if (pcolor.A == 0xff || GetStyle(ControlStyles.SupportsTransparentBackColor))
2099                                                         return pcolor;
2100                                         }
2101                                         return DefaultBackColor;
2102                                 }
2103                                 return background_color;
2104                         }
2105
2106                         set {
2107                                 if (!value.IsEmpty && (value.A != 0xff) && !GetStyle(ControlStyles.SupportsTransparentBackColor)) {
2108                                         throw new ArgumentException("Transparent background colors are not supported on this control");
2109                                 }
2110
2111                                 if (background_color != value) {
2112                                         background_color=value;
2113                                         SetChildColor(this);
2114                                         OnBackColorChanged(EventArgs.Empty);
2115                                         Invalidate();
2116                                 }
2117                         }
2118                 }
2119
2120                 internal bool ShouldSerializeBackColor ()
2121                 {
2122                         return this.BackColor != DefaultBackColor;
2123                 }
2124
2125                 [Localizable(true)]
2126                 [DefaultValue(null)]
2127                 [MWFCategory("Appearance")]
2128                 public virtual Image BackgroundImage {
2129                         get {
2130                                 return background_image;
2131                         }
2132
2133                         set {
2134                                 if (background_image!=value) {
2135                                         background_image=value;
2136                                         OnBackgroundImageChanged(EventArgs.Empty);
2137                                         Invalidate ();
2138                                 }
2139                         }
2140                 }
2141
2142                 [DefaultValue (ImageLayout.Tile)]
2143                 [Localizable (true)]
2144                 [MWFCategory("Appearance")]
2145                 public virtual ImageLayout BackgroundImageLayout {
2146                         get {
2147                                 return backgroundimage_layout;
2148                         }
2149                         set {
2150                                 if (Array.IndexOf (Enum.GetValues (typeof (ImageLayout)), value) == -1)
2151                                         throw new InvalidEnumArgumentException ("value", (int) value, typeof(ImageLayout));
2152
2153                                 if (value != backgroundimage_layout) {
2154                                         backgroundimage_layout = value;
2155                                         Invalidate ();
2156                                         OnBackgroundImageLayoutChanged (EventArgs.Empty);
2157                                 }
2158                                 
2159                         }
2160                 } 
2161
2162                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2163                 [Browsable(false)]
2164                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2165                 public virtual BindingContext BindingContext {
2166                         get {
2167                                 if (binding_context != null)
2168                                         return binding_context;
2169                                 if (Parent == null)
2170                                         return null;
2171                                 binding_context = Parent.BindingContext;
2172                                 return binding_context;
2173                         }
2174                         set {
2175                                 if (binding_context != value) {
2176                                         binding_context = value;
2177                                         OnBindingContextChanged(EventArgs.Empty);
2178                                 }
2179                         }
2180                 }
2181
2182                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2183                 [Browsable(false)]
2184                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2185                 public int Bottom {
2186                         get {
2187                                 return this.bounds.Bottom;
2188                         }
2189                 }
2190
2191                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2192                 [Browsable(false)]
2193                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2194                 public Rectangle Bounds {
2195                         get {
2196                                 return this.bounds;
2197                         }
2198
2199                         set {
2200                                 SetBounds(value.Left, value.Top, value.Width, value.Height, BoundsSpecified.All);
2201                         }
2202                 }
2203
2204                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2205                 [Browsable(false)]
2206                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2207                 public bool CanFocus {
2208                         get {
2209                                 if (IsHandleCreated && Visible && Enabled) {
2210                                         return true;
2211                                 }
2212                                 return false;
2213                         }
2214                 }
2215
2216                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2217                 [Browsable(false)]
2218                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2219                 public bool CanSelect {
2220                         get {
2221                                 Control parent;
2222
2223                                 if (!GetStyle(ControlStyles.Selectable)) {
2224                                         return false;
2225                                 }
2226
2227                                 parent = this;
2228                                 while (parent != null) {
2229                                         if (!parent.is_visible || !parent.is_enabled) {
2230                                                 return false;
2231                                         }
2232
2233                                         parent = parent.parent;
2234                                 }
2235                                 return true;
2236                         }
2237                 }
2238
2239                 internal virtual bool InternalCapture {
2240                         get {
2241                                 return Capture;
2242                         }
2243
2244                         set {
2245                                 Capture = value;
2246                         }
2247                 }
2248
2249                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2250                 [Browsable(false)]
2251                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2252                 public bool Capture {
2253                         get {
2254                                 return this.is_captured;
2255                         }
2256
2257                         set {
2258                                 // Call OnMouseCaptureChanged when we get WM_CAPTURECHANGED.
2259                                 if (value != is_captured) {
2260                                         if (value) {
2261                                                 is_captured = true;
2262                                                 XplatUI.GrabWindow(Handle, IntPtr.Zero);
2263                                         } else {
2264                                                 if (IsHandleCreated)
2265                                                         XplatUI.UngrabWindow(Handle);
2266                                                 is_captured = false;
2267                                         }
2268                                 }
2269                         }
2270                 }
2271
2272                 [DefaultValue(true)]
2273                 [MWFCategory("Focus")]
2274                 public bool CausesValidation {
2275                         get {
2276                                 return this.causes_validation;
2277                         }
2278
2279                         set {
2280                                 if (this.causes_validation != value) {
2281                                         causes_validation = value;
2282                                         OnCausesValidationChanged(EventArgs.Empty);
2283                                 }
2284                         }
2285                 }
2286
2287                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2288                 [Browsable(false)]
2289                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2290                 public Rectangle ClientRectangle {
2291                         get {
2292                                 client_rect.Width = client_size.Width;
2293                                 client_rect.Height = client_size.Height;
2294                                 return client_rect;
2295                         }
2296                 }
2297
2298                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2299                 [Browsable(false)]
2300                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2301                 public Size ClientSize {
2302                         get {
2303 #if notneeded
2304                                 if ((this is Form) && (((Form)this).form_parent_window != null)) {
2305                                         return ((Form)this).form_parent_window.ClientSize;
2306                                 }
2307 #endif
2308
2309                                 return client_size;
2310                         }
2311
2312                         set {
2313                                 this.SetClientSizeCore(value.Width, value.Height);
2314                                 this.OnClientSizeChanged (EventArgs.Empty);
2315                         }
2316                 }
2317
2318                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2319                 [Browsable(false)]
2320                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2321                 [DescriptionAttribute("ControlCompanyNameDescr")]
2322                 public String CompanyName {
2323                         get {
2324                                 return "Mono Project, Novell, Inc.";
2325                         }
2326                 }
2327
2328                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2329                 [Browsable(false)]
2330                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2331                 public bool ContainsFocus {
2332                         get {
2333                                 IntPtr focused_window;
2334
2335                                 focused_window = XplatUI.GetFocus();
2336                                 if (IsHandleCreated) {
2337                                         if (focused_window == Handle) {
2338                                                 return true;
2339                                         }
2340
2341                                         for (int i=0; i < child_controls.Count; i++) {
2342                                                 if (child_controls[i].ContainsFocus) {
2343                                                         return true;
2344                                                 }
2345                                         }
2346                                 }
2347                                 return false;
2348                         }
2349                 }
2350                 [Browsable (false)]
2351                 [DefaultValue(null)]
2352                 [MWFCategory("Behavior")]
2353                 public virtual ContextMenu ContextMenu {
2354                         get {
2355                                 return ContextMenuInternal;
2356                         }
2357
2358                         set {
2359                                 ContextMenuInternal = value;
2360                         }
2361                 }
2362
2363                 internal virtual ContextMenu ContextMenuInternal {
2364                         get {
2365                                 return context_menu;
2366                         }
2367                         set {
2368                                 if (context_menu != value) {
2369                                         context_menu = value;
2370                                         OnContextMenuChanged (EventArgs.Empty);
2371                                 }
2372                         }
2373                 }
2374
2375                 [DefaultValue (null)]
2376                 [MWFCategory("Behavior")]
2377                 public virtual ContextMenuStrip ContextMenuStrip {
2378                         get { return this.context_menu_strip; }
2379                         set { 
2380                                 if (this.context_menu_strip != value) {
2381                                         this.context_menu_strip = value;
2382                                         if (value != null)
2383                                                 value.container = this;
2384                                         OnContextMenuStripChanged (EventArgs.Empty);
2385                                 }
2386                         }
2387                 }
2388
2389                 [Browsable(false)]
2390                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
2391                 public ControlCollection Controls {
2392                         get {
2393                                 return this.child_controls;
2394                         }
2395                 }
2396
2397                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2398                 [Browsable(false)]
2399                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2400                 public bool Created {
2401                         get {
2402                                 return (!is_disposed && is_created);
2403                         }
2404                 }
2405                 
2406                 [AmbientValue(null)]
2407                 [MWFCategory("Appearance")]
2408                 public virtual Cursor Cursor {
2409                         get {
2410                                 if (use_wait_cursor)
2411                                         return Cursors.WaitCursor;
2412
2413                                 if (cursor != null) {
2414                                         return cursor;
2415                                 }
2416
2417                                 if (parent != null) {
2418                                         return parent.Cursor;
2419                                 }
2420
2421                                 return Cursors.Default;
2422                         }
2423
2424                         set {
2425                                 if (cursor == value) {
2426                                         return;
2427                                 }
2428
2429                                 cursor = value;
2430                                 UpdateCursor ();
2431
2432                                 OnCursorChanged (EventArgs.Empty);
2433                         }
2434                 }
2435
2436                 internal bool ShouldSerializeCursor ()
2437                 {
2438                         return this.Cursor != Cursors.Default;
2439                 }
2440
2441                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
2442                 [ParenthesizePropertyName(true)]
2443                 [RefreshProperties(RefreshProperties.All)]
2444                 [MWFCategory("Data")]
2445                 public ControlBindingsCollection DataBindings {
2446                         get {
2447                                 if (data_bindings == null)
2448                                         data_bindings = new ControlBindingsCollection (this);
2449                                 return data_bindings;
2450                         }
2451                 }
2452
2453                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2454                 [Browsable(false)]
2455                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2456                 public virtual Rectangle DisplayRectangle {
2457                         get {
2458                                 // for the control class the DisplayRectangle == ClientRectangle
2459                                 return ClientRectangle;
2460                         }
2461                 }
2462
2463                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2464                 [Browsable(false)]
2465                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2466                 public bool Disposing {
2467                         get {
2468                                 return is_disposed;
2469                         }
2470                 }
2471
2472                 [Localizable(true)]
2473                 [RefreshProperties(RefreshProperties.Repaint)]
2474                 [DefaultValue(DockStyle.None)]
2475                 [MWFCategory("Layout")]
2476                 public virtual DockStyle Dock {
2477                         get {
2478                                 return dock_style;
2479                         }
2480
2481                         set {
2482                                 // If the user sets this to None, we need to still use Anchor layout
2483                                 if (value != DockStyle.None)
2484                                         layout_type = LayoutType.Dock;
2485
2486                                 if (dock_style == value) {
2487                                         return;
2488                                 }
2489
2490                                 if (!Enum.IsDefined (typeof (DockStyle), value)) {
2491                                         throw new InvalidEnumArgumentException ("value", (int) value,
2492                                                 typeof (DockStyle));
2493                                 }
2494
2495                                 dock_style = value;
2496                                 anchor_style = AnchorStyles.Top | AnchorStyles.Left;
2497
2498                                 if (dock_style == DockStyle.None) {
2499                                         bounds = explicit_bounds;
2500                                         layout_type = LayoutType.Anchor;
2501                                 }
2502
2503                                 if (parent != null)
2504                                         parent.PerformLayout(this, "Dock");
2505                                 else if (Controls.Count > 0)
2506                                         PerformLayout ();
2507
2508                                 OnDockChanged(EventArgs.Empty);
2509                         }
2510                 }
2511
2512                 protected virtual bool DoubleBuffered {
2513                         get {
2514                                 return (control_style & ControlStyles.OptimizedDoubleBuffer) != 0;
2515                         }
2516
2517                         set {
2518                                 if (value == DoubleBuffered)
2519                                         return;
2520                                 if (value) {
2521                                         SetStyle (ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);
2522                                 } else {
2523                                         SetStyle (ControlStyles.OptimizedDoubleBuffer, false);
2524                                 }
2525                                 
2526                         }
2527                 }
2528                 
2529                 public void DrawToBitmap (Bitmap bitmap, Rectangle targetBounds)
2530                 {
2531                         Graphics g = Graphics.FromImage (bitmap);
2532                         
2533                         // Only draw within the target bouds, and up to the size of the control
2534                         g.IntersectClip (targetBounds);
2535                         g.IntersectClip (Bounds);
2536                         
2537                         // Logic copied from WmPaint
2538                         PaintEventArgs pea = new PaintEventArgs (g, targetBounds);
2539                         
2540                         if (!GetStyle (ControlStyles.Opaque))
2541                                 OnPaintBackground (pea);
2542
2543                         OnPaintBackgroundInternal (pea);
2544
2545                         OnPaintInternal (pea);
2546
2547                         if (!pea.Handled)
2548                                 OnPaint (pea);
2549                         
2550                         g.Dispose ();
2551                 }
2552                 
2553                 [DispId(-514)]
2554                 [Localizable(true)]
2555                 [MWFCategory("Behavior")]
2556                 public bool Enabled {
2557                         get {
2558                                 if (!is_enabled) {
2559                                         return false;
2560                                 }
2561
2562                                 if (parent != null) {
2563                                         return parent.Enabled;
2564                                 }
2565
2566                                 return true;
2567                         }
2568
2569                         set {
2570                                 if (this.is_enabled == value)
2571                                         return;
2572
2573                                 bool old_value = is_enabled;
2574
2575                                 is_enabled = value;
2576
2577                                 if (!value)
2578                                         UpdateCursor ();
2579
2580                                 if (old_value != value && !value && this.has_focus)
2581                                         SelectNextControl(this, true, true, true, true);
2582
2583                                 OnEnabledChanged (EventArgs.Empty);
2584                         }
2585                 }
2586
2587                 internal bool ShouldSerializeEnabled ()
2588                 {
2589                         return this.Enabled != true;
2590                 }
2591
2592                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2593                 [Browsable(false)]
2594                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2595                 public virtual bool Focused {
2596                         get {
2597                                 return this.has_focus;
2598                         }
2599                 }
2600
2601                 [DispId(-512)]
2602                 [AmbientValue(null)]
2603                 [Localizable(true)]
2604                 [MWFCategory("Appearance")]
2605                 public virtual Font Font {
2606                         [return: MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof (Font))]
2607                         get {
2608                                 if (font != null)
2609                                         return font;
2610
2611                                 if (parent != null) {
2612                                         Font f = parent.Font;
2613                                         
2614                                         if (f != null)
2615                                                 return f;
2616                                 }
2617
2618                                 return DefaultFont;
2619                         }
2620
2621                         [param:MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(Font))]
2622                         set {
2623                                 if (font != null && font == value) {
2624                                         return;
2625                                 }
2626
2627                                 font = value;
2628                                 Invalidate();
2629                                 OnFontChanged (EventArgs.Empty);
2630                                 PerformLayout ();
2631                         }
2632                 }
2633
2634                 internal bool ShouldSerializeFont ()
2635                 {
2636                         return !this.Font.Equals (DefaultFont);
2637                 }
2638
2639                 [DispId(-513)]
2640                 [MWFCategory("Appearance")]
2641                 public virtual Color ForeColor {
2642                         get {
2643                                 if (foreground_color.IsEmpty) {
2644                                         if (parent!=null) {
2645                                                 return parent.ForeColor;
2646                                         }
2647                                         return DefaultForeColor;
2648                                 }
2649                                 return foreground_color;
2650                         }
2651
2652                         set {
2653                                 if (foreground_color != value) {
2654                                         foreground_color=value;
2655                                         Invalidate();
2656                                         OnForeColorChanged(EventArgs.Empty);
2657                                 }
2658                         }
2659                 }
2660
2661                 internal bool ShouldSerializeForeColor ()
2662                 {
2663                         return this.ForeColor != DefaultForeColor;
2664                 }
2665
2666                 [DispId(-515)]
2667                 [Browsable(false)]
2668                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2669                 public IntPtr Handle {                                                  // IWin32Window
2670                         get {
2671                                 if (verify_thread_handle) {
2672                                         if (this.InvokeRequired) {
2673                                                 throw new InvalidOperationException("Cross-thread access of handle detected. Handle access only valid on thread that created the control");
2674                                         }
2675                                 }
2676                                 if (!IsHandleCreated) {
2677                                         CreateHandle();
2678                                 }
2679                                 return window.Handle;
2680                         }
2681                 }
2682
2683                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2684                 [Browsable(false)]
2685                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2686                 public bool HasChildren {
2687                         get {
2688                                 if (this.child_controls.Count>0) {
2689                                         return true;
2690                                 }
2691                                 return false;
2692                         }
2693                 }
2694
2695                 [EditorBrowsable(EditorBrowsableState.Always)]
2696                 [Browsable(false)]
2697                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2698                 public int Height {
2699                         get { return this.bounds.Height; }
2700                         set { SetBounds(bounds.X, bounds.Y, bounds.Width, value, BoundsSpecified.Height); }
2701                 }
2702                 
2703                 [AmbientValue(ImeMode.Inherit)]
2704                 [Localizable(true)]
2705                 [MWFCategory("Behavior")]
2706                 public ImeMode ImeMode {
2707                         get {
2708                                 if (ime_mode == ImeMode.Inherit) {
2709                                         if (parent != null)
2710                                                 return parent.ImeMode;
2711                                         else
2712                                                 return ImeMode.NoControl; // default value
2713                                 }
2714                                 return ime_mode;
2715                         }
2716
2717                         set {
2718                                 if (ime_mode != value) {
2719                                         ime_mode = value;
2720
2721                                         OnImeModeChanged(EventArgs.Empty);
2722                                 }
2723                         }
2724                 }
2725
2726                 internal bool ShouldSerializeImeMode ()
2727                 {
2728                         return this.ImeMode != ImeMode.NoControl;
2729                 }
2730
2731                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2732                 [Browsable(false)]
2733                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2734                 public bool InvokeRequired {                                            // ISynchronizeInvoke
2735                         get {
2736                                 if (creator_thread != null && creator_thread!=Thread.CurrentThread) {
2737                                         return true;
2738                                 }
2739                                 return false;
2740                         }
2741                 }
2742
2743                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2744                 [Browsable(false)]
2745                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2746                 public bool IsAccessible {
2747                         get {
2748                                 return is_accessible;
2749                         }
2750
2751                         set {
2752                                 is_accessible = value;
2753                         }
2754                 }
2755
2756                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2757                 [Browsable(false)]
2758                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2759                 public bool IsDisposed {
2760                         get {
2761                                 return this.is_disposed;
2762                         }
2763                 }
2764
2765                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2766                 [Browsable(false)]
2767                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2768                 public bool IsHandleCreated {
2769                         get {
2770                                 if (window == null || window.Handle == IntPtr.Zero)
2771                                         return false;
2772
2773                                 Hwnd hwnd = Hwnd.ObjectFromHandle (window.Handle);
2774                                 if (hwnd != null && hwnd.zombie)
2775                                         return false;
2776
2777                                 return true;
2778                         }
2779                 }
2780
2781                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2782                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2783                 [Browsable(false)]
2784                 [MonoNotSupported ("RTL is not supported")]
2785                 public bool IsMirrored {
2786                         get { return false; }
2787                 }
2788
2789                 [Browsable (false)]
2790                 [EditorBrowsable (EditorBrowsableState.Advanced)]
2791                 public virtual Layout.LayoutEngine LayoutEngine {
2792                         get {
2793                                 if (layout_engine == null)
2794                                         layout_engine = new Layout.DefaultLayout ();
2795                                 return layout_engine;
2796                         }
2797                 }
2798
2799                 [EditorBrowsable(EditorBrowsableState.Always)]
2800                 [Browsable(false)]
2801                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2802                 public int Left {
2803                         get {
2804                                 return this.bounds.Left;
2805                         }
2806
2807                         set {
2808                                 SetBounds(value, bounds.Y, bounds.Width, bounds.Height, BoundsSpecified.X);
2809                         }
2810                 }
2811
2812                 [Localizable(true)]
2813                 [MWFCategory("Layout")]
2814                 public Point Location {
2815                         get {
2816                                 return this.bounds.Location;
2817                         }
2818
2819                         set {
2820                                 SetBounds(value.X, value.Y, bounds.Width, bounds.Height, BoundsSpecified.Location);
2821                         }
2822                 }
2823
2824                 internal bool ShouldSerializeLocation ()
2825                 {
2826                         return this.Location != new Point (0, 0);
2827                 }
2828
2829                 [Localizable (true)]
2830                 [MWFCategory("Layout")]
2831                 public Padding Margin {
2832                         get { return this.margin; }
2833                         set { 
2834                                 if (this.margin != value) {
2835                                         this.margin = value; 
2836                                         if (Parent != null)
2837                                                 Parent.PerformLayout (this, "Margin");
2838                                         OnMarginChanged (EventArgs.Empty);
2839                                 }
2840                         }
2841                 }
2842
2843                 internal bool ShouldSerializeMargin ()
2844                 {
2845                         return this.Margin != DefaultMargin;
2846                 }
2847
2848                 [Browsable(false)]
2849                 public string Name {
2850                         get {
2851                                 return name;
2852                         }
2853
2854                         set {
2855                                 name = value;
2856                         }
2857                 }
2858
2859                 [Localizable(true)]
2860                 [MWFCategory("Layout")]
2861                 public Padding Padding {
2862                         get {
2863                                 return padding;
2864                         }
2865
2866                         set {
2867                                 if (padding != value) {
2868                                         padding = value;
2869                                         OnPaddingChanged (EventArgs.Empty);
2870                                         
2871                                         // Changing padding generally requires a new size
2872                                         if (this.AutoSize && this.Parent != null)
2873                                                 parent.PerformLayout (this, "Padding");
2874                                         else
2875                                                 PerformLayout (this, "Padding");
2876                                 }
2877                         }
2878                 }
2879
2880                 internal bool ShouldSerializePadding ()
2881                 {
2882                         return this.Padding != DefaultPadding;
2883                 }
2884
2885                 [Browsable(false)]
2886                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2887                 public Control Parent {
2888                         get {
2889                                 return this.parent;
2890                         }
2891
2892                         set {
2893                                 if (value == this) {
2894                                         throw new ArgumentException("A circular control reference has been made. A control cannot be owned or parented to itself.");
2895                                 }
2896
2897                                 if (parent!=value) {
2898                                         if (value==null) {
2899                                                 parent.Controls.Remove(this);
2900                                                 parent = null;
2901                                                 return;
2902                                         }
2903
2904                                         value.Controls.Add(this);
2905                                 }
2906                         }
2907                 }
2908
2909                 [Browsable (false)]
2910                 public Size PreferredSize {
2911                         get { return this.GetPreferredSize (Size.Empty); }
2912                 }
2913
2914                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2915                 [Browsable(false)]
2916                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2917                 public string ProductName {
2918                         get {
2919                                 Type t = typeof (AssemblyProductAttribute);
2920                                 Assembly assembly = GetType().Module.Assembly;
2921                                 object [] attrs = assembly.GetCustomAttributes (t, false);
2922                                 AssemblyProductAttribute a = null;
2923                                 // On MS we get a NullRefException if product attribute is not
2924                                 // set. 
2925                                 if (attrs != null && attrs.Length > 0)
2926                                         a = (AssemblyProductAttribute) attrs [0];
2927                                 if (a == null) {
2928                                         return GetType ().Namespace;
2929                                 }
2930                                 return a.Product;
2931                         }
2932                 }
2933
2934                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2935                 [Browsable(false)]
2936                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2937                 public string ProductVersion {
2938                         get {
2939                                 Type t = typeof (AssemblyVersionAttribute);
2940                                 Assembly assembly = GetType().Module.Assembly;
2941                                 object [] attrs = assembly.GetCustomAttributes (t, false);
2942                                 if (attrs == null || attrs.Length < 1)
2943                                         return "1.0.0.0";
2944                                 return ((AssemblyVersionAttribute)attrs [0]).Version;
2945                         }
2946                 }
2947
2948                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2949                 [Browsable(false)]
2950                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2951                 public bool RecreatingHandle {
2952                         get {
2953                                 return is_recreating;
2954                         }
2955                 }
2956
2957                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2958                 [Browsable(false)]
2959                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2960                 public Region Region {
2961                         get {
2962                                 return clip_region;
2963                         }
2964
2965                         set {
2966                                 if (clip_region != value) {
2967                                         if (IsHandleCreated)
2968                                                 XplatUI.SetClipRegion(Handle, value);
2969
2970                                         clip_region = value;
2971                                         
2972                                         OnRegionChanged (EventArgs.Empty);
2973                                 }
2974                         }
2975                 }
2976
2977                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2978                 [Browsable(false)]
2979                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2980                 public int Right {
2981                         get {
2982                                 return this.bounds.Right;
2983                         }
2984                 }
2985
2986                 [AmbientValue(RightToLeft.Inherit)]
2987                 [Localizable(true)]
2988                 [MWFCategory("Appearance")]
2989                 public virtual RightToLeft RightToLeft {
2990                         get {
2991                                 if (right_to_left == RightToLeft.Inherit) {
2992                                         if (parent != null)
2993                                                 return parent.RightToLeft;
2994                                         else
2995                                                 return RightToLeft.No; // default value
2996                                 }
2997                                 return right_to_left;
2998                         }
2999
3000                         set {
3001                                 if (value != right_to_left) {
3002                                         right_to_left = value;
3003                                         OnRightToLeftChanged(EventArgs.Empty);
3004                                         PerformLayout ();
3005                                 }
3006                         }
3007                 }
3008
3009                 internal bool ShouldSerializeRightToLeft ()
3010                 {
3011                         return this.RightToLeft != RightToLeft.No;
3012                 }
3013
3014                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3015                 public override ISite Site {
3016                         get {
3017                                 return base.Site;
3018                         }
3019
3020                         set {
3021                                 base.Site = value;
3022
3023                                 if (value != null) {
3024                                         AmbientProperties ap = (AmbientProperties) value.GetService (typeof (AmbientProperties));
3025                                         if (ap != null) {
3026                                                 BackColor = ap.BackColor;
3027                                                 ForeColor = ap.ForeColor;
3028                                                 Cursor = ap.Cursor;
3029                                                 Font = ap.Font;
3030                                         }
3031                                 }
3032                         }
3033                 }
3034
3035                 internal bool ShouldSerializeSite ()
3036                 {
3037                         return false;
3038                 }
3039
3040                 [Localizable(true)]
3041                 [MWFCategory("Layout")]
3042                 public Size Size {
3043                         get {
3044                                 return new Size(Width, Height);
3045                         }
3046
3047                         set {
3048                                 SetBounds(bounds.X, bounds.Y, value.Width, value.Height, BoundsSpecified.Size);
3049                         }
3050                 }
3051
3052                 internal virtual bool ShouldSerializeSize ()
3053                 {
3054                         return this.Size != DefaultSize;
3055                 }
3056
3057                 [Localizable(true)]
3058                 [MergableProperty(false)]
3059                 [MWFCategory("Behavior")]
3060                 public int TabIndex {
3061                         get {
3062                                 if (tab_index != -1) {
3063                                         return tab_index;
3064                                 }
3065                                 return 0;
3066                         }
3067
3068                         set {
3069                                 if (tab_index != value) {
3070                                         tab_index = value;
3071                                         OnTabIndexChanged(EventArgs.Empty);
3072                                 }
3073                         }
3074                 }
3075
3076                 [DispId(-516)]
3077                 [DefaultValue(true)]
3078                 [MWFCategory("Behavior")]
3079                 public bool TabStop {
3080                         get {
3081                                 return tab_stop;
3082                         }
3083
3084                         set {
3085                                 if (tab_stop != value) {
3086                                         tab_stop = value;
3087                                         OnTabStopChanged(EventArgs.Empty);
3088                                 }
3089                         }
3090                 }
3091
3092                 [Localizable(false)]
3093                 [Bindable(true)]
3094                 [TypeConverter(typeof(StringConverter))]
3095                 [DefaultValue(null)]
3096                 [MWFCategory("Data")]
3097                 public object Tag {
3098                         get {
3099                                 return control_tag;
3100                         }
3101
3102                         set {
3103                                 control_tag = value;
3104                         }
3105                 }
3106
3107                 [DispId(-517)]
3108                 [Localizable(true)]
3109                 [BindableAttribute(true)]
3110                 [MWFCategory("Appearance")]
3111                 public virtual string Text {
3112                         get {
3113                                 // Our implementation ignores ControlStyles.CacheText - we always cache
3114                                 return this.text;
3115                         }
3116
3117                         set {
3118                                 if (value == null) {
3119                                         value = String.Empty;
3120                                 }
3121
3122                                 if (text!=value) {
3123                                         text=value;
3124                                         UpdateWindowText ();
3125                                         OnTextChanged (EventArgs.Empty);
3126
3127                                         // Label has its own AutoSize implementation
3128                                         if (AutoSize && Parent != null && (!(this is Label)))
3129                                                 Parent.PerformLayout (this, "Text");
3130                                 }
3131                         }
3132                 }
3133
3134                 internal virtual void UpdateWindowText ()
3135                 {
3136                         if (!IsHandleCreated) {
3137                                 return;
3138                         }
3139                         XplatUI.Text (Handle, text);
3140                 }
3141
3142                 [EditorBrowsable(EditorBrowsableState.Always)]
3143                 [Browsable(false)]
3144                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
3145                 public int Top {
3146                         get {
3147                                 return this.bounds.Top;
3148                         }
3149
3150                         set {
3151                                 SetBounds(bounds.X, value, bounds.Width, bounds.Height, BoundsSpecified.Y);
3152                         }
3153                 }
3154
3155                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3156                 [Browsable(false)]
3157                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
3158                 public Control TopLevelControl {
3159                         get {
3160                                 Control p = this;
3161
3162                                 while (p.parent != null) {
3163                                         p = p.parent;
3164                                 }
3165
3166                                 return p is Form ? p : null;
3167                         }
3168                 }
3169
3170                 [EditorBrowsable(EditorBrowsableState.Always)]
3171                 [Browsable(true)]
3172                 [DefaultValue (false)]
3173                 [MWFCategory("Appearance")]
3174                 public bool UseWaitCursor {
3175                         get { return use_wait_cursor; }
3176                         set {
3177                                 if (use_wait_cursor != value) {
3178                                         use_wait_cursor = value;
3179                                         UpdateCursor ();
3180                                         OnCursorChanged (EventArgs.Empty);
3181                                 }
3182                         }
3183                 }
3184
3185                 [Localizable(true)]
3186                 [MWFCategory("Behavior")]
3187                 public bool Visible {
3188                         get {
3189                                 if (!is_visible) {
3190                                         return false;
3191                                 } else if (parent != null) {
3192                                         return parent.Visible;
3193                                 }
3194
3195                                 return true;
3196                         }
3197
3198                         set {
3199                                 if (this.is_visible != value) {
3200                                         SetVisibleCore(value);
3201
3202                                         if (parent != null)
3203                                                 parent.PerformLayout (this, "Visible");
3204                                 }
3205                         }
3206                 }
3207
3208                 internal bool ShouldSerializeVisible ()
3209                 {
3210                         return this.Visible != true;
3211                 }
3212
3213                 [EditorBrowsable(EditorBrowsableState.Always)]
3214                 [Browsable(false)]
3215                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
3216                 public int Width {
3217                         get {
3218                                 return this.bounds.Width;
3219                         }
3220
3221                         set {
3222                                 SetBounds(bounds.X, bounds.Y, value, bounds.Height, BoundsSpecified.Width);
3223                         }
3224                 }
3225
3226                 [EditorBrowsable(EditorBrowsableState.Never)]
3227                 [Browsable(false)]
3228                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
3229                 public IWindowTarget WindowTarget {
3230                         get { return window_target; }
3231                         set { window_target = value; }
3232                 }
3233                 #endregion      // Public Instance Properties
3234
3235                 #region Protected Instance Properties
3236                 protected virtual bool CanEnableIme {
3237                         get { return false; }
3238                 }
3239                 
3240                 // Is only false in some ActiveX contexts
3241                 protected override bool CanRaiseEvents {
3242                         get { return true; }
3243                 }
3244
3245                 protected virtual CreateParams CreateParams {
3246                         get {
3247                                 CreateParams create_params = new CreateParams();
3248
3249                                 try {
3250                                         create_params.Caption = Text;
3251                                 }
3252                                 catch {
3253                                         create_params.Caption = text;
3254                                 }
3255
3256                                 try {
3257                                         create_params.X = Left;
3258                                 }
3259                                 catch {
3260                                         create_params.X = this.bounds.X;
3261                                 }
3262
3263                                 try {
3264                                         create_params.Y = Top;
3265                                 }
3266                                 catch {
3267                                         create_params.Y = this.bounds.Y;
3268                                 }
3269
3270                                 try {
3271                                         create_params.Width = Width;
3272                                 }
3273                                 catch {
3274                                         create_params.Width = this.bounds.Width;
3275                                 }
3276
3277                                 try {
3278                                         create_params.Height = Height;
3279                                 }
3280                                 catch {
3281                                         create_params.Height = this.bounds.Height;
3282                                 }
3283
3284
3285                                 create_params.ClassName = XplatUI.GetDefaultClassName (GetType ());
3286                                 create_params.ClassStyle = (int)(XplatUIWin32.ClassStyle.CS_OWNDC | XplatUIWin32.ClassStyle.CS_DBLCLKS);
3287                                 create_params.ExStyle = 0;
3288                                 create_params.Param = 0;
3289
3290                                 if (allow_drop) {
3291                                         create_params.ExStyle |= (int)WindowExStyles.WS_EX_ACCEPTFILES;
3292                                 }
3293
3294                                 if ((parent!=null) && (parent.IsHandleCreated)) {
3295                                         create_params.Parent = parent.Handle;
3296                                 }
3297
3298                                 create_params.Style = (int)WindowStyles.WS_CHILD | (int)WindowStyles.WS_CLIPCHILDREN | (int)WindowStyles.WS_CLIPSIBLINGS;
3299
3300                                 if (is_visible) {
3301                                         create_params.Style |= (int)WindowStyles.WS_VISIBLE;
3302                                 }
3303
3304                                 if (!is_enabled) {
3305                                         create_params.Style |= (int)WindowStyles.WS_DISABLED;
3306                                 }
3307
3308                                 switch (border_style) {
3309                                         case BorderStyle.FixedSingle:
3310                                                 create_params.Style |= (int) WindowStyles.WS_BORDER;
3311                                                 break;
3312                                         case BorderStyle.Fixed3D:
3313                                                 create_params.ExStyle |= (int) WindowExStyles.WS_EX_CLIENTEDGE;
3314                                                 break;
3315                                 }
3316                                 
3317                                 create_params.control = this;
3318
3319                                 return create_params;
3320                         }
3321                 }
3322
3323                 protected virtual Cursor DefaultCursor { get { return Cursors.Default; } }
3324
3325                 protected virtual ImeMode DefaultImeMode {
3326                         get {
3327                                 return ImeMode.Inherit;
3328                         }
3329                 }
3330
3331                 protected virtual Padding DefaultMargin {
3332                         get { return new Padding (3); }
3333                 }
3334                 
3335                 protected virtual Size DefaultMaximumSize { get { return new Size (); } }
3336                 protected virtual Size DefaultMinimumSize { get { return new Size (); } }
3337                 protected virtual Padding DefaultPadding { get { return new Padding (); } }
3338
3339                 protected virtual Size DefaultSize {
3340                         get {
3341                                 return new Size(0, 0);
3342                         }
3343                 }
3344
3345                 protected int FontHeight {
3346                         get {
3347                                 return Font.Height;
3348                         }
3349
3350                         set {
3351                                 ;; // Nothing to do
3352                         }
3353                 }
3354                 [Obsolete ()]
3355                 protected bool RenderRightToLeft {
3356                         get {
3357                                 return (this.right_to_left == RightToLeft.Yes);
3358                         }
3359                 }
3360
3361                 protected bool ResizeRedraw {
3362                         get {
3363                                 return GetStyle(ControlStyles.ResizeRedraw);
3364                         }
3365
3366                         set {
3367                                 SetStyle(ControlStyles.ResizeRedraw, value);
3368                         }
3369                 }
3370
3371                 [EditorBrowsable (EditorBrowsableState.Advanced)]
3372                 protected virtual bool ScaleChildren {
3373                         get { return ScaleChildrenInternal; }
3374                 }
3375
3376                 internal virtual bool ScaleChildrenInternal {
3377                         get { return true; }
3378                 }
3379
3380                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3381                 [Browsable(false)]
3382                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
3383                 protected internal virtual bool ShowFocusCues {
3384                         get {
3385                                 if (this is Form)
3386                                         return show_focus_cues;
3387                                         
3388                                 if (this.parent == null)
3389                                         return false;
3390                                         
3391                                 Form f = this.FindForm ();
3392                                 
3393                                 if (f != null)
3394                                         return f.show_focus_cues;
3395                                         
3396                                 return false;
3397                         }
3398                 }
3399
3400                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3401                 [Browsable(false)]
3402                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
3403                 internal virtual protected bool ShowKeyboardCues {
3404                         get {
3405                                 return ShowKeyboardCuesInternal;
3406                         }
3407                 }
3408
3409                 internal bool ShowKeyboardCuesInternal {
3410                         get {
3411                                 if (SystemInformation.MenuAccessKeysUnderlined || DesignMode)
3412                                         return true; 
3413
3414                                 return show_keyboard_cues;
3415                         }
3416                 }
3417
3418                 #endregion      // Protected Instance Properties
3419
3420                 #region Public Static Methods
3421                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3422                 public static Control FromChildHandle(IntPtr handle) {
3423                         return Control.ControlNativeWindow.ControlFromChildHandle (handle);
3424                 }
3425
3426                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3427                 public static Control FromHandle(IntPtr handle) {
3428                         return Control.ControlNativeWindow.ControlFromHandle(handle);
3429                 }
3430
3431                 [MonoTODO ("Only implemented for Win32, others always return false")]
3432                 public static bool IsKeyLocked (Keys keyVal)
3433                 {
3434                         switch (keyVal) {
3435                                 case Keys.CapsLock:
3436                                 case Keys.NumLock:
3437                                 case Keys.Scroll:
3438                                         return XplatUI.IsKeyLocked ((VirtualKeys)keyVal);
3439                                 default:
3440                                         throw new NotSupportedException ("keyVal must be CapsLock, NumLock, or ScrollLock");
3441                         }
3442                 }
3443
3444                 public static bool IsMnemonic(char charCode, string text) {
3445                         int amp;
3446
3447                         amp = text.IndexOf('&');
3448
3449                         if (amp != -1) {
3450                                 if (amp + 1 < text.Length) {
3451                                         if (text[amp + 1] != '&') {
3452                                                 if (Char.ToUpper(charCode) == Char.ToUpper(text.ToCharArray(amp + 1, 1)[0])) {
3453                                                         return true;
3454                                                 }       
3455                                         }
3456                                 }
3457                         }
3458                         return false;
3459                 }
3460                 #endregion
3461
3462                 #region Protected Static Methods
3463                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3464                 protected static bool ReflectMessage(IntPtr hWnd, ref Message m) {
3465                         Control c;
3466
3467                         c = Control.FromHandle(hWnd);
3468
3469                         if (c != null) {
3470                                 c.WndProc(ref m);
3471                                 return true;
3472                         }
3473                         return false;
3474                 }
3475                 #endregion
3476
3477                 #region Public Instance Methods
3478                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3479                 public IAsyncResult BeginInvoke(Delegate method) {
3480                         object [] prms = null;
3481                         if (method is EventHandler)
3482                                 prms = new object [] { this, EventArgs.Empty };
3483                         return BeginInvokeInternal(method, prms);
3484                 }
3485
3486                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3487                 public IAsyncResult BeginInvoke (Delegate method, params object[] args)
3488                 {
3489                         return BeginInvokeInternal (method, args);
3490                 }
3491
3492                 public void BringToFront() {
3493                         if (parent != null) {
3494                                 parent.child_controls.SetChildIndex(this, 0);
3495                         }
3496                         else if (IsHandleCreated) {
3497                                 XplatUI.SetZOrder(Handle, IntPtr.Zero, false, false);
3498                         }
3499                 }
3500
3501                 public bool Contains(Control ctl) {
3502                         while (ctl != null) {
3503                                 ctl = ctl.parent;
3504                                 if (ctl == this) {
3505                                         return true;
3506                                 }
3507                         }
3508                         return false;
3509                 }
3510
3511                 public void CreateControl () {
3512                         if (is_created) {
3513                                 return;
3514                         }
3515
3516                         if (is_disposing) {
3517                                 return;
3518                         }
3519
3520                         if (!is_visible) {
3521                                 return;
3522                         }
3523                         
3524                         if (parent != null && !parent.Created) {
3525                                 return;
3526                         }
3527
3528                         if (!IsHandleCreated) {
3529                                 CreateHandle();
3530                         }
3531
3532                         if (!is_created) {
3533                                 is_created = true;
3534
3535                                 // Create all of our children (implicit ones as well) when we are created.
3536                                 // The child should fire it's OnLoad before the parents, however
3537                                 // if the child checks Parent.Created in it's OnCreateControl, the
3538                                 // parent is already created.
3539                                 foreach (Control c in Controls.GetAllControls ())
3540                                         if (!c.Created && !c.IsDisposed)
3541                                                 c.CreateControl ();
3542                                                 
3543                                 OnCreateControl();
3544                         }
3545                 }
3546
3547                 public Graphics CreateGraphics() {
3548                         if (!IsHandleCreated) {
3549                                 this.CreateHandle();
3550                         }
3551                         return Graphics.FromHwnd(this.window.Handle);
3552                 }
3553
3554                 public DragDropEffects DoDragDrop(object data, DragDropEffects allowedEffects) {
3555                         DragDropEffects result = DragDropEffects.None;
3556                         if (IsHandleCreated)
3557                                 result = XplatUI.StartDrag(Handle, data, allowedEffects);
3558                         OnDragDropEnd (result);
3559                         return result;
3560                 }
3561
3562                 internal virtual void OnDragDropEnd (DragDropEffects effects)
3563                 {
3564                 }
3565
3566                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3567                 public object EndInvoke (IAsyncResult asyncResult) {
3568                         AsyncMethodResult result = (AsyncMethodResult) asyncResult;
3569                         return result.EndInvoke ();
3570                 }
3571
3572                 internal Control FindRootParent ()
3573                 {
3574                         Control c = this;
3575                         
3576                         while (c.Parent != null)
3577                                 c = c.Parent;
3578
3579                         return c;
3580                 }
3581
3582                 public Form FindForm() {
3583                         Control c;
3584
3585                         c = this;
3586                         while (c != null) {
3587                                 if (c is Form) {
3588                                         return (Form)c;
3589                                 }
3590                                 c = c.Parent;
3591                         }
3592                         return null;
3593                 }
3594                 [EditorBrowsable (EditorBrowsableState.Advanced)]
3595                 public bool Focus() {
3596                         return FocusInternal (false);
3597                 }
3598
3599                 internal virtual bool FocusInternal (bool skip_check) {
3600                         if (skip_check || (CanFocus && IsHandleCreated && !has_focus && !is_focusing)) {
3601                                 is_focusing = true;
3602                                 Select(this);
3603                                 is_focusing = false;
3604                         }
3605                         return has_focus;
3606                 }
3607
3608                 internal Control GetRealChildAtPoint (Point pt) {
3609                         if (!IsHandleCreated)
3610                                 CreateHandle ();
3611
3612                         foreach (Control control in child_controls.GetAllControls ()) {
3613                                 if (control.Bounds.Contains (PointToClient (pt))) {
3614                                         Control child = control.GetRealChildAtPoint (pt);
3615                                         if (child == null)
3616                                                 return control;
3617                                         else
3618                                                 return child;
3619                                 }
3620                         }
3621
3622                         return null;
3623                 }
3624
3625                 public Control GetChildAtPoint(Point pt)
3626                 {
3627                         return GetChildAtPoint (pt, GetChildAtPointSkip.None);
3628                 }
3629
3630                 public Control GetChildAtPoint (Point pt, GetChildAtPointSkip skipValue)
3631                 {
3632                         // MS's version causes the handle to be created.  The stack trace shows that get_Handle is called here, but
3633                         // we'll just call CreateHandle instead.
3634                         if (!IsHandleCreated)
3635                                 CreateHandle ();
3636
3637                         // Microsoft's version of this function doesn't seem to work, so I can't check
3638                         // if we only consider children or also grandchildren, etc.
3639                         // I'm gonna say 'children only'
3640                         foreach (Control child in Controls) {
3641                                 if ((skipValue & GetChildAtPointSkip.Disabled) == GetChildAtPointSkip.Disabled && !child.Enabled)
3642                                         continue;
3643                                 else if ((skipValue & GetChildAtPointSkip.Invisible) == GetChildAtPointSkip.Invisible && !child.Visible)
3644                                         continue;
3645                                 else if ((skipValue & GetChildAtPointSkip.Transparent) == GetChildAtPointSkip.Transparent && child.BackColor.A == 0x0)
3646                                         continue;
3647                                 else if (child.Bounds.Contains (pt))
3648                                         return child;
3649                         }
3650
3651                         return null;
3652                 }
3653
3654                 public IContainerControl GetContainerControl() {
3655                         Control current = this;
3656
3657                         while (current!=null) {
3658                                 if ((current is IContainerControl) && ((current.control_style & ControlStyles.ContainerControl)!=0)) {
3659                                         return (IContainerControl)current;
3660                                 }
3661                                 current = current.parent;
3662                         }
3663                         return null;
3664                 }
3665
3666                 internal ContainerControl InternalGetContainerControl() {
3667                         Control current = this;
3668
3669                         while (current!=null) {
3670                                 if ((current is ContainerControl) && ((current.control_style & ControlStyles.ContainerControl)!=0)) {
3671                                         return current as ContainerControl;
3672                                 }
3673                                 current = current.parent;
3674                         }
3675                         return null;
3676                 }
3677
3678                 public Control GetNextControl(Control ctl, bool forward) {
3679
3680                         if (!this.Contains(ctl)) {
3681                                 ctl = this;
3682                         }
3683
3684                         if (forward) {
3685                                 ctl = FindControlForward(this, ctl);
3686                         }
3687                         else {
3688                                 ctl = FindControlBackward(this, ctl);
3689                         }
3690
3691                         if (ctl != this) {
3692                                 return ctl;
3693                         }
3694                         return null;
3695                 }
3696
3697                 [EditorBrowsable (EditorBrowsableState.Advanced)]
3698                 public virtual Size GetPreferredSize (Size proposedSize) {
3699                         Size retsize = GetPreferredSizeCore (proposedSize);
3700                         
3701                         // If we're bigger than the MaximumSize, fix that
3702                         if (this.maximum_size.Width != 0 && retsize.Width > this.maximum_size.Width)
3703                                 retsize.Width = this.maximum_size.Width;
3704                         if (this.maximum_size.Height != 0 && retsize.Height > this.maximum_size.Height)
3705                                 retsize.Height = this.maximum_size.Height;
3706                                 
3707                         // If we're smaller than the MinimumSize, fix that
3708                         if (this.minimum_size.Width != 0 && retsize.Width < this.minimum_size.Width)
3709                                 retsize.Width = this.minimum_size.Width;
3710                         if (this.minimum_size.Height != 0 && retsize.Height < this.minimum_size.Height)
3711                                 retsize.Height = this.minimum_size.Height;
3712                                 
3713                         return retsize;
3714                 }
3715
3716                 public void Hide() {
3717                         this.Visible = false;
3718                 }
3719
3720                 public void Invalidate ()
3721                 {
3722                         Invalidate (ClientRectangle, false);
3723                 }
3724
3725                 public void Invalidate (bool invalidateChildren)
3726                 {
3727                         Invalidate (ClientRectangle, invalidateChildren);
3728                 }
3729
3730                 public void Invalidate (Rectangle rc)
3731                 {
3732                         Invalidate (rc, false);
3733                 }
3734
3735                 public void Invalidate (Rectangle rc, bool invalidateChildren)
3736                 {
3737                         // Win32 invalidates control including when Width and Height is equal 0
3738                         // or is not visible, only Paint event must be care about this.
3739                         if (!IsHandleCreated)
3740                                 return;
3741
3742                         if (rc.IsEmpty)
3743                                 rc = ClientRectangle;
3744                                 
3745                         if  (rc.Width > 0 && rc.Height > 0) {
3746
3747                                 NotifyInvalidate(rc);
3748
3749                                 XplatUI.Invalidate(Handle, rc, false);
3750
3751                                 if (invalidateChildren) {
3752                                         Control [] controls = child_controls.GetAllControls ();
3753                                         for (int i=0; i<controls.Length; i++)
3754                                                 controls [i].Invalidate ();
3755                                 } else {
3756                                         // If any of our children are transparent, we
3757                                         // have to invalidate them anyways
3758                                         foreach (Control c in Controls)
3759                                                 if (c.BackColor.A != 255)
3760                                                         c.Invalidate ();
3761                                 }
3762                         }
3763                         OnInvalidated(new InvalidateEventArgs(rc));
3764                 }
3765
3766                 public void Invalidate (Region region)
3767                 {
3768                         Invalidate (region, false);
3769                 }
3770
3771                 public void Invalidate (Region region, bool invalidateChildren)
3772                 {
3773                         using (Graphics g = CreateGraphics ()){
3774                                 RectangleF bounds = region.GetBounds (g);
3775                                 Invalidate (new Rectangle ((int) bounds.X, (int) bounds.Y, (int) bounds.Width, (int) bounds.Height), invalidateChildren);
3776                         }
3777                 }
3778
3779                 public object Invoke (Delegate method) {
3780                         object [] prms = null;
3781                         if (method is EventHandler)
3782                                 prms = new object [] { this, EventArgs.Empty };
3783
3784                         return Invoke(method, prms);
3785                 }
3786                 public object Invoke (Delegate method, params object [] args) {
3787                         Control control = FindControlToInvokeOn ();
3788                         
3789                         if (!this.InvokeRequired) {
3790                                 return method.DynamicInvoke(args);
3791                         }
3792
3793                         IAsyncResult result = BeginInvokeInternal (method, args, control);
3794                         return EndInvoke(result);
3795                 }
3796
3797                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3798                 public void PerformLayout() {
3799                         PerformLayout(null, null);
3800                 }
3801
3802                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3803                 public void PerformLayout(Control affectedControl, string affectedProperty) {
3804                         LayoutEventArgs levent = new LayoutEventArgs(affectedControl, affectedProperty);
3805
3806                         foreach (Control c in Controls.GetAllControls ())
3807                                 if (c.recalculate_distances)
3808                                         c.UpdateDistances ();
3809
3810                         if (layout_suspended > 0) {
3811                                 layout_pending = true;
3812                                 return;
3813                         }
3814                                         
3815                         layout_pending = false;
3816
3817                         // Prevent us from getting messed up
3818                         layout_suspended++;
3819
3820                         // Perform all Dock and Anchor calculations
3821                         try {
3822                                 OnLayout(levent);
3823                         }
3824
3825                                 // Need to make sure we decremend layout_suspended
3826                         finally {
3827                                 layout_suspended--;
3828                         }
3829                 }
3830
3831                 public Point PointToClient (Point p) {
3832                         int x = p.X;
3833                         int y = p.Y;
3834
3835                         XplatUI.ScreenToClient (Handle, ref x, ref y);
3836
3837                         return new Point (x, y);
3838                 }
3839
3840                 public Point PointToScreen(Point p) {
3841                         int x = p.X;
3842                         int y = p.Y;
3843
3844                         XplatUI.ClientToScreen(Handle, ref x, ref y);
3845
3846                         return new Point(x, y);
3847                 }
3848
3849                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3850                 public PreProcessControlState PreProcessControlMessage (ref Message msg)
3851                 {
3852                         return PreProcessControlMessageInternal (ref msg);
3853                 }
3854
3855                 internal PreProcessControlState PreProcessControlMessageInternal (ref Message msg)
3856                 {
3857                         switch ((Msg)msg.Msg) {
3858                                 case Msg.WM_KEYDOWN:
3859                                 case Msg.WM_SYSKEYDOWN:
3860                                         PreviewKeyDownEventArgs e = new PreviewKeyDownEventArgs ((Keys)msg.WParam.ToInt32 () | XplatUI.State.ModifierKeys);
3861                                         OnPreviewKeyDown (e);
3862                                 
3863                                         if (e.IsInputKey)
3864                                                 return PreProcessControlState.MessageNeeded;
3865                                 
3866                                         if (PreProcessMessage (ref msg))
3867                                                 return PreProcessControlState.MessageProcessed;
3868
3869                                         if (IsInputKey ((Keys)msg.WParam.ToInt32 () | XplatUI.State.ModifierKeys))
3870                                                 return PreProcessControlState.MessageNeeded;    
3871                                         
3872                                         break;
3873                                 case Msg.WM_CHAR:
3874                                 case Msg.WM_SYSCHAR:
3875                                         if (PreProcessMessage (ref msg))
3876                                                 return PreProcessControlState.MessageProcessed;
3877                                                 
3878                                         if (IsInputChar ((char)msg.WParam))
3879                                                 return PreProcessControlState.MessageNeeded;
3880                                                 
3881                                         break;
3882                                 default:
3883                                         break;
3884                         }
3885                                 
3886                         return PreProcessControlState.MessageNotNeeded;
3887                 }
3888                 
3889                 public virtual bool PreProcessMessage (ref Message msg)
3890                 {
3891                         return InternalPreProcessMessage (ref msg);
3892                 }
3893
3894                 internal virtual bool InternalPreProcessMessage (ref Message msg) {
3895                         Keys key_data;
3896
3897                         if ((msg.Msg == (int)Msg.WM_KEYDOWN) || (msg.Msg == (int)Msg.WM_SYSKEYDOWN)) {
3898                                 key_data = (Keys)msg.WParam.ToInt32() | XplatUI.State.ModifierKeys;
3899
3900                                 if (!ProcessCmdKey(ref msg, key_data)) {
3901                                         if (IsInputKey(key_data)) {
3902                                                 return false;
3903                                         }
3904
3905                                         return ProcessDialogKey(key_data);
3906                                 }
3907
3908                                 return true;
3909                         } else if (msg.Msg == (int)Msg.WM_CHAR) {
3910                                 if (IsInputChar((char)msg.WParam)) {
3911                                         return false;
3912                                 }
3913                                 return ProcessDialogChar((char)msg.WParam);
3914                         } else if (msg.Msg == (int)Msg.WM_SYSCHAR) {
3915                                 if (ProcessDialogChar((char)msg.WParam))
3916                                         return true;
3917                                 else
3918                                         return ToolStripManager.ProcessMenuKey (ref msg);
3919                         }
3920                         return false;
3921                 }
3922
3923                 public Rectangle RectangleToClient(Rectangle r) {
3924                         return new Rectangle(PointToClient(r.Location), r.Size);
3925                 }
3926
3927                 public Rectangle RectangleToScreen(Rectangle r) {
3928                         return new Rectangle(PointToScreen(r.Location), r.Size);
3929                 }
3930
3931                 public virtual void Refresh() {
3932                         if (IsHandleCreated && Visible) {
3933                                 Invalidate(true);
3934                                 Update ();
3935                         }
3936                 }
3937
3938                 [EditorBrowsable(EditorBrowsableState.Never)]
3939                 public virtual void ResetBackColor() {
3940                         BackColor = Color.Empty;
3941                 }
3942
3943                 [EditorBrowsable(EditorBrowsableState.Never)]
3944                 public void ResetBindings() {
3945                         if (data_bindings != null)
3946                                 data_bindings.Clear();
3947                 }
3948
3949                 [EditorBrowsable(EditorBrowsableState.Never)]
3950                 public virtual void ResetCursor() {
3951                         Cursor = null;
3952                 }
3953
3954                 [EditorBrowsable(EditorBrowsableState.Never)]
3955                 public virtual void ResetFont() {
3956                         font = null;
3957                 }
3958
3959                 [EditorBrowsable(EditorBrowsableState.Never)]
3960                 public virtual void ResetForeColor() {
3961                         foreground_color = Color.Empty;
3962                 }
3963
3964                 [EditorBrowsable(EditorBrowsableState.Never)]
3965                 public void ResetImeMode() {
3966                         ime_mode = DefaultImeMode;
3967                 }
3968
3969                 [EditorBrowsable(EditorBrowsableState.Never)]
3970                 public virtual void ResetRightToLeft() {
3971                         right_to_left = RightToLeft.Inherit;
3972                 }
3973
3974                 public virtual void ResetText() {
3975                         Text = String.Empty;
3976                 }
3977
3978                 public void ResumeLayout() {
3979                         ResumeLayout (true);
3980                 }
3981
3982                 public void ResumeLayout(bool performLayout) {
3983                         if (layout_suspended > 0) {
3984                                 layout_suspended--;
3985                         }
3986
3987                         if (layout_suspended == 0) {
3988                                 if (this is ContainerControl)
3989                                         (this as ContainerControl).PerformDelayedAutoScale();
3990
3991                                 if (!performLayout)
3992                                         foreach (Control c in Controls.GetAllControls ())
3993                                                 c.UpdateDistances ();
3994
3995                                 if (performLayout && layout_pending) {
3996                                         PerformLayout();
3997                                 }
3998                         }
3999                 }
4000                 [EditorBrowsable (EditorBrowsableState.Never)]
4001                 [Obsolete ()]
4002                 public void Scale(float ratio) {
4003                         ScaleCore(ratio, ratio);
4004                 }
4005                 
4006                 [EditorBrowsable (EditorBrowsableState.Never)]
4007                 [Obsolete ()]
4008                 public void Scale(float dx, float dy) {
4009                         ScaleCore(dx, dy);
4010                 }
4011
4012                 [EditorBrowsable (EditorBrowsableState.Advanced)]
4013                 public void Scale (SizeF factor)
4014                 {
4015                         BoundsSpecified bounds_spec = BoundsSpecified.All;
4016
4017                         SuspendLayout ();
4018
4019                         if (this is ContainerControl) {
4020                                 if ((this as ContainerControl).IsAutoScaling)
4021                                         bounds_spec = BoundsSpecified.Size;
4022                                 else if (IsContainerAutoScaling (this.Parent))
4023                                         bounds_spec = BoundsSpecified.Location;
4024                         }
4025
4026                         ScaleControl (factor, bounds_spec);
4027
4028                         // Scale children
4029                         if ((bounds_spec != BoundsSpecified.Location) && ScaleChildren) {
4030                                 foreach (Control c in Controls.GetAllControls ()) {
4031                                         c.Scale (factor);
4032                                         if (c is ContainerControl) {
4033                                                 ContainerControl cc = c as ContainerControl;
4034                                                 if ((cc.AutoScaleMode == AutoScaleMode.Inherit) && IsContainerAutoScaling (this))
4035                                                         cc.PerformAutoScale (true);
4036                                         }
4037                                 }
4038                         }
4039
4040                         ResumeLayout ();
4041                 }
4042
4043                 internal ContainerControl FindContainer (Control c)
4044                 {
4045                         while ((c != null) && !(c is ContainerControl))
4046                                 c = c.Parent;
4047                         return c as ContainerControl;
4048                 }
4049
4050                 private bool IsContainerAutoScaling (Control c)
4051                 {
4052                         ContainerControl cc = FindContainer (c);
4053                         return (cc != null) && cc.IsAutoScaling;
4054                 }
4055
4056                 public void Select() {
4057                         Select(false, false);   
4058                 }
4059
4060 #if DebugFocus
4061                 private void printTree(Control c, string t) {
4062                         foreach(Control i in c.child_controls) {
4063                                 Console.WriteLine ("{2}{0}.TabIndex={1}", i, i.tab_index, t);
4064                                 printTree (i, t+"\t");
4065                         }
4066                 }
4067 #endif
4068                 public bool SelectNextControl(Control ctl, bool forward, bool tabStopOnly, bool nested, bool wrap) {
4069                         Control c;
4070
4071 #if DebugFocus
4072                         Console.WriteLine("{0}", this.FindForm());
4073                         printTree(this, "\t");
4074 #endif
4075
4076                         if (!this.Contains(ctl) || (!nested && (ctl.parent != this))) {
4077                                 ctl = null;
4078                         }
4079                         c = ctl;
4080                         do {
4081                                 c = GetNextControl(c, forward);
4082                                 if (c == null) {
4083                                         if (wrap) {
4084                                                 wrap = false;
4085                                                 continue;
4086                                         }
4087                                         break;
4088                                 }
4089
4090 #if DebugFocus
4091                                 Console.WriteLine("{0} {1}", c, c.CanSelect);
4092 #endif
4093                                 if (c.CanSelect && ((c.parent == this) || nested) && (c.tab_stop || !tabStopOnly)) {
4094                                         c.Select (true, true);
4095                                         return true;
4096                                 }
4097                         } while (c != ctl); // If we wrap back to ourselves we stop
4098
4099                         return false;
4100                 }
4101
4102                 public void SendToBack() {
4103                         if (parent != null) {
4104                                 parent.child_controls.SetChildIndex(this, parent.child_controls.Count);
4105                         }
4106                 }
4107
4108                 public void SetBounds(int x, int y, int width, int height) {
4109                         SetBounds(x, y, width, height, BoundsSpecified.All);
4110                 }
4111
4112                 public void SetBounds(int x, int y, int width, int height, BoundsSpecified specified) {
4113                         // Fill in the values that were not specified
4114                         if ((specified & BoundsSpecified.X) == 0)
4115                                 x = Left;
4116                         if ((specified & BoundsSpecified.Y) == 0)
4117                                 y = Top;
4118                         if ((specified & BoundsSpecified.Width) == 0)
4119                                 width = Width;
4120                         if ((specified & BoundsSpecified.Height) == 0)
4121                                 height = Height;
4122                 
4123                         SetBoundsInternal (x, y, width, height, specified);
4124                 }
4125
4126                 internal void SetBoundsInternal (int x, int y, int width, int height, BoundsSpecified specified)
4127                 {
4128                         // SetBoundsCore is really expensive to call, so we want to avoid it if we can.
4129                         // We can avoid it if:
4130                         // - The requested dimensions are the same as our current dimensions
4131                         // AND
4132                         // - Any BoundsSpecified is the same as our current explicit_size
4133                         if (bounds.X != x || (explicit_bounds.X != x && (specified & BoundsSpecified.X) == BoundsSpecified.X))
4134                                 SetBoundsCore (x, y, width, height, specified);
4135                         else if (bounds.Y != y || (explicit_bounds.Y != y && (specified & BoundsSpecified.Y) == BoundsSpecified.Y))
4136                                 SetBoundsCore (x, y, width, height, specified);
4137                         else if (bounds.Width != width || (explicit_bounds.Width != width && (specified & BoundsSpecified.Width) == BoundsSpecified.Width))
4138                                 SetBoundsCore (x, y, width, height, specified);
4139                         else if (bounds.Height != height || (explicit_bounds.Height != height && (specified & BoundsSpecified.Height) == BoundsSpecified.Height))
4140                                 SetBoundsCore (x, y, width, height, specified);
4141                         else
4142                                 return;
4143                         
4144                         // If the user explicitly moved or resized us, recalculate our anchor distances
4145                         if (specified != BoundsSpecified.None)
4146                                 UpdateDistances ();
4147                         
4148                         if (parent != null)
4149                                 parent.PerformLayout(this, "Bounds");
4150                 }
4151
4152                 public void Show () {
4153                         this.Visible = true;
4154                 }
4155
4156                 public void SuspendLayout() {
4157                         layout_suspended++;
4158                 }
4159
4160                 public void Update() {
4161                         if (IsHandleCreated) {
4162                                 XplatUI.UpdateWindow(window.Handle);
4163                         }
4164                 }
4165                 #endregion      // Public Instance Methods
4166
4167                 #region Protected Instance Methods
4168                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4169                 protected void AccessibilityNotifyClients(AccessibleEvents accEvent, int childID) {
4170                         // turns out this method causes handle
4171                         // creation in 1.1.  at first I thought this
4172                         // would be accomplished just by using
4173                         // get_AccessibilityObject, which would route
4174                         // through CreateAccessibilityInstance, which
4175                         // calls CreateControl.  This isn't the case,
4176                         // though (as overriding
4177                         // CreateAccessibilityInstance and adding a
4178                         // CWL shows nothing.  So we fudge it and put
4179                         // a CreateHandle here.
4180
4181
4182                         if (accessibility_object != null && accessibility_object is ControlAccessibleObject)
4183                                 ((ControlAccessibleObject)accessibility_object).NotifyClients (accEvent, childID);
4184                 }
4185
4186                 [EditorBrowsable (EditorBrowsableState.Advanced)]
4187                 protected void AccessibilityNotifyClients (AccessibleEvents accEvent, int objectID, int childID)
4188                 {
4189                         if (accessibility_object != null && accessibility_object is ControlAccessibleObject)
4190                                 ((ControlAccessibleObject)accessibility_object).NotifyClients (accEvent, objectID, childID);
4191                 }
4192
4193                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4194                 protected virtual AccessibleObject CreateAccessibilityInstance() {
4195                         CreateControl ();
4196                         return new Control.ControlAccessibleObject(this);
4197                 }
4198
4199                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4200                 protected virtual ControlCollection CreateControlsInstance() {
4201                         return new ControlCollection(this);
4202                 }
4203
4204                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4205                 protected virtual void CreateHandle() {
4206                         if (IsDisposed) {
4207                                 throw new ObjectDisposedException(GetType().FullName);
4208                         }
4209
4210                         if (IsHandleCreated && !is_recreating) {
4211                                 return;
4212                         }
4213
4214                         CreateParams create_params = CreateParams;
4215                         window.CreateHandle(create_params);
4216
4217                         if (window.Handle != IntPtr.Zero) {
4218                                 creator_thread = Thread.CurrentThread;
4219
4220                                 XplatUI.EnableWindow(window.Handle, is_enabled);
4221
4222                                 if (clip_region != null) {
4223                                         XplatUI.SetClipRegion(window.Handle, clip_region);
4224                                 }
4225
4226                                 // Set our handle with our parent
4227                                 if ((parent != null) && (parent.IsHandleCreated)) {
4228                                         XplatUI.SetParent(window.Handle, parent.Handle);
4229                                 }
4230
4231                                 UpdateStyles();
4232                                 XplatUI.SetAllowDrop (window.Handle, allow_drop);
4233
4234                                 // Find out where the window manager placed us
4235                                 if ((CreateParams.Style & (int)WindowStyles.WS_CHILD) != 0) {
4236                                         XplatUI.SetBorderStyle(window.Handle, (FormBorderStyle)border_style);
4237                                 }
4238
4239                                 Rectangle save_bounds = explicit_bounds;
4240                                 UpdateBounds ();
4241                                 explicit_bounds = save_bounds;
4242                         }
4243                 }
4244
4245                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4246                 protected virtual void DefWndProc(ref Message m) {
4247                         window.DefWndProc(ref m);
4248                 }
4249
4250                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4251                 protected virtual void DestroyHandle() {
4252                         if (IsHandleCreated) {
4253                                 if (window != null) {
4254                                         window.DestroyHandle();
4255                                 }
4256                         }
4257                 }
4258
4259                 protected virtual AccessibleObject GetAccessibilityObjectById (int objectId)
4260                 {
4261                         // XXX need to implement this.
4262                         return null;
4263                 }
4264                 
4265                 protected internal AutoSizeMode GetAutoSizeMode () 
4266                 {
4267                         return auto_size_mode;
4268                 }
4269
4270                 [EditorBrowsable (EditorBrowsableState.Advanced)]
4271                 protected virtual Rectangle GetScaledBounds (Rectangle bounds, SizeF factor, BoundsSpecified specified)
4272                 {
4273                         // Top level controls do not scale location
4274                         if (!is_toplevel) {
4275                                 if ((specified & BoundsSpecified.X) == BoundsSpecified.X)
4276                                         bounds.X = (int)Math.Round (bounds.X * factor.Width);
4277                                 if ((specified & BoundsSpecified.Y) == BoundsSpecified.Y)
4278                                         bounds.Y = (int)Math.Round (bounds.Y * factor.Height);
4279                         }
4280
4281                         if ((specified & BoundsSpecified.Width) == BoundsSpecified.Width && !GetStyle (ControlStyles.FixedWidth)) {
4282                                 int border = (this is ComboBox) ? (ThemeEngine.Current.Border3DSize.Width * 2) :
4283                                         (this.bounds.Width - this.client_size.Width);
4284                                 bounds.Width = (int)Math.Round ((bounds.Width - border) * factor.Width + border);
4285                         }
4286                         if ((specified & BoundsSpecified.Height) == BoundsSpecified.Height && !GetStyle (ControlStyles.FixedHeight)) {
4287                                 int border = (this is ComboBox) ? (ThemeEngine.Current.Border3DSize.Height * 2) :
4288                                         (this.bounds.Height - this.client_size.Height);
4289                                 bounds.Height = (int)Math.Round ((bounds.Height - border) * factor.Height + border);
4290                         }
4291
4292                         return bounds;
4293                 }
4294
4295                 private Rectangle GetScaledBoundsOld (Rectangle bounds, SizeF factor, BoundsSpecified specified)
4296                 {
4297                         RectangleF new_bounds = new RectangleF(bounds.Location, bounds.Size);
4298
4299                         // Top level controls do not scale location
4300                         if (!is_toplevel) {
4301                                 if ((specified & BoundsSpecified.X) == BoundsSpecified.X)
4302                                         new_bounds.X *= factor.Width;
4303                                 if ((specified & BoundsSpecified.Y) == BoundsSpecified.Y)
4304                                         new_bounds.Y *= factor.Height;
4305                         }
4306
4307                         if ((specified & BoundsSpecified.Width) == BoundsSpecified.Width && !GetStyle (ControlStyles.FixedWidth)) {
4308                                 int border = (this is Form) ? (this.bounds.Width - this.client_size.Width) : 0;
4309                                 new_bounds.Width = ((new_bounds.Width - border) * factor.Width + border);
4310                         }
4311                         if ((specified & BoundsSpecified.Height) == BoundsSpecified.Height && !GetStyle (ControlStyles.FixedHeight)) {
4312                                 int border = (this is Form) ? (this.bounds.Height - this.client_size.Height) : 0;
4313                                 new_bounds.Height = ((new_bounds.Height - border) * factor.Height + border);
4314                         }
4315
4316                         bounds.X = (int)Math.Round (new_bounds.X);
4317                         bounds.Y = (int)Math.Round (new_bounds.Y);
4318                         bounds.Width = (int)Math.Round (new_bounds.Right) - bounds.X;
4319                         bounds.Height = (int)Math.Round (new_bounds.Bottom) - bounds.Y;
4320
4321                         return bounds;
4322                 }
4323
4324                 protected internal bool GetStyle(ControlStyles flag) {
4325                         return (control_style & flag) != 0;
4326                 }
4327
4328                 protected bool GetTopLevel() {
4329                         return is_toplevel;
4330                 }
4331
4332                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4333                 protected virtual void InitLayout() {
4334                 }
4335
4336                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4337                 protected void InvokeGotFocus(Control toInvoke, EventArgs e) {
4338                         toInvoke.OnGotFocus(e);
4339                 }
4340
4341                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4342                 protected void InvokeLostFocus(Control toInvoke, EventArgs e) {
4343                         toInvoke.OnLostFocus(e);
4344                 }
4345
4346                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4347                 protected void InvokeOnClick(Control toInvoke, EventArgs e) {
4348                         toInvoke.OnClick(e);
4349                 }
4350
4351                 protected void InvokePaint(Control c, PaintEventArgs e) {
4352                         c.OnPaint (e);
4353                 }
4354
4355                 protected void InvokePaintBackground(Control c, PaintEventArgs e) {
4356                         c.OnPaintBackground (e);
4357                 }
4358
4359                 protected virtual bool IsInputChar (char charCode) {
4360                         // XXX on MS.NET this method causes the handle to be created..
4361                         if (!IsHandleCreated)
4362                                 CreateHandle ();
4363
4364                         return IsInputCharInternal (charCode);
4365                 }
4366
4367                 internal virtual bool IsInputCharInternal (char charCode) {
4368                         return false;
4369                 }
4370                 
4371                 protected virtual bool IsInputKey (Keys keyData) {
4372                         // Doc says this one calls IsInputChar; not sure what to do with that
4373                         return false;
4374                 }
4375
4376                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4377                 protected virtual void NotifyInvalidate(Rectangle invalidatedArea) {
4378                         // override me?
4379                 }
4380
4381                 protected virtual bool ProcessCmdKey(ref Message msg, Keys keyData) {
4382                         if ((context_menu != null) && context_menu.ProcessCmdKey(ref msg, keyData)) {
4383                                 return true;
4384                         }
4385
4386                         if (parent != null) {
4387                                 return parent.ProcessCmdKey(ref msg, keyData);
4388                         }
4389
4390                         return false;
4391                 }
4392
4393                 protected virtual bool ProcessDialogChar(char charCode) {
4394                         if (parent != null) {
4395                                 return parent.ProcessDialogChar (charCode);
4396                         }
4397
4398                         return false;
4399                 }
4400
4401                 protected virtual bool ProcessDialogKey (Keys keyData) {
4402                         if (parent != null) {
4403                                 return parent.ProcessDialogKey (keyData);
4404                         }
4405
4406                         return false;
4407                 }
4408
4409                 protected virtual bool ProcessKeyEventArgs (ref Message m)
4410                 {
4411                         KeyEventArgs key_event;
4412
4413                         switch (m.Msg) {
4414                                 case (int)Msg.WM_SYSKEYDOWN:
4415                                 case (int)Msg.WM_KEYDOWN: {
4416                                         key_event = new KeyEventArgs (((Keys) m.WParam.ToInt32 ()) | XplatUI.State.ModifierKeys);
4417                                         OnKeyDown (key_event);
4418                                         suppressing_key_press = key_event.SuppressKeyPress;
4419                                         return key_event.Handled;
4420                                 }
4421
4422                                 case (int)Msg.WM_SYSKEYUP:
4423                                 case (int)Msg.WM_KEYUP: {
4424                                         key_event = new KeyEventArgs (((Keys) m.WParam.ToInt32 ()) | XplatUI.State.ModifierKeys);
4425                                         OnKeyUp (key_event);
4426                                         return key_event.Handled;
4427                                 }
4428
4429                                 case (int)Msg.WM_SYSCHAR:
4430                                 case (int)Msg.WM_CHAR: {
4431                                         if (suppressing_key_press)
4432                                                 return true;
4433                                         KeyPressEventArgs key_press_event;
4434
4435                                         key_press_event = new KeyPressEventArgs ((char) m.WParam);
4436                                         OnKeyPress(key_press_event);
4437                                         m.WParam = (IntPtr) key_press_event.KeyChar;
4438                                         return key_press_event.Handled;
4439                                 }
4440
4441                                 default: {
4442                                         break;
4443                                 }
4444                         }
4445
4446                         return false;
4447                 }
4448
4449                 protected internal virtual bool ProcessKeyMessage (ref Message m)
4450                 {
4451                         if (parent != null) {
4452                                 if (parent.ProcessKeyPreview (ref m))
4453                                         return true;
4454                         }
4455
4456                         return ProcessKeyEventArgs (ref m);
4457                 }
4458
4459                 protected virtual bool ProcessKeyPreview (ref Message m) {
4460                         if (parent != null)
4461                                 return parent.ProcessKeyPreview(ref m);
4462
4463                         return false;
4464                 }
4465
4466                 protected virtual bool ProcessMnemonic(char charCode) {
4467                         // override me
4468                         return false;
4469                 }
4470
4471                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4472                 protected void RaiseDragEvent(object key, DragEventArgs e) {
4473                         // MS Internal
4474                 }
4475
4476                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4477                 protected void RaiseKeyEvent(object key, KeyEventArgs e) {
4478                         // MS Internal
4479                 }
4480
4481                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4482                 protected void RaiseMouseEvent(object key, MouseEventArgs e) {
4483                         // MS Internal
4484                 }
4485
4486                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4487                 protected void RaisePaintEvent(object key, PaintEventArgs e) {
4488                         // MS Internal
4489                 }
4490
4491                 private void SetIsRecreating () {
4492                         is_recreating=true;
4493
4494                         foreach (Control c in Controls.GetAllControls()) {
4495                                 c.SetIsRecreating ();
4496                         }
4497                 }
4498
4499                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4500                 protected void RecreateHandle() {
4501                         if (!IsHandleCreated)
4502                                 return;
4503
4504 #if DebugRecreate
4505                         Console.WriteLine("Recreating control {0}", XplatUI.Window(window.Handle));
4506 #endif
4507
4508                         SetIsRecreating ();
4509
4510                         if (IsHandleCreated) {
4511 #if DebugRecreate
4512                                 Console.WriteLine(" + handle is created, destroying it.");
4513 #endif
4514                                 DestroyHandle();
4515                                 // WM_DESTROY will CreateHandle for us
4516                         } else {
4517 #if DebugRecreate
4518                                 Console.WriteLine(" + handle is not created, creating it.");
4519 #endif
4520                                 if (!is_created) {
4521                                         CreateControl();
4522                                 } else {
4523                                         CreateHandle();
4524                                 }
4525
4526                                 is_recreating = false;
4527 #if DebugRecreate
4528                                 Console.WriteLine (" + new handle = {0:X}", Handle.ToInt32());
4529 #endif
4530                         }
4531
4532                 }
4533
4534                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4535                 protected void ResetMouseEventArgs() {
4536                         // MS Internal
4537                 }
4538
4539                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4540                 protected ContentAlignment RtlTranslateAlignment(ContentAlignment align) {
4541                         if (right_to_left == RightToLeft.No) {
4542                                 return align;
4543                         }
4544
4545                         switch (align) {
4546                                 case ContentAlignment.TopLeft: {
4547                                         return ContentAlignment.TopRight;
4548                                 }
4549
4550                                 case ContentAlignment.TopRight: {
4551                                         return ContentAlignment.TopLeft;
4552                                 }
4553
4554                                 case ContentAlignment.MiddleLeft: {
4555                                         return ContentAlignment.MiddleRight;
4556                                 }
4557
4558                                 case ContentAlignment.MiddleRight: {
4559                                         return ContentAlignment.MiddleLeft;
4560                                 }
4561
4562                                 case ContentAlignment.BottomLeft: {
4563                                         return ContentAlignment.BottomRight;
4564                                 }
4565
4566                                 case ContentAlignment.BottomRight: {
4567                                         return ContentAlignment.BottomLeft;
4568                                 }
4569
4570                                 default: {
4571                                         // if it's center it doesn't change
4572                                         return align;
4573                                 }
4574                         }
4575                 }
4576
4577                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4578                 protected HorizontalAlignment RtlTranslateAlignment(HorizontalAlignment align) {
4579                         if ((right_to_left == RightToLeft.No) || (align == HorizontalAlignment.Center)) {
4580                                 return align;
4581                         }
4582
4583                         if (align == HorizontalAlignment.Left) {
4584                                 return HorizontalAlignment.Right;
4585                         }
4586
4587                         // align must be HorizontalAlignment.Right
4588                         return HorizontalAlignment.Left;
4589                 }
4590
4591                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4592                 protected LeftRightAlignment RtlTranslateAlignment(LeftRightAlignment align) {
4593                         if (right_to_left == RightToLeft.No) {
4594                                 return align;
4595                         }
4596
4597                         if (align == LeftRightAlignment.Left) {
4598                                 return LeftRightAlignment.Right;
4599                         }
4600
4601                         // align must be LeftRightAlignment.Right;
4602                         return LeftRightAlignment.Left;
4603                 }
4604
4605                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4606                 protected ContentAlignment RtlTranslateContent(ContentAlignment align) {
4607                         return RtlTranslateAlignment(align);
4608                 }
4609
4610                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4611                 protected HorizontalAlignment RtlTranslateHorizontal(HorizontalAlignment align) {
4612                         return RtlTranslateAlignment(align);
4613                 }
4614
4615                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4616                 protected LeftRightAlignment RtlTranslateLeftRight(LeftRightAlignment align) {
4617                         return RtlTranslateAlignment(align);
4618                 }
4619
4620                 [EditorBrowsable (EditorBrowsableState.Advanced)]
4621                 protected virtual void ScaleControl (SizeF factor, BoundsSpecified specified)
4622                 {
4623                         Rectangle new_bounds = GetScaledBounds (bounds, factor, specified);
4624
4625                         SetBounds (new_bounds.X, new_bounds.Y, new_bounds.Width, new_bounds.Height, specified);
4626                 }
4627
4628                 [EditorBrowsable (EditorBrowsableState.Never)]
4629                 protected virtual void ScaleCore (float dx, float dy)
4630                 {
4631                         Rectangle new_bounds = GetScaledBoundsOld (bounds, new SizeF (dx, dy), BoundsSpecified.All);
4632
4633                         SuspendLayout ();
4634
4635                         SetBounds (new_bounds.X, new_bounds.Y, new_bounds.Width, new_bounds.Height, BoundsSpecified.All);
4636
4637                         if (ScaleChildrenInternal)
4638                                 foreach (Control c in Controls.GetAllControls ())
4639                                         c.Scale (dx, dy);
4640
4641                         ResumeLayout ();
4642                 }
4643
4644                 protected virtual void Select(bool directed, bool forward) {
4645                         IContainerControl       container;
4646                         
4647                         container = GetContainerControl();
4648                         if (container != null && (Control)container != this)
4649                                 container.ActiveControl = this;
4650                 }
4651
4652                 protected void SetAutoSizeMode (AutoSizeMode mode)
4653                 {
4654                         if (auto_size_mode != mode) {
4655                                 auto_size_mode = mode;
4656                                 PerformLayout (this, "AutoSizeMode");
4657                         }
4658                 }
4659                 
4660                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4661                 protected virtual void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) {
4662                         SetBoundsCoreInternal (x, y, width, height, specified);
4663                 }
4664                 
4665                 internal virtual void SetBoundsCoreInternal(int x, int y, int width, int height, BoundsSpecified specified) {
4666                         // Nasty hack for 2.0 DateTimePicker
4667                         height = OverrideHeight (height);
4668                         
4669                         Rectangle old_explicit = explicit_bounds;
4670                         Rectangle new_bounds = new Rectangle (x, y, width, height);
4671
4672                         // SetBoundsCore updates the Win32 control itself. UpdateBounds updates the controls variables and fires events, I'm guessing - pdb
4673                         if (IsHandleCreated) {
4674                                 XplatUI.SetWindowPos(Handle, x, y, width, height);
4675
4676                                 // Win32 automatically changes negative width/height to 0.
4677                                 // The control has already been sent a WM_WINDOWPOSCHANGED message and it has the correct
4678                                 // data, but it'll be overwritten when we call UpdateBounds unless we get the updated
4679                                 // size.
4680                                 int cw, ch, ix, iy;
4681                                 XplatUI.GetWindowPos(Handle, this is Form, out ix, out iy, out width, out height, out cw, out ch);
4682                         }
4683
4684                         // BoundsSpecified tells us which variables were programatic (user-set).
4685                         // We need to store those in the explicit bounds
4686                         if ((specified & BoundsSpecified.X) == BoundsSpecified.X)
4687                                 explicit_bounds.X = new_bounds.X;
4688                         else
4689                                 explicit_bounds.X = old_explicit.X;
4690
4691                         if ((specified & BoundsSpecified.Y) == BoundsSpecified.Y)
4692                                 explicit_bounds.Y = new_bounds.Y;
4693                         else
4694                                 explicit_bounds.Y = old_explicit.Y;
4695
4696                         if ((specified & BoundsSpecified.Width) == BoundsSpecified.Width)
4697                                 explicit_bounds.Width = new_bounds.Width;
4698                         else
4699                                 explicit_bounds.Width = old_explicit.Width;
4700
4701                         if ((specified & BoundsSpecified.Height) == BoundsSpecified.Height)
4702                                 explicit_bounds.Height = new_bounds.Height;
4703                         else
4704                                 explicit_bounds.Height = old_explicit.Height;
4705
4706                         // We need to store the explicit bounds because UpdateBounds is always going
4707                         // to change it, and we have to fix it.  However, UpdateBounds also calls
4708                         // OnLocationChanged, OnSizeChanged, and OnClientSizeChanged.  The user can
4709                         // override those or use those events to change the size explicitly, and we 
4710                         // can't undo those changes.  So if the bounds after calling UpdateBounds are
4711                         // the same as the ones we sent it, we need to fix the explicit bounds.  If
4712                         // it's not the same as we sent UpdateBounds, then someone else changed it, and
4713                         // we better not mess it up.  Fun stuff.
4714                         Rectangle stored_explicit_bounds = explicit_bounds;
4715                         
4716                         UpdateBounds(x, y, width, height);
4717
4718                         if (explicit_bounds.X == x)
4719                                 explicit_bounds.X = stored_explicit_bounds.X;
4720
4721                         if (explicit_bounds.Y == y)
4722                                 explicit_bounds.Y = stored_explicit_bounds.Y;
4723
4724                         if (explicit_bounds.Width == width)
4725                                 explicit_bounds.Width = stored_explicit_bounds.Width;
4726
4727                         if (explicit_bounds.Height == height)
4728                                 explicit_bounds.Height = stored_explicit_bounds.Height;
4729                 }
4730
4731                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4732                 protected virtual void SetClientSizeCore(int x, int y) {
4733                         Size NewSize = InternalSizeFromClientSize (new Size (x, y));
4734                         
4735                         if (NewSize != Size.Empty)
4736                                 SetBounds (bounds.X, bounds.Y, NewSize.Width, NewSize.Height, BoundsSpecified.Size);
4737                 }
4738
4739                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4740                 protected internal void SetStyle(ControlStyles flag, bool value) {
4741                         if (value) {
4742                                 control_style |= flag;
4743                         } else {
4744                                 control_style &= ~flag;
4745                         }
4746                 }
4747
4748                 protected void SetTopLevel(bool value) {
4749                         if ((GetTopLevel() != value) && (parent != null)) {
4750                                 throw new ArgumentException ("Cannot change toplevel style of a parented control.");
4751                         }
4752
4753                         if (this is Form) {
4754                                 if (IsHandleCreated && value != Visible) {
4755                                         Visible = value;
4756                                 }
4757                         } else {
4758                                 // XXX MS.NET causes handle to be created here
4759                                 if (!IsHandleCreated)
4760                                         CreateHandle ();
4761                         }
4762                         is_toplevel = value;
4763                 }
4764
4765                 protected virtual void SetVisibleCore(bool value) {
4766                         if (value != is_visible) {
4767                                 is_visible = value;
4768                                 
4769                                 if (is_visible && ((window.Handle == IntPtr.Zero) || !is_created)) {
4770                                         CreateControl();
4771                                         if (!(this is Form))
4772                                                 UpdateZOrder ();
4773                                 }
4774
4775                                 if (IsHandleCreated) {
4776                                         XplatUI.SetVisible (Handle, is_visible, true);
4777                                         if (!is_visible) {
4778                                                 if (parent != null && parent.IsHandleCreated) {
4779                                                         parent.Invalidate (bounds);
4780                                                         parent.Update ();
4781                                                 } else {
4782                                                         Refresh ();
4783                                                 }
4784                                         } else if (is_visible && this is Form) {
4785                                                 // If we are Min or Max, we won't get a WM_SHOWWINDOW from SetWindowState,
4786                                                 // so we need to manually create our children, and set them visible
4787                                                 // (This normally happens in WmShowWindow.)
4788                                                 if ((this as Form).WindowState != FormWindowState.Normal)
4789                                                         OnVisibleChanged (EventArgs.Empty);
4790                                                 else
4791                                                         // Explicitly move Toplevel windows to where we want them;
4792                                                         // apparently moving unmapped toplevel windows doesn't work
4793                                                         XplatUI.SetWindowPos(window.Handle, bounds.X, bounds.Y, bounds.Width, bounds.Height);   
4794                                         } else {
4795                                                 // If we are becoming visible, z-order may have changed while
4796                                                 // we were invisible, so update our z-order position
4797                                                 if (parent != null)
4798                                                         parent.UpdateZOrderOfChild (this);
4799                                         }
4800                                         
4801                                         if (!(this is Form))
4802                                                 OnVisibleChanged (EventArgs.Empty);
4803                                 }
4804                                 else {
4805                                         OnVisibleChanged(EventArgs.Empty);
4806                                 }
4807                         }
4808                 }
4809
4810                 [EditorBrowsable (EditorBrowsableState.Advanced)]
4811                 protected virtual Size SizeFromClientSize (Size clientSize) {
4812                         return InternalSizeFromClientSize (clientSize);
4813                 }
4814
4815                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4816                 protected void UpdateBounds() {
4817                         if (!IsHandleCreated)
4818                                 return;
4819
4820                         int     x;
4821                         int     y;
4822                         int     width;
4823                         int     height;
4824                         int     client_width;
4825                         int     client_height;
4826
4827                         XplatUI.GetWindowPos(this.Handle, this is Form, out x, out y, out width, out height, out client_width, out client_height);
4828
4829                         UpdateBounds(x, y, width, height, client_width, client_height);
4830                 }
4831
4832                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4833                 protected void UpdateBounds(int x, int y, int width, int height) {
4834                         CreateParams    cp;
4835                         Rectangle       rect;
4836
4837                         // Calculate client rectangle
4838                         rect = new Rectangle(0, 0, 0, 0);
4839                         cp = CreateParams;
4840
4841                         XplatUI.CalculateWindowRect(ref rect, cp, cp.menu, out rect);
4842                         UpdateBounds(x, y, width, height, width - (rect.Right - rect.Left), height - (rect.Bottom - rect.Top));
4843                 }
4844
4845                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4846                 protected void UpdateBounds(int x, int y, int width, int height, int clientWidth, int clientHeight) {
4847                         // UpdateBounds only seems to set our sizes and fire events but not update the GUI window to match
4848                         bool    moved   = false;
4849                         bool    resized = false;
4850
4851                         // Needed to generate required notifications
4852                         if ((this.bounds.X!=x) || (this.bounds.Y!=y)) {
4853                                 moved=true;
4854                         }
4855
4856                         if ((this.Bounds.Width!=width) || (this.Bounds.Height!=height)) {
4857                                 resized=true;
4858                         }
4859
4860                         bounds.X=x;
4861                         bounds.Y=y;
4862                         bounds.Width=width;
4863                         bounds.Height=height;
4864
4865                         // Assume explicit bounds set. SetBoundsCore will restore old bounds
4866                         // if needed.
4867                         explicit_bounds = bounds;
4868
4869                         client_size.Width=clientWidth;
4870                         client_size.Height=clientHeight;
4871
4872                         if (moved) {
4873                                 OnLocationChanged(EventArgs.Empty);
4874
4875                                 if (!background_color.IsEmpty && background_color.A < byte.MaxValue)
4876                                         Invalidate ();
4877                         }
4878
4879                         if (resized) {
4880                                 OnSizeInitializedOrChanged ();
4881                                 OnSizeChanged(EventArgs.Empty);
4882                                 OnClientSizeChanged (EventArgs.Empty);
4883                         }
4884                 }
4885
4886                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4887                 protected void UpdateStyles() {
4888                         if (!IsHandleCreated) {
4889                                 return;
4890                         }
4891
4892                         XplatUI.SetWindowStyle(window.Handle, CreateParams);
4893                         OnStyleChanged(EventArgs.Empty);
4894                 }
4895
4896                 private void UpdateZOrderOfChild(Control child) {
4897                         if (IsHandleCreated && child.IsHandleCreated && (child.parent == this) && Hwnd.ObjectFromHandle(child.Handle).Mapped) {
4898                                 // Need to take into account all controls
4899                                 Control [] all_controls = child_controls.GetAllControls ();
4900
4901                                 int index = Array.IndexOf (all_controls, child);
4902                                 
4903                                 for (; index > 0; index--) {
4904                                         if (!all_controls [index - 1].IsHandleCreated || !all_controls [index - 1].VisibleInternal || !Hwnd.ObjectFromHandle(all_controls [index - 1].Handle).Mapped)
4905                                                 continue;
4906                                         break;
4907                                 }
4908                                 
4909                                 if (index > 0)  {
4910                                         XplatUI.SetZOrder(child.Handle, all_controls [index - 1].Handle, false, false);
4911                                 } else {
4912                                         IntPtr after = AfterTopMostControl ();
4913                                         if (after != IntPtr.Zero && after != child.Handle)
4914                                                 XplatUI.SetZOrder (child.Handle, after, false, false);
4915                                         else
4916                                                 XplatUI.SetZOrder (child.Handle, IntPtr.Zero, true, false);
4917                                 }
4918                         }
4919                 }
4920                 
4921                 // Override this if there is a control that shall always remain on
4922                 // top of other controls (such as scrollbars). If there are several
4923                 // of these controls, the bottom-most should be returned.
4924                 internal virtual IntPtr AfterTopMostControl () {
4925                         return IntPtr.Zero;
4926                 }
4927
4928                 // internal because we need to call it from ScrollableControl.OnVisibleChanged
4929                 internal void UpdateChildrenZOrder() {
4930                         Control [] controls;
4931
4932                         if (!IsHandleCreated) {
4933                                 return;
4934                         }
4935
4936                         // XXX This code is severely broken.  It leaks
4937                         // the "zero_sized" abstraction out of the X11
4938                         // backend and into Control.cs.  It'll work on
4939                         // windows simply by virtue of windows never
4940                         // setting that field to true.
4941                         //
4942                         // basically what we need to guard against is
4943                         // calling XplatUI.SetZOrder on an hwnd that
4944                         // corresponds to an unmapped X window.
4945                         //
4946                         // Also, explicitly send implicit controls to the back.
4947                         if (child_controls.ImplicitControls == null) {
4948                                 controls = new Control [child_controls.Count];
4949                                 child_controls.CopyTo (controls, 0);
4950                         } else {
4951                                 controls = new Control [child_controls.Count + child_controls.ImplicitControls.Count];
4952                                 child_controls.CopyTo (controls, 0);
4953                                 child_controls.ImplicitControls.CopyTo (controls, child_controls.Count);
4954                         }
4955
4956                         ArrayList children_to_order = new ArrayList ();
4957
4958                         for (int i = 0; i < controls.Length; i ++) {
4959                                 if (!controls[i].IsHandleCreated || !controls[i].VisibleInternal)
4960                                         continue;
4961
4962                                 Hwnd hwnd = Hwnd.ObjectFromHandle (controls[i].Handle);
4963                                 if (hwnd == null || hwnd.zero_sized)
4964                                         continue;
4965
4966                                 children_to_order.Add (controls[i]);
4967                         }
4968
4969                         for (int i = 1; i < children_to_order.Count; i ++) {
4970                                 Control upper = (Control)children_to_order[i-1];
4971                                 Control lower = (Control)children_to_order[i];
4972
4973                                 XplatUI.SetZOrder(lower.Handle, upper.Handle, false, false);
4974                         }
4975                 }
4976
4977                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4978                 protected void UpdateZOrder() {
4979                         if (parent != null) {
4980                                 parent.UpdateZOrderOfChild(this);
4981                         }
4982                 }
4983
4984                 protected virtual void WndProc(ref Message m) {
4985 #if DebugMessages
4986                         Console.WriteLine("Control {0} received message {1}", window.Handle == IntPtr.Zero ? this.Text : XplatUI.Window(window.Handle), m.ToString ());
4987 #endif
4988                         if ((this.control_style & ControlStyles.EnableNotifyMessage) != 0) {
4989                                 OnNotifyMessage(m);
4990                         }
4991
4992                         switch((Msg)m.Msg) {
4993                                 case Msg.WM_DESTROY: {
4994                                         WmDestroy(ref m);
4995                                         return;
4996                                 }
4997
4998                                 case Msg.WM_WINDOWPOSCHANGED: {
4999                                         WmWindowPosChanged(ref m);
5000                                         return;
5001                                 }
5002
5003                                         // Nice description of what should happen when handling WM_PAINT
5004                                         // can be found here: http://pluralsight.com/wiki/default.aspx/Craig/FlickerFreeControlDrawing.html
5005                                         // and here http://msdn.microsoft.com/msdnmag/issues/06/03/WindowsFormsPerformance/
5006                                 case Msg.WM_PAINT: {
5007                                         WmPaint (ref m);
5008                                         return;
5009                                 }
5010                                         
5011                                 // The DefWndProc will never have to handle this, we always paint the background in managed code
5012                                 // In theory this code would look at ControlStyles.AllPaintingInWmPaint and and call OnPaintBackground
5013                                 // here but it just makes things more complicated...
5014                                 case Msg.WM_ERASEBKGND: {
5015                                         WmEraseBackground (ref m);
5016                                         return;
5017                                 }
5018
5019                                 case Msg.WM_LBUTTONUP: {
5020                                         WmLButtonUp (ref m);
5021                                         return;
5022                                 }
5023                                         
5024                                 case Msg.WM_LBUTTONDOWN: {
5025                                         WmLButtonDown (ref m);
5026                                         return;
5027                                 }
5028
5029                                 case Msg.WM_LBUTTONDBLCLK: {
5030                                         WmLButtonDblClick (ref m);
5031                                         return;
5032                                 }
5033
5034                                 case Msg.WM_MBUTTONUP: {
5035                                         WmMButtonUp (ref m);
5036                                         return;
5037                                 }
5038                                         
5039                                 case Msg.WM_MBUTTONDOWN: {                                      
5040                                         WmMButtonDown (ref m);
5041                                         return;
5042                                 }
5043
5044                                 case Msg.WM_MBUTTONDBLCLK: {
5045                                         WmMButtonDblClick (ref m);
5046                                         return;
5047                                 }
5048
5049                                 case Msg.WM_RBUTTONUP: {
5050                                         WmRButtonUp (ref m);
5051                                         return;
5052                                 }
5053                                         
5054                                 case Msg.WM_RBUTTONDOWN: {                                      
5055                                         WmRButtonDown (ref m);
5056                                         return;
5057                                 }
5058
5059                                 case Msg.WM_RBUTTONDBLCLK: {
5060                                         WmRButtonDblClick (ref m);
5061                                         return;
5062                                 }
5063
5064                                 case Msg.WM_CONTEXTMENU: {
5065                                         WmContextMenu (ref m);
5066                                         return;
5067                                 }
5068
5069                                 case Msg.WM_MOUSEWHEEL: {
5070                                         WmMouseWheel (ref m);
5071                                         return;
5072                                 }
5073
5074                                 case Msg.WM_MOUSEMOVE: {
5075                                         WmMouseMove (ref m);
5076                                         return;
5077                                 }
5078
5079                                 case Msg.WM_SHOWWINDOW: {
5080                                         WmShowWindow (ref m);
5081                                         return;
5082                                 }
5083
5084                                 case Msg.WM_CREATE: {
5085                                         WmCreate (ref m);
5086                                         return;
5087                                 }
5088
5089                                 case Msg.WM_MOUSE_ENTER: {
5090                                         WmMouseEnter (ref m);
5091                                         return;
5092                                 }
5093
5094                                 case Msg.WM_MOUSELEAVE: {
5095                                         WmMouseLeave (ref m);
5096                                         return;
5097                                 }
5098
5099                                 case Msg.WM_MOUSEHOVER: {
5100                                         WmMouseHover (ref m);
5101                                         return;
5102                                 }
5103
5104                                 case Msg.WM_SYSKEYUP: {
5105                                         WmSysKeyUp (ref m);
5106                                         return;
5107                                 }
5108
5109                                 case Msg.WM_SYSKEYDOWN:
5110                                 case Msg.WM_KEYDOWN:
5111                                 case Msg.WM_KEYUP:
5112                                 case Msg.WM_SYSCHAR:
5113                                 case Msg.WM_CHAR: {
5114                                         WmKeys (ref m);
5115                                         return;
5116                                 }
5117
5118                                 case Msg.WM_HELP: {
5119                                         WmHelp (ref m);
5120                                         return;
5121                                 }
5122
5123                                 case Msg.WM_KILLFOCUS: {
5124                                         WmKillFocus (ref m);
5125                                         return;
5126                                 }
5127
5128                                 case Msg.WM_SETFOCUS: {
5129                                         WmSetFocus (ref m);
5130                                         return;
5131                                 }
5132                                         
5133                                 case Msg.WM_SYSCOLORCHANGE: {
5134                                         WmSysColorChange (ref m);
5135                                         return;
5136                                 }
5137
5138                                 case Msg.WM_SETCURSOR: {
5139                                         WmSetCursor (ref m);
5140                                         return;
5141                                 }
5142
5143                                 case Msg.WM_CAPTURECHANGED: {
5144                                         WmCaptureChanged (ref m);
5145                                         return;
5146                                 }
5147
5148                                 case Msg.WM_CHANGEUISTATE: {
5149                                         WmChangeUIState (ref m);
5150                                         return;
5151                                 }
5152                         
5153                                 case Msg.WM_UPDATEUISTATE: {
5154                                         WmUpdateUIState (ref m);
5155                                         return;
5156                                 }
5157
5158                                 default:
5159                                         DefWndProc(ref m);
5160                                         return;
5161                         }
5162                 }
5163
5164                 #endregion      // Public Instance Methods
5165
5166                 #region WM methods
5167                 
5168                 private void WmDestroy (ref Message m) {
5169                         OnHandleDestroyed(EventArgs.Empty);
5170 #if DebugRecreate
5171                         IntPtr handle = window.Handle;
5172 #endif
5173                         window.InvalidateHandle();
5174
5175                         is_created = false;
5176                         if (is_recreating) {
5177 #if DebugRecreate
5178                                 Console.WriteLine ("Creating handle for {0:X}", handle.ToInt32());
5179 #endif
5180                                 CreateHandle();
5181 #if DebugRecreate
5182                                 Console.WriteLine (" + new handle = {0:X}", Handle.ToInt32());
5183 #endif
5184                                 is_recreating = false;
5185                         }
5186
5187                         if (is_disposing) {
5188                                 is_disposing = false;
5189                                 is_visible = false;
5190                         }
5191                 }
5192
5193                 private void WmWindowPosChanged (ref Message m) {
5194                         if (Visible) {
5195                                 Rectangle save_bounds = explicit_bounds;
5196                                 UpdateBounds();
5197                                 explicit_bounds = save_bounds;
5198                                 if (GetStyle(ControlStyles.ResizeRedraw)) {
5199                                         Invalidate();
5200                                 }
5201                         }
5202                 }
5203
5204
5205                 // Nice description of what should happen when handling WM_PAINT
5206                 // can be found here: http://pluralsight.com/wiki/default.aspx/Craig/FlickerFreeControlDrawing.html
5207                 // and here http://msdn.microsoft.com/msdnmag/issues/06/03/WindowsFormsPerformance/
5208                 private void WmPaint (ref Message m) {
5209                         IntPtr handle = Handle;
5210
5211                         PaintEventArgs paint_event = XplatUI.PaintEventStart (ref m, handle, true);
5212
5213                         if (paint_event == null)
5214                                 return;
5215
5216                         DoubleBuffer current_buffer = null;
5217                         if (UseDoubleBuffering) {
5218                                 current_buffer = GetBackBuffer ();
5219                                 // This optimization doesn't work when the area is invalidated
5220                                 // during a paint operation because finishing the paint operation
5221                                 // clears the invalidated region and then this thing keeps the new
5222                                 // invalidate from working.  To re-enable this, we would need a
5223                                 // mechanism to allow for nested invalidates (see bug #328681)
5224                                 //if (!current_buffer.InvalidRegion.IsVisible (paint_event.ClipRectangle)) {
5225                                 //        // Just blit the previous image
5226                                 //        current_buffer.Blit (paint_event);
5227                                 //        XplatUI.PaintEventEnd (ref m, handle, true);
5228                                 //        return;
5229                                 //}
5230                                 current_buffer.Start (paint_event);
5231                         }
5232                         // If using OptimizedDoubleBuffer, ensure the clip region gets set
5233                         if (GetStyle (ControlStyles.OptimizedDoubleBuffer))
5234                                 paint_event.Graphics.SetClip (Rectangle.Intersect (paint_event.ClipRectangle, this.ClientRectangle));
5235
5236                         if (!GetStyle(ControlStyles.Opaque)) {
5237                                 OnPaintBackground (paint_event);
5238                         }
5239
5240                         // Button-derived controls choose to ignore their Opaque style, give them a chance to draw their background anyways
5241                         OnPaintBackgroundInternal (paint_event);
5242
5243                         OnPaintInternal(paint_event);
5244                         if (!paint_event.Handled) {
5245                                 OnPaint (paint_event);
5246                         }
5247
5248                         if (current_buffer != null) {
5249                                 current_buffer.End (paint_event);
5250                         }
5251
5252
5253                         XplatUI.PaintEventEnd (ref m, handle, true);
5254                 }
5255
5256                 private void WmEraseBackground (ref Message m) {
5257                         // The DefWndProc will never have to handle this, we always paint the background in managed code
5258                         // In theory this code would look at ControlStyles.AllPaintingInWmPaint and and call OnPaintBackground
5259                         // here but it just makes things more complicated...
5260                         m.Result = (IntPtr)1;
5261                 }
5262
5263                 private void WmLButtonUp (ref Message m)
5264                 {
5265                         // Menu handle.
5266                         if (XplatUI.IsEnabled (Handle) && active_tracker != null) {
5267                                 ProcessActiveTracker (ref m);
5268                                 return;
5269                         }
5270
5271                         MouseEventArgs me;
5272
5273                         me = new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()) | MouseButtons.Left, 
5274                                 mouse_clicks, 
5275                                 LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
5276                                 0);
5277
5278                         HandleClick(mouse_clicks, me);
5279                         OnMouseUp (me);
5280
5281                         if (InternalCapture) {
5282                                 InternalCapture = false;
5283                         }
5284
5285                         if (mouse_clicks > 1) {
5286                                 mouse_clicks = 1;
5287                         }
5288                 }
5289
5290                 private void WmLButtonDown (ref Message m)
5291                 {
5292                         // Menu handle.
5293                         if (XplatUI.IsEnabled (Handle) && active_tracker != null) {
5294                                 ProcessActiveTracker (ref m);
5295                                 return;
5296                         }
5297                 
5298                         ValidationFailed = false;
5299                         if (CanSelect) {
5300                                 Select (true, true);
5301                         }
5302                         if (!ValidationFailed) {
5303                                 InternalCapture = true;
5304                                 OnMouseDown (new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()), 
5305                                         mouse_clicks, LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
5306                                         0));
5307                         }
5308                 }
5309
5310                 private void WmLButtonDblClick (ref Message m) {
5311                         InternalCapture = true;
5312                         mouse_clicks++;
5313                         OnMouseDown (new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()), 
5314                                 mouse_clicks, LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
5315                                 0));
5316                 }
5317
5318                 private void WmMButtonUp (ref Message m) {
5319                         MouseEventArgs me;
5320
5321                         me = new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()) | MouseButtons.Middle, 
5322                                 mouse_clicks, 
5323                                 LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
5324                                 0);
5325
5326                         HandleClick(mouse_clicks, me);
5327                         OnMouseUp (me);
5328                         if (InternalCapture) {
5329                                 InternalCapture = false;
5330                         }
5331                         if (mouse_clicks > 1) {
5332                                 mouse_clicks = 1;
5333                         }
5334                 }
5335
5336                 private void WmMButtonDown (ref Message m) {
5337                         InternalCapture = true;
5338                         OnMouseDown (new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()), 
5339                                 mouse_clicks, LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
5340                                 0));
5341                 }
5342
5343                 private void WmMButtonDblClick (ref Message m) {
5344                         InternalCapture = true;
5345                         mouse_clicks++;
5346                         OnMouseDown (new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()), 
5347                                 mouse_clicks, LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
5348                                 0));
5349                 }
5350
5351                 private void WmRButtonUp (ref Message m)
5352                 {
5353                         // Menu handle.
5354                         if (XplatUI.IsEnabled (Handle) && active_tracker != null) {
5355                                 ProcessActiveTracker (ref m);
5356                                 return;
5357                         }
5358
5359                         MouseEventArgs  me;
5360                         Point           pt;
5361
5362                         pt = new Point(LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()));
5363                         pt = PointToScreen(pt);
5364
5365                         me = new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()) | MouseButtons.Right, 
5366                                 mouse_clicks, 
5367                                 LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
5368                                 0);
5369
5370                         HandleClick(mouse_clicks, me);
5371
5372                         XplatUI.SendMessage(m.HWnd, Msg.WM_CONTEXTMENU, m.HWnd, (IntPtr)(pt.X + (pt.Y << 16)));
5373                         OnMouseUp (me);
5374
5375                         if (InternalCapture) {
5376                                 InternalCapture = false;
5377                         }
5378
5379                         if (mouse_clicks > 1) {
5380                                 mouse_clicks = 1;
5381                         }
5382                 }
5383
5384                 private void WmRButtonDown (ref Message m)
5385                 {
5386                         // Menu handle.
5387                         if (XplatUI.IsEnabled (Handle) && active_tracker != null) {
5388                                 ProcessActiveTracker (ref m);
5389                                 return;
5390                         }
5391
5392                         InternalCapture = true;
5393                         OnMouseDown (new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()), 
5394                                 mouse_clicks, LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
5395                                 0));
5396                 }
5397
5398                 private void WmRButtonDblClick (ref Message m) {
5399                         InternalCapture = true;
5400                         mouse_clicks++;
5401                         OnMouseDown (new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()), 
5402                                 mouse_clicks, LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
5403                                 0));
5404                 }
5405
5406                 private void WmContextMenu (ref Message m) {
5407                         if (context_menu != null) {
5408                                 Point   pt;
5409
5410                                 pt = new Point(LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()));
5411
5412                                 if (pt.X == -1 || pt.Y == -1) {
5413                                         pt.X = (this.Width / 2) + this.Left;
5414                                         pt.Y = (this.Height / 2) + this.Top;
5415                                         pt = this.PointToScreen (pt);
5416                                 }
5417                                         
5418                                 context_menu.Show (this, PointToClient (pt));
5419                                 return;
5420                         }
5421
5422                                 // If there isn't a regular context menu, show the Strip version
5423                                 if (context_menu == null && context_menu_strip != null) {
5424                                         Point pt;
5425
5426                                         pt = new Point (LowOrder ((int)m.LParam.ToInt32 ()), HighOrder ((int)m.LParam.ToInt32 ()));
5427                                         
5428                                         if (pt.X == -1 || pt.Y == -1) { 
5429                                                 pt.X = (this.Width / 2) + this.Left; 
5430                                                 pt.Y = (this.Height /2) + this.Top; 
5431                                                 pt = this.PointToScreen (pt);
5432                                         }
5433                                         
5434                                         context_menu_strip.SetSourceControl (this);
5435                                         context_menu_strip.Show (this, PointToClient (pt));
5436                                         return;
5437                                 }
5438                         DefWndProc(ref m);
5439                 }
5440
5441                 private void WmCreate (ref Message m) {
5442                         OnHandleCreated(EventArgs.Empty);
5443                 }
5444
5445                 private void WmMouseWheel (ref Message m) {
5446                         DefWndProc(ref m);
5447                         OnMouseWheel (new MouseEventArgs (FromParamToMouseButtons ((long) m.WParam), 
5448                                 mouse_clicks, LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
5449                                 HighOrder((long)m.WParam)));
5450                 }
5451
5452
5453                 private void WmMouseMove (ref Message m) {
5454                         if (XplatUI.IsEnabled (Handle) && active_tracker != null) {
5455                                 MouseEventArgs args = new MouseEventArgs (
5456                                         FromParamToMouseButtons ((int)m.WParam.ToInt32 ()),
5457                                         mouse_clicks,
5458                                         Control.MousePosition.X,
5459                                         Control.MousePosition.Y,
5460                                         0);
5461
5462                                 active_tracker.OnMotion (args);
5463                                 return;
5464                         }
5465                         
5466                         OnMouseMove  (new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()), 
5467                                 mouse_clicks, 
5468                                 LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
5469                                 0));
5470                 }
5471
5472                 private void WmMouseEnter (ref Message m) {
5473                         if (is_entered) {
5474                                 return;
5475                         }
5476                         is_entered = true;
5477                         OnMouseEnter(EventArgs.Empty);
5478                 }
5479
5480                 private void WmMouseLeave (ref Message m) {
5481                         is_entered=false;
5482                         OnMouseLeave(EventArgs.Empty);
5483                 }
5484
5485                 private void WmMouseHover (ref Message m) {
5486                         OnMouseHover(EventArgs.Empty);
5487                 }
5488
5489                 private void WmShowWindow (ref Message m) {
5490                         if (IsDisposed)
5491                                 return;
5492
5493                         Form frm = this as Form;
5494                         if (m.WParam.ToInt32() != 0) {
5495                                 if (m.LParam.ToInt32 () == 0) {
5496                                         CreateControl ();
5497                                 
5498                                         // Make sure all our children are properly parented to us
5499                                         Control [] controls = child_controls.GetAllControls ();
5500 //                                      bool parented = false;
5501                                         for (int i=0; i<controls.Length; i++) {
5502                                                 if (controls [i].is_visible && controls[i].IsHandleCreated)
5503                                                         if (XplatUI.GetParent (controls[i].Handle) != window.Handle) {
5504                                                                 XplatUI.SetParent(controls[i].Handle, window.Handle);
5505 //                                                              parented = true;
5506                                                         }
5507
5508                                         }
5509                                         
5510                                         //if (parented)
5511                                                 UpdateChildrenZOrder ();
5512                                 }
5513                         } else {
5514                                 if (parent != null && Focused) {
5515                                         Control container;
5516                                         // Need to start at parent, GetContainerControl might return ourselves if we're a container
5517                                         container = (Control)parent.GetContainerControl();
5518                                         if (container != null && (frm == null || !frm.IsMdiChild)) {
5519                                                 container.SelectNextControl(this, true, true, true, true);
5520                                         }
5521                                 }
5522                         }
5523
5524                         if (frm != null)
5525                                 frm.waiting_showwindow = false;
5526
5527                         // If the form is Max/Min, it got its OnVisibleChanged in SetVisibleCore
5528                         if (frm != null) {
5529                                 if (!IsRecreating && (frm.IsMdiChild || frm.WindowState == FormWindowState.Normal)) /* XXX make sure this works for mdi forms */
5530                                         OnVisibleChanged(EventArgs.Empty);
5531                         } else if (is_toplevel)
5532                                 OnVisibleChanged(EventArgs.Empty);
5533                 }
5534
5535                 private void WmSysKeyUp (ref Message m) {
5536                         if (ProcessKeyMessage(ref m)) {
5537                                 m.Result = IntPtr.Zero;
5538                                 return;
5539                         }
5540
5541                         if ((m.WParam.ToInt32() & (int)Keys.KeyCode) == (int)Keys.Menu) {
5542                                 Form    form;
5543
5544                                 form = FindForm();
5545                                 if (form != null && form.ActiveMenu != null) {
5546                                         form.ActiveMenu.ProcessCmdKey(ref m, (Keys)m.WParam.ToInt32());
5547                                 }
5548                                 else
5549                                         if (ToolStripManager.ProcessMenuKey (ref m))
5550                                                 return;
5551                         }
5552
5553                         DefWndProc (ref m);
5554                 }
5555
5556                 private void WmKeys (ref Message m)
5557                 {
5558                         if (ProcessKeyMessage(ref m)) {
5559                                 m.Result = IntPtr.Zero;
5560                                 return;
5561                         }
5562                         DefWndProc (ref m);
5563                 }
5564
5565                 private void WmHelp (ref Message m) {
5566                         Point   mouse_pos;
5567                         if (m.LParam != IntPtr.Zero) {
5568                                 HELPINFO        hi;
5569
5570                                 hi = new HELPINFO();
5571
5572                                 hi = (HELPINFO) Marshal.PtrToStructure (m.LParam, typeof (HELPINFO));
5573                                 mouse_pos = new Point(hi.MousePos.x, hi.MousePos.y);
5574                         } else {
5575                                 mouse_pos = Control.MousePosition;
5576                         }
5577                         OnHelpRequested(new HelpEventArgs(mouse_pos));
5578                         m.Result = (IntPtr)1;
5579                 }
5580
5581                 private void WmKillFocus (ref Message m) {
5582                         this.has_focus = false;
5583                         OnLostFocus (EventArgs.Empty);
5584                 }
5585
5586                 private void WmSetFocus (ref Message m) {
5587                         if (!has_focus) {
5588                                 this.has_focus = true;
5589                                 OnGotFocus (EventArgs.Empty);
5590                         }
5591                 }
5592                                         
5593                 private void WmSysColorChange (ref Message m) {
5594                         ThemeEngine.Current.ResetDefaults();
5595                         OnSystemColorsChanged(EventArgs.Empty);
5596                 }
5597
5598                 private void WmSetCursor (ref Message m) {
5599                         if ((cursor == null && use_wait_cursor == false) || ((HitTest)(m.LParam.ToInt32() & 0xffff) != HitTest.HTCLIENT)) {
5600                                 DefWndProc(ref m);
5601                                 return;
5602                         }
5603
5604                         XplatUI.SetCursor(window.Handle, Cursor.handle);
5605                         m.Result = (IntPtr)1;
5606                 }
5607
5608                 private void WmCaptureChanged (ref Message m) {
5609                         is_captured = false;
5610                         OnMouseCaptureChanged (EventArgs.Empty);
5611                         m.Result = (IntPtr) 0;
5612                 }
5613
5614                 private void WmChangeUIState (ref Message m) {
5615                         foreach (Control control in Controls) {
5616                                 XplatUI.SendMessage (control.Handle, Msg.WM_UPDATEUISTATE, m.WParam, m.LParam);
5617                         }
5618                 }
5619
5620                 private void WmUpdateUIState (ref Message m) {
5621                         int action = LowOrder (m.WParam.ToInt32 ());
5622                         int element = HighOrder (m.WParam.ToInt32 ());
5623
5624                         if (action == (int) MsgUIState.UIS_INITIALIZE)
5625                                 return;
5626
5627                         UICues cues = UICues.None;
5628
5629                         if ((element & (int) MsgUIState.UISF_HIDEACCEL) != 0) {
5630                                 if ((action == (int) MsgUIState.UIS_CLEAR) != show_keyboard_cues) {
5631                                         cues |= UICues.ChangeKeyboard;
5632                                         show_keyboard_cues = (action == (int) MsgUIState.UIS_CLEAR);
5633                                 }
5634                         }
5635
5636                         if ((element & (int) MsgUIState.UISF_HIDEFOCUS) != 0) {
5637                                 if ((action == (int) MsgUIState.UIS_CLEAR) != show_focus_cues) {
5638                                         cues |= UICues.ChangeFocus;
5639                                         show_focus_cues = (action == (int) MsgUIState.UIS_CLEAR);
5640                                 }
5641                         }
5642
5643                         if ((cues & UICues.Changed) != UICues.None) {
5644                                 OnChangeUICues (new UICuesEventArgs (cues));
5645                                 Invalidate ();
5646                         }
5647                 }
5648
5649                 #endregion
5650
5651                 #region OnXXX methods
5652                 protected virtual void OnAutoSizeChanged (EventArgs e)
5653                 {
5654                         EventHandler eh = (EventHandler)(Events[AutoSizeChangedEvent]);
5655                         if (eh != null)
5656                                 eh (this, e);
5657                 }
5658
5659                 [EditorBrowsable (EditorBrowsableState.Advanced)]
5660                 protected virtual void OnBackColorChanged(EventArgs e) {
5661                         EventHandler eh = (EventHandler)(Events [BackColorChangedEvent]);
5662                         if (eh != null)
5663                                 eh (this, e);
5664                         for (int i=0; i<child_controls.Count; i++) child_controls[i].OnParentBackColorChanged(e);
5665                 }
5666
5667                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5668                 protected virtual void OnBackgroundImageChanged(EventArgs e) {
5669                         EventHandler eh = (EventHandler)(Events [BackgroundImageChangedEvent]);
5670                         if (eh != null)
5671                                 eh (this, e);
5672                         for (int i=0; i<child_controls.Count; i++) child_controls[i].OnParentBackgroundImageChanged(e);
5673                 }
5674
5675                 [EditorBrowsable (EditorBrowsableState.Advanced)]
5676                 protected virtual void OnBackgroundImageLayoutChanged (EventArgs e)
5677                 {
5678                         EventHandler eh = (EventHandler)(Events[BackgroundImageLayoutChangedEvent]);
5679                         if (eh != null)
5680                                 eh (this, e);
5681                 }
5682
5683                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5684                 protected virtual void OnBindingContextChanged(EventArgs e) {
5685                         CheckDataBindings ();
5686                         EventHandler eh = (EventHandler)(Events [BindingContextChangedEvent]);
5687                         if (eh != null)
5688                                 eh (this, e);
5689                         for (int i=0; i<child_controls.Count; i++) child_controls[i].OnParentBindingContextChanged(e);
5690                 }
5691
5692                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5693                 protected virtual void OnCausesValidationChanged(EventArgs e) {
5694                         EventHandler eh = (EventHandler)(Events [CausesValidationChangedEvent]);
5695                         if (eh != null)
5696                                 eh (this, e);
5697                 }
5698
5699                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5700                 protected virtual void OnChangeUICues(UICuesEventArgs e) {
5701                         UICuesEventHandler eh = (UICuesEventHandler)(Events [ChangeUICuesEvent]);
5702                         if (eh != null)
5703                                 eh (this, e);
5704                 }
5705
5706                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5707                 protected virtual void OnClick(EventArgs e) {
5708                         EventHandler eh = (EventHandler)(Events [ClickEvent]);
5709                         if (eh != null)
5710                                 eh (this, e);
5711                 }
5712
5713                 [EditorBrowsable (EditorBrowsableState.Advanced)]
5714                 protected virtual void OnClientSizeChanged (EventArgs e)
5715                 {
5716                         EventHandler eh = (EventHandler)(Events[ClientSizeChangedEvent]);
5717                         if (eh != null)
5718                                 eh (this, e);
5719                 }
5720
5721                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5722                 protected virtual void OnContextMenuChanged(EventArgs e) {
5723                         EventHandler eh = (EventHandler)(Events [ContextMenuChangedEvent]);
5724                         if (eh != null)
5725                                 eh (this, e);
5726                 }
5727
5728                 [EditorBrowsable (EditorBrowsableState.Advanced)]
5729                 protected virtual void OnContextMenuStripChanged (EventArgs e) {
5730                         EventHandler eh = (EventHandler)(Events [ContextMenuStripChangedEvent]);
5731                         if (eh != null)
5732                                 eh (this, e);
5733                 }
5734
5735                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5736                 protected virtual void OnControlAdded(ControlEventArgs e) {
5737                         ControlEventHandler eh = (ControlEventHandler)(Events [ControlAddedEvent]);
5738                         if (eh != null)
5739                                 eh (this, e);
5740                 }
5741
5742                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5743                 protected virtual void OnControlRemoved(ControlEventArgs e) {
5744                         ControlEventHandler eh = (ControlEventHandler)(Events [ControlRemovedEvent]);
5745                         if (eh != null)
5746                                 eh (this, e);
5747                 }
5748
5749                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5750                 protected virtual void OnCreateControl() {
5751                         // Override me!
5752                 }
5753
5754                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5755                 protected virtual void OnCursorChanged(EventArgs e) {
5756                         EventHandler eh = (EventHandler)(Events [CursorChangedEvent]);
5757                         if (eh != null)
5758                                 eh (this, e);
5759                                 
5760                         for (int i = 0; i < child_controls.Count; i++) child_controls[i].OnParentCursorChanged (e);
5761                 }
5762
5763                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5764                 protected virtual void OnDockChanged(EventArgs e) {
5765                         EventHandler eh = (EventHandler)(Events [DockChangedEvent]);
5766                         if (eh != null)
5767                                 eh (this, e);
5768                 }
5769
5770                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5771                 protected virtual void OnDoubleClick(EventArgs e) {
5772                         EventHandler eh = (EventHandler)(Events [DoubleClickEvent]);
5773                         if (eh != null)
5774                                 eh (this, e);
5775                 }
5776
5777                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5778                 protected virtual void OnDragDrop(DragEventArgs drgevent) {
5779                         DragEventHandler eh = (DragEventHandler)(Events [DragDropEvent]);
5780                         if (eh != null)
5781                                 eh (this, drgevent);
5782                 }
5783
5784                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5785                 protected virtual void OnDragEnter(DragEventArgs drgevent) {
5786                         DragEventHandler eh = (DragEventHandler)(Events [DragEnterEvent]);
5787                         if (eh != null)
5788                                 eh (this, drgevent);
5789                 }
5790
5791                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5792                 protected virtual void OnDragLeave(EventArgs e) {
5793                         EventHandler eh = (EventHandler)(Events [DragLeaveEvent]);
5794                         if (eh != null)
5795                                 eh (this, e);
5796                 }
5797
5798                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5799                 protected virtual void OnDragOver(DragEventArgs drgevent) {
5800                         DragEventHandler eh = (DragEventHandler)(Events [DragOverEvent]);
5801                         if (eh != null)
5802                                 eh (this, drgevent);
5803                 }
5804
5805                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5806                 protected virtual void OnEnabledChanged(EventArgs e) {
5807                         if (IsHandleCreated) {
5808                                 if (this is Form) {
5809                                         if (((Form)this).context == null) {
5810                                                 XplatUI.EnableWindow(window.Handle, Enabled);
5811                                         }
5812                                 } else {
5813                                         XplatUI.EnableWindow(window.Handle, Enabled);
5814                                 }
5815                                 Refresh();
5816                         }
5817
5818                         EventHandler eh = (EventHandler)(Events [EnabledChangedEvent]);
5819                         if (eh != null)
5820                                 eh (this, e);
5821
5822                         foreach (Control c in Controls.GetAllControls ())
5823                                 c.OnParentEnabledChanged (e);
5824                 }
5825
5826                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5827                 protected virtual void OnEnter(EventArgs e) {
5828                         EventHandler eh = (EventHandler)(Events [EnterEvent]);
5829                         if (eh != null)
5830                                 eh (this, e);
5831                 }
5832
5833                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5834                 protected virtual void OnFontChanged(EventArgs e) {
5835                         EventHandler eh = (EventHandler)(Events [FontChangedEvent]);
5836                         if (eh != null)
5837                                 eh (this, e);
5838                         for (int i=0; i<child_controls.Count; i++) child_controls[i].OnParentFontChanged(e);
5839                 }
5840
5841                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5842                 protected virtual void OnForeColorChanged(EventArgs e) {
5843                         EventHandler eh = (EventHandler)(Events [ForeColorChangedEvent]);
5844                         if (eh != null)
5845                                 eh (this, e);
5846                         for (int i=0; i<child_controls.Count; i++) child_controls[i].OnParentForeColorChanged(e);
5847                 }
5848
5849                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5850                 protected virtual void OnGiveFeedback(GiveFeedbackEventArgs gfbevent) {
5851                         GiveFeedbackEventHandler eh = (GiveFeedbackEventHandler)(Events [GiveFeedbackEvent]);
5852                         if (eh != null)
5853                                 eh (this, gfbevent);
5854                 }
5855                 
5856                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5857                 protected virtual void OnGotFocus(EventArgs e) {
5858                         EventHandler eh = (EventHandler)(Events [GotFocusEvent]);
5859                         if (eh != null)
5860                                 eh (this, e);
5861                 }
5862
5863                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5864                 protected virtual void OnHandleCreated(EventArgs e) {
5865                         EventHandler eh = (EventHandler)(Events [HandleCreatedEvent]);
5866                         if (eh != null)
5867                                 eh (this, e);
5868                 }
5869
5870                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5871                 protected virtual void OnHandleDestroyed(EventArgs e) {
5872                         EventHandler eh = (EventHandler)(Events [HandleDestroyedEvent]);
5873                         if (eh != null)
5874                                 eh (this, e);
5875                 }
5876
5877                 internal void RaiseHelpRequested (HelpEventArgs hevent) {
5878                         OnHelpRequested (hevent);
5879                 }
5880                 
5881                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5882                 protected virtual void OnHelpRequested(HelpEventArgs hevent) {
5883                         HelpEventHandler eh = (HelpEventHandler)(Events [HelpRequestedEvent]);
5884                         if (eh != null)
5885                                 eh (this, hevent);
5886                 }
5887
5888                 protected virtual void OnImeModeChanged(EventArgs e) {
5889                         EventHandler eh = (EventHandler)(Events [ImeModeChangedEvent]);
5890                         if (eh != null)
5891                                 eh (this, e);
5892                 }
5893
5894                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5895                 protected virtual void OnInvalidated(InvalidateEventArgs e) {
5896                         if (UseDoubleBuffering) {
5897                                 // should this block be here?  seems like it
5898                                 // would be more at home in
5899                                 // NotifyInvalidated..
5900                                 if (e.InvalidRect == ClientRectangle) {
5901                                         InvalidateBackBuffer ();
5902                                 } else if (backbuffer != null){
5903                                         // we need this Inflate call here so
5904                                         // that the border of the rectangle is
5905                                         // considered Visible (the
5906                                         // invalid_region.IsVisible call) in
5907                                         // the WM_PAINT handling below.
5908                                         Rectangle r = Rectangle.Inflate(e.InvalidRect, 1,1);
5909                                         backbuffer.InvalidRegion.Union (r);
5910                                 }
5911                         }
5912
5913                         InvalidateEventHandler eh = (InvalidateEventHandler)(Events [InvalidatedEvent]);
5914                         if (eh != null)
5915                                 eh (this, e);
5916                 }
5917
5918                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5919                 protected virtual void OnKeyDown(KeyEventArgs e) {
5920                         KeyEventHandler eh = (KeyEventHandler)(Events [KeyDownEvent]);
5921                         if (eh != null)
5922                                 eh (this, e);
5923                 }
5924
5925                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5926                 protected virtual void OnKeyPress(KeyPressEventArgs e) {
5927                         KeyPressEventHandler eh = (KeyPressEventHandler)(Events [KeyPressEvent]);
5928                         if (eh != null)
5929                                 eh (this, e);
5930                 }
5931
5932                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5933                 protected virtual void OnKeyUp(KeyEventArgs e) {
5934                         KeyEventHandler eh = (KeyEventHandler)(Events [KeyUpEvent]);
5935                         if (eh != null)
5936                                 eh (this, e);
5937                 }
5938
5939                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5940                 protected virtual void OnLayout(LayoutEventArgs levent) {
5941                         LayoutEventHandler eh = (LayoutEventHandler)(Events [LayoutEvent]);
5942                         if (eh != null)
5943                                 eh (this, levent);
5944
5945                         Size s = Size;
5946                         
5947                         // If our layout changed our PreferredSize, our parent
5948                         // needs to re-lay us out.  However, it's not always possible to
5949                         // be our preferred size, so only try once so we don't loop forever.
5950                         if (Parent != null && AutoSize && !nested_layout && PreferredSize != s) {
5951                                 nested_layout = true;
5952                                 Parent.PerformLayout ();
5953                                 nested_layout = false;
5954                         }
5955                         
5956                         LayoutEngine.Layout (this, levent);
5957                 }
5958
5959                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5960                 protected virtual void OnLeave(EventArgs e) {
5961                         EventHandler eh = (EventHandler)(Events [LeaveEvent]);
5962                         if (eh != null)
5963                                 eh (this, e);
5964                 }
5965
5966                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5967                 protected virtual void OnLocationChanged(EventArgs e) {
5968                         OnMove(e);
5969                         EventHandler eh = (EventHandler)(Events [LocationChangedEvent]);
5970                         if (eh != null)
5971                                 eh (this, e);
5972                 }
5973
5974                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5975                 protected virtual void OnLostFocus(EventArgs e) {
5976                         EventHandler eh = (EventHandler)(Events [LostFocusEvent]);
5977                         if (eh != null)
5978                                 eh (this, e);
5979                 }
5980
5981                 protected virtual void OnMarginChanged (EventArgs e)
5982                 {
5983                         EventHandler eh = (EventHandler)(Events[MarginChangedEvent]);
5984                         if (eh != null)
5985                                 eh (this, e);
5986                 }
5987                 [EditorBrowsable (EditorBrowsableState.Advanced)]
5988                 protected virtual void OnMouseCaptureChanged (EventArgs e)
5989                 {
5990                         EventHandler eh = (EventHandler)(Events [MouseCaptureChangedEvent]);
5991                         if (eh != null)
5992                                 eh (this, e);
5993                 }
5994
5995                 [EditorBrowsable (EditorBrowsableState.Advanced)]
5996                 protected virtual void OnMouseClick (MouseEventArgs e)
5997                 {
5998                         MouseEventHandler eh = (MouseEventHandler)(Events [MouseClickEvent]);
5999                         if (eh != null)
6000                                 eh (this, e);
6001                 }
6002
6003                 [EditorBrowsable (EditorBrowsableState.Advanced)]
6004                 protected virtual void OnMouseDoubleClick (MouseEventArgs e)
6005                 {
6006                         MouseEventHandler eh = (MouseEventHandler)(Events [MouseDoubleClickEvent]);
6007                         if (eh != null)
6008                                 eh (this, e);
6009                 }
6010
6011                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6012                 protected virtual void OnMouseDown(MouseEventArgs e) {
6013                         MouseEventHandler eh = (MouseEventHandler)(Events [MouseDownEvent]);
6014                         if (eh != null)
6015                                 eh (this, e);
6016                 }
6017
6018                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6019                 protected virtual void OnMouseEnter(EventArgs e) {
6020                         EventHandler eh = (EventHandler)(Events [MouseEnterEvent]);
6021                         if (eh != null)
6022                                 eh (this, e);
6023                 }
6024
6025                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6026                 protected virtual void OnMouseHover(EventArgs e) {
6027                         EventHandler eh = (EventHandler)(Events [MouseHoverEvent]);
6028                         if (eh != null)
6029                                 eh (this, e);
6030                 }
6031
6032                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6033                 protected virtual void OnMouseLeave(EventArgs e) {
6034                         EventHandler eh = (EventHandler)(Events [MouseLeaveEvent]);
6035                         if (eh != null)
6036                                 eh (this, e);
6037                 }
6038
6039                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6040                 protected virtual void OnMouseMove(MouseEventArgs e) {
6041                         MouseEventHandler eh = (MouseEventHandler)(Events [MouseMoveEvent]);
6042                         if (eh != null)
6043                                 eh (this, e);
6044                 }
6045
6046                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6047                 protected virtual void OnMouseUp(MouseEventArgs e) {
6048                         MouseEventHandler eh = (MouseEventHandler)(Events [MouseUpEvent]);
6049                         if (eh != null)
6050                                 eh (this, e);
6051                 }
6052
6053                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6054                 protected virtual void OnMouseWheel(MouseEventArgs e) {
6055                         MouseEventHandler eh = (MouseEventHandler)(Events [MouseWheelEvent]);
6056                         if (eh != null)
6057                                 eh (this, e);
6058                 }
6059
6060                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6061                 protected virtual void OnMove(EventArgs e) {
6062                         EventHandler eh = (EventHandler)(Events [MoveEvent]);
6063                         if (eh != null)
6064                                 eh (this, e);
6065                 }
6066
6067                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6068                 protected virtual void OnNotifyMessage(Message m) {
6069                         // Override me!
6070                 }
6071
6072                 protected virtual void OnPaddingChanged (EventArgs e) {
6073                         EventHandler eh = (EventHandler) (Events [PaddingChangedEvent]);
6074                         if (eh != null)
6075                                 eh (this, e);
6076                 }
6077
6078                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6079                 protected virtual void OnPaint(PaintEventArgs e) {
6080                         PaintEventHandler eh = (PaintEventHandler)(Events [PaintEvent]);
6081                         if (eh != null)
6082                                 eh (this, e);
6083                 }
6084
6085                 internal virtual void OnPaintBackgroundInternal(PaintEventArgs e) {
6086                         // Override me
6087                 }
6088
6089                 internal virtual void OnPaintInternal(PaintEventArgs e) {
6090                         // Override me
6091                 }
6092
6093                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6094                 protected virtual void OnPaintBackground(PaintEventArgs pevent) {
6095                         PaintControlBackground (pevent);
6096                 }
6097
6098                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6099                 protected virtual void OnParentBackColorChanged(EventArgs e) {
6100                         if (background_color.IsEmpty && background_image==null) {
6101                                 Invalidate();
6102                                 OnBackColorChanged(e);
6103                         }
6104                 }
6105
6106                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6107                 protected virtual void OnParentBackgroundImageChanged(EventArgs e) {
6108                         Invalidate();
6109                         OnBackgroundImageChanged(e);
6110                 }
6111
6112                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6113                 protected virtual void OnParentBindingContextChanged(EventArgs e) {
6114                         if (binding_context==null && Parent != null) {
6115                                 binding_context=Parent.binding_context;
6116                                 OnBindingContextChanged(e);
6117                         }
6118                 }
6119
6120                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6121                 protected virtual void OnParentChanged(EventArgs e) {
6122                         EventHandler eh = (EventHandler)(Events [ParentChangedEvent]);
6123                         if (eh != null)
6124                                 eh (this, e);
6125                 }
6126
6127                 [EditorBrowsable (EditorBrowsableState.Advanced)]
6128                 protected virtual void OnParentCursorChanged (EventArgs e)
6129                 {
6130                 }
6131
6132                 [EditorBrowsable (EditorBrowsableState.Advanced)]
6133                 protected virtual void OnParentEnabledChanged(EventArgs e) {
6134                         if (is_enabled) {
6135                                 OnEnabledChanged(e);
6136                         }
6137                 }
6138
6139                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6140                 protected virtual void OnParentFontChanged(EventArgs e) {
6141                         if (font==null) {
6142                                 Invalidate();
6143                                 OnFontChanged(e);
6144                         }
6145                 }
6146
6147                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6148                 protected virtual void OnParentForeColorChanged(EventArgs e) {
6149                         if (foreground_color.IsEmpty) {
6150                                 Invalidate();
6151                                 OnForeColorChanged(e);
6152                         }
6153                 }
6154
6155                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6156                 protected virtual void OnParentRightToLeftChanged(EventArgs e) {
6157                         if (right_to_left==RightToLeft.Inherit) {
6158                                 Invalidate();
6159                                 OnRightToLeftChanged(e);
6160                         }
6161                 }
6162
6163                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6164                 protected virtual void OnParentVisibleChanged(EventArgs e) {
6165                         if (is_visible) {
6166                                 OnVisibleChanged(e);
6167                         }
6168                 }
6169
6170                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6171                 protected virtual void OnQueryContinueDrag (QueryContinueDragEventArgs qcdevent)
6172                 {
6173                         QueryContinueDragEventHandler eh = (QueryContinueDragEventHandler)(Events [QueryContinueDragEvent]);
6174                         if (eh != null)
6175                                 eh (this, qcdevent);
6176                 }
6177
6178                 [EditorBrowsable (EditorBrowsableState.Advanced)]
6179                 protected virtual void OnPreviewKeyDown (PreviewKeyDownEventArgs e)
6180                 {
6181                         PreviewKeyDownEventHandler eh = (PreviewKeyDownEventHandler)(Events[PreviewKeyDownEvent]);
6182                         if (eh != null)
6183                                 eh (this, e);
6184                 }
6185
6186                 [EditorBrowsable (EditorBrowsableState.Advanced)]
6187                 protected virtual void OnPrint (PaintEventArgs e)
6188                 {
6189                         PaintEventHandler eh = (PaintEventHandler)(Events[PaintEvent]);
6190                         if (eh != null)
6191                                 eh (this, e);
6192                 }
6193
6194                 [EditorBrowsable (EditorBrowsableState.Advanced)]
6195                 protected virtual void OnRegionChanged (EventArgs e)
6196                 {
6197                         EventHandler eh = (EventHandler)(Events[RegionChangedEvent]);
6198                         if (eh != null)
6199                                 eh (this, e);
6200                 }
6201
6202                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6203                 protected virtual void OnResize(EventArgs e) {
6204                         OnResizeInternal (e);
6205                 }
6206                 
6207                 internal virtual void OnResizeInternal (EventArgs e) {
6208                         PerformLayout(this, "Bounds");
6209
6210                         EventHandler eh = (EventHandler)(Events [ResizeEvent]);
6211                         if (eh != null)
6212                                 eh (this, e);
6213                 }
6214
6215                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6216                 protected virtual void OnRightToLeftChanged(EventArgs e) {
6217                         EventHandler eh = (EventHandler)(Events [RightToLeftChangedEvent]);
6218                         if (eh != null)
6219                                 eh (this, e);
6220                         for (int i=0; i<child_controls.Count; i++) child_controls[i].OnParentRightToLeftChanged(e);
6221                 }
6222
6223                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6224                 protected virtual void OnSizeChanged(EventArgs e) {
6225                         DisposeBackBuffer ();
6226                         OnResize(e);
6227                         EventHandler eh = (EventHandler)(Events [SizeChangedEvent]);
6228                         if (eh != null)
6229                                 eh (this, e);
6230                 }
6231
6232                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6233                 protected virtual void OnStyleChanged(EventArgs e) {
6234                         EventHandler eh = (EventHandler)(Events [StyleChangedEvent]);
6235                         if (eh != null)
6236                                 eh (this, e);
6237                 }
6238
6239                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6240                 protected virtual void OnSystemColorsChanged(EventArgs e) {
6241                         EventHandler eh = (EventHandler)(Events [SystemColorsChangedEvent]);
6242                         if (eh != null)
6243                                 eh (this, e);
6244                 }
6245
6246                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6247                 protected virtual void OnTabIndexChanged(EventArgs e) {
6248                         EventHandler eh = (EventHandler)(Events [TabIndexChangedEvent]);
6249                         if (eh != null)
6250                                 eh (this, e);
6251                 }
6252
6253                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6254                 protected virtual void OnTabStopChanged(EventArgs e) {
6255                         EventHandler eh = (EventHandler)(Events [TabStopChangedEvent]);
6256                         if (eh != null)
6257                                 eh (this, e);
6258                 }
6259
6260                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6261                 protected virtual void OnTextChanged(EventArgs e) {
6262                         EventHandler eh = (EventHandler)(Events [TextChangedEvent]);
6263                         if (eh != null)
6264                                 eh (this, e);
6265                 }
6266
6267                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6268                 protected virtual void OnValidated(EventArgs e) {
6269                         EventHandler eh = (EventHandler)(Events [ValidatedEvent]);
6270                         if (eh != null)
6271                                 eh (this, e);
6272                 }
6273
6274                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6275                 protected virtual void OnValidating(System.ComponentModel.CancelEventArgs e) {
6276                         CancelEventHandler eh = (CancelEventHandler)(Events [ValidatingEvent]);
6277                         if (eh != null)
6278                                 eh (this, e);
6279                 }
6280
6281                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6282                 protected virtual void OnVisibleChanged(EventArgs e) {
6283                         if (Visible)
6284                                 CreateControl ();
6285                                 
6286                         EventHandler eh = (EventHandler)(Events [VisibleChangedEvent]);
6287                         if (eh != null)
6288                                 eh (this, e);
6289
6290                         // We need to tell our kids (including implicit ones)
6291                         foreach (Control c in Controls.GetAllControls ())
6292                                 if (c.Visible)
6293                                         c.OnParentVisibleChanged (e);
6294                 }
6295                 #endregion      // OnXXX methods
6296
6297                 #region Events
6298                 static object AutoSizeChangedEvent = new object ();
6299                 static object BackColorChangedEvent = new object ();
6300                 static object BackgroundImageChangedEvent = new object ();
6301                 static object BackgroundImageLayoutChangedEvent = new object ();
6302                 static object BindingContextChangedEvent = new object ();
6303                 static object CausesValidationChangedEvent = new object ();
6304                 static object ChangeUICuesEvent = new object ();
6305                 static object ClickEvent = new object ();
6306                 static object ClientSizeChangedEvent = new object ();
6307                 static object ContextMenuChangedEvent = new object ();
6308                 static object ContextMenuStripChangedEvent = new object ();
6309                 static object ControlAddedEvent = new object ();
6310                 static object ControlRemovedEvent = new object ();
6311                 static object CursorChangedEvent = new object ();
6312                 static object DockChangedEvent = new object ();
6313                 static object DoubleClickEvent = new object ();
6314                 static object DragDropEvent = new object ();
6315                 static object DragEnterEvent = new object ();
6316                 static object DragLeaveEvent = new object ();
6317                 static object DragOverEvent = new object ();
6318                 static object EnabledChangedEvent = new object ();
6319                 static object EnterEvent = new object ();
6320                 static object FontChangedEvent = new object ();
6321                 static object ForeColorChangedEvent = new object ();
6322                 static object GiveFeedbackEvent = new object ();
6323                 static object GotFocusEvent = new object ();
6324                 static object HandleCreatedEvent = new object ();
6325                 static object HandleDestroyedEvent = new object ();
6326                 static object HelpRequestedEvent = new object ();
6327                 static object ImeModeChangedEvent = new object ();
6328                 static object InvalidatedEvent = new object ();
6329                 static object KeyDownEvent = new object ();
6330                 static object KeyPressEvent = new object ();
6331                 static object KeyUpEvent = new object ();
6332                 static object LayoutEvent = new object ();
6333                 static object LeaveEvent = new object ();
6334                 static object LocationChangedEvent = new object ();
6335                 static object LostFocusEvent = new object ();
6336                 static object MarginChangedEvent = new object ();
6337                 static object MouseCaptureChangedEvent = new object ();
6338                 static object MouseClickEvent = new object ();
6339                 static object MouseDoubleClickEvent = new object ();
6340                 static object MouseDownEvent = new object ();
6341                 static object MouseEnterEvent = new object ();
6342                 static object MouseHoverEvent = new object ();
6343                 static object MouseLeaveEvent = new object ();
6344                 static object MouseMoveEvent = new object ();
6345                 static object MouseUpEvent = new object ();
6346                 static object MouseWheelEvent = new object ();
6347                 static object MoveEvent = new object ();
6348                 static object PaddingChangedEvent = new object ();
6349                 static object PaintEvent = new object ();
6350                 static object ParentChangedEvent = new object ();
6351                 static object PreviewKeyDownEvent = new object ();
6352                 static object QueryAccessibilityHelpEvent = new object ();
6353                 static object QueryContinueDragEvent = new object ();
6354                 static object RegionChangedEvent = new object ();
6355                 static object ResizeEvent = new object ();
6356                 static object RightToLeftChangedEvent = new object ();
6357                 static object SizeChangedEvent = new object ();
6358                 static object StyleChangedEvent = new object ();
6359                 static object SystemColorsChangedEvent = new object ();
6360                 static object TabIndexChangedEvent = new object ();
6361                 static object TabStopChangedEvent = new object ();
6362                 static object TextChangedEvent = new object ();
6363                 static object ValidatedEvent = new object ();
6364                 static object ValidatingEvent = new object ();
6365                 static object VisibleChangedEvent = new object ();
6366
6367                 [Browsable (false)]
6368                 [EditorBrowsable (EditorBrowsableState.Never)]
6369                 public event EventHandler AutoSizeChanged {
6370                         add { Events.AddHandler (AutoSizeChangedEvent, value);}
6371                         remove {Events.RemoveHandler (AutoSizeChangedEvent, value);}
6372                 }
6373                 public event EventHandler BackColorChanged {
6374                         add { Events.AddHandler (BackColorChangedEvent, value); }
6375                         remove { Events.RemoveHandler (BackColorChangedEvent, value); }
6376                 }
6377
6378                 public event EventHandler BackgroundImageChanged {
6379                         add { Events.AddHandler (BackgroundImageChangedEvent, value); }
6380                         remove { Events.RemoveHandler (BackgroundImageChangedEvent, value); }
6381                 }
6382
6383                 public event EventHandler BackgroundImageLayoutChanged {
6384                         add {Events.AddHandler (BackgroundImageLayoutChangedEvent, value);}
6385                         remove {Events.RemoveHandler (BackgroundImageLayoutChangedEvent, value);}
6386                 }
6387
6388                 public event EventHandler BindingContextChanged {
6389                         add { Events.AddHandler (BindingContextChangedEvent, value); }
6390                         remove { Events.RemoveHandler (BindingContextChangedEvent, value); }
6391                 }
6392
6393                 public event EventHandler CausesValidationChanged {
6394                         add { Events.AddHandler (CausesValidationChangedEvent, value); }
6395                         remove { Events.RemoveHandler (CausesValidationChangedEvent, value); }
6396                 }
6397
6398                 public event UICuesEventHandler ChangeUICues {
6399                         add { Events.AddHandler (ChangeUICuesEvent, value); }
6400                         remove { Events.RemoveHandler (ChangeUICuesEvent, value); }
6401                 }
6402
6403                 public event EventHandler Click {
6404                         add { Events.AddHandler (ClickEvent, value); }
6405                         remove { Events.RemoveHandler (ClickEvent, value); }
6406                 }
6407                 
6408                 public event EventHandler ClientSizeChanged {
6409                         add {Events.AddHandler (ClientSizeChangedEvent, value);}
6410                         remove {Events.RemoveHandler (ClientSizeChangedEvent, value);}
6411                 }
6412
6413                 [Browsable (false)]
6414                 public event EventHandler ContextMenuChanged {
6415                         add { Events.AddHandler (ContextMenuChangedEvent, value); }
6416                         remove { Events.RemoveHandler (ContextMenuChangedEvent, value); }
6417                 }
6418
6419                 public event EventHandler ContextMenuStripChanged {
6420                         add { Events.AddHandler (ContextMenuStripChangedEvent, value); }
6421                         remove { Events.RemoveHandler (ContextMenuStripChangedEvent, value);}
6422                 }
6423
6424
6425                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6426                 [Browsable(true)]
6427                 public event ControlEventHandler ControlAdded {
6428                         add { Events.AddHandler (ControlAddedEvent, value); }
6429                         remove { Events.RemoveHandler (ControlAddedEvent, value); }
6430                 }
6431
6432                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6433                 [Browsable(true)]
6434                 public event ControlEventHandler ControlRemoved {
6435                         add { Events.AddHandler (ControlRemovedEvent, value); }
6436                         remove { Events.RemoveHandler (ControlRemovedEvent, value); }
6437                 }
6438
6439                 [MWFDescription("Fired when the cursor for the control has been changed"), MWFCategory("PropertyChanged")]
6440                 public event EventHandler CursorChanged {
6441                         add { Events.AddHandler (CursorChangedEvent, value); }
6442                         remove { Events.RemoveHandler (CursorChangedEvent, value); }
6443                 }
6444                 public event EventHandler DockChanged {
6445                         add { Events.AddHandler (DockChangedEvent, value); }
6446                         remove { Events.RemoveHandler (DockChangedEvent, value); }
6447                 }
6448
6449                 public event EventHandler DoubleClick {
6450                         add { Events.AddHandler (DoubleClickEvent, value); }
6451                         remove { Events.RemoveHandler (DoubleClickEvent, value); }
6452                 }
6453
6454                 public event DragEventHandler DragDrop {
6455                         add { Events.AddHandler (DragDropEvent, value); }
6456                         remove { Events.RemoveHandler (DragDropEvent, value); }
6457                 }
6458
6459                 public event DragEventHandler DragEnter {
6460                         add { Events.AddHandler (DragEnterEvent, value); }
6461                         remove { Events.RemoveHandler (DragEnterEvent, value); }
6462                 }
6463
6464                 public event EventHandler DragLeave {
6465                         add { Events.AddHandler (DragLeaveEvent, value); }
6466                         remove { Events.RemoveHandler (DragLeaveEvent, value); }
6467                 }
6468
6469                 public event DragEventHandler DragOver {
6470                         add { Events.AddHandler (DragOverEvent, value); }
6471                         remove { Events.RemoveHandler (DragOverEvent, value); }
6472                 }
6473
6474                 public event EventHandler EnabledChanged {
6475                         add { Events.AddHandler (EnabledChangedEvent, value); }
6476                         remove { Events.RemoveHandler (EnabledChangedEvent, value); }
6477                 }
6478
6479                 public event EventHandler Enter {
6480                         add { Events.AddHandler (EnterEvent, value); }
6481                         remove { Events.RemoveHandler (EnterEvent, value); }
6482                 }
6483
6484                 public event EventHandler FontChanged {
6485                         add { Events.AddHandler (FontChangedEvent, value); }
6486                         remove { Events.RemoveHandler (FontChangedEvent, value); }
6487                 }
6488
6489                 public event EventHandler ForeColorChanged {
6490                         add { Events.AddHandler (ForeColorChangedEvent, value); }
6491                         remove { Events.RemoveHandler (ForeColorChangedEvent, value); }
6492                 }
6493
6494                 public event GiveFeedbackEventHandler GiveFeedback {
6495                         add { Events.AddHandler (GiveFeedbackEvent, value); }
6496                         remove { Events.RemoveHandler (GiveFeedbackEvent, value); }
6497                 }
6498
6499                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6500                 [Browsable(false)]
6501                 public event EventHandler GotFocus {
6502                         add { Events.AddHandler (GotFocusEvent, value); }
6503                         remove { Events.RemoveHandler (GotFocusEvent, value); }
6504                 }
6505
6506
6507                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6508                 [Browsable(false)]
6509                 public event EventHandler HandleCreated {
6510                         add { Events.AddHandler (HandleCreatedEvent, value); }
6511                         remove { Events.RemoveHandler (HandleCreatedEvent, value); }
6512                 }
6513
6514                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6515                 [Browsable(false)]
6516                 public event EventHandler HandleDestroyed {
6517                         add { Events.AddHandler (HandleDestroyedEvent, value); }
6518                         remove { Events.RemoveHandler (HandleDestroyedEvent, value); }
6519                 }
6520
6521                 public event HelpEventHandler HelpRequested {
6522                         add { Events.AddHandler (HelpRequestedEvent, value); }
6523                         remove { Events.RemoveHandler (HelpRequestedEvent, value); }
6524                 }
6525
6526                 public event EventHandler ImeModeChanged {
6527                         add { Events.AddHandler (ImeModeChangedEvent, value); }
6528                         remove { Events.RemoveHandler (ImeModeChangedEvent, value); }
6529                 }
6530
6531                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6532                 [Browsable(false)]
6533                 public event InvalidateEventHandler Invalidated {
6534                         add { Events.AddHandler (InvalidatedEvent, value); }
6535                         remove { Events.RemoveHandler (InvalidatedEvent, value); }
6536                 }
6537
6538                 public event KeyEventHandler KeyDown {
6539                         add { Events.AddHandler (KeyDownEvent, value); }
6540                         remove { Events.RemoveHandler (KeyDownEvent, value); }
6541                 }
6542
6543                 public event KeyPressEventHandler KeyPress {
6544                         add { Events.AddHandler (KeyPressEvent, value); }
6545                         remove { Events.RemoveHandler (KeyPressEvent, value); }
6546                 }
6547
6548                 public event KeyEventHandler KeyUp {
6549                         add { Events.AddHandler (KeyUpEvent, value); }
6550                         remove { Events.RemoveHandler (KeyUpEvent, value); }
6551                 }
6552
6553                 public event LayoutEventHandler Layout {
6554                         add { Events.AddHandler (LayoutEvent, value); }
6555                         remove { Events.RemoveHandler (LayoutEvent, value); }
6556                 }
6557
6558                 public event EventHandler Leave {
6559                         add { Events.AddHandler (LeaveEvent, value); }
6560                         remove { Events.RemoveHandler (LeaveEvent, value); }
6561                 }
6562
6563                 public event EventHandler LocationChanged {
6564                         add { Events.AddHandler (LocationChangedEvent, value); }
6565                         remove { Events.RemoveHandler (LocationChangedEvent, value); }
6566                 }
6567
6568                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6569                 [Browsable(false)]
6570                 public event EventHandler LostFocus {
6571                         add { Events.AddHandler (LostFocusEvent, value); }
6572                         remove { Events.RemoveHandler (LostFocusEvent, value); }
6573                 }
6574
6575                 public event EventHandler MarginChanged {
6576                         add { Events.AddHandler (MarginChangedEvent, value); }
6577                         remove {Events.RemoveHandler (MarginChangedEvent, value); }
6578                 }
6579
6580                 public event EventHandler MouseCaptureChanged {
6581                         add { Events.AddHandler (MouseCaptureChangedEvent, value); }
6582                         remove { Events.RemoveHandler (MouseCaptureChangedEvent, value); }
6583                 }
6584                 public event MouseEventHandler MouseClick
6585                 {
6586                         add { Events.AddHandler (MouseClickEvent, value); }
6587                         remove { Events.RemoveHandler (MouseClickEvent, value); }
6588                 }
6589                 public event MouseEventHandler MouseDoubleClick
6590                 {
6591                         add { Events.AddHandler (MouseDoubleClickEvent, value); }
6592                         remove { Events.RemoveHandler (MouseDoubleClickEvent, value); }
6593                 }
6594                 public event MouseEventHandler MouseDown {
6595                         add { Events.AddHandler (MouseDownEvent, value); }
6596                         remove { Events.RemoveHandler (MouseDownEvent, value); }
6597                 }
6598
6599                 public event EventHandler MouseEnter {
6600                         add { Events.AddHandler (MouseEnterEvent, value); }
6601                         remove { Events.RemoveHandler (MouseEnterEvent, value); }
6602                 }
6603
6604                 public event EventHandler MouseHover {
6605                         add { Events.AddHandler (MouseHoverEvent, value); }
6606                         remove { Events.RemoveHandler (MouseHoverEvent, value); }
6607                 }
6608
6609                 public event EventHandler MouseLeave {
6610                         add { Events.AddHandler (MouseLeaveEvent, value); }
6611                         remove { Events.RemoveHandler (MouseLeaveEvent, value); }
6612                 }
6613
6614                 public event MouseEventHandler MouseMove {
6615                         add { Events.AddHandler (MouseMoveEvent, value); }
6616                         remove { Events.RemoveHandler (MouseMoveEvent, value); }
6617                 }
6618
6619                 public event MouseEventHandler MouseUp {
6620                         add { Events.AddHandler (MouseUpEvent, value); }
6621                         remove { Events.RemoveHandler (MouseUpEvent, value); }
6622                 }
6623
6624                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6625                 [Browsable(false)]
6626                 public event MouseEventHandler MouseWheel {
6627                         add { Events.AddHandler (MouseWheelEvent, value); }
6628                         remove { Events.RemoveHandler (MouseWheelEvent, value); }
6629                 }
6630
6631                 public event EventHandler Move {
6632                         add { Events.AddHandler (MoveEvent, value); }
6633                         remove { Events.RemoveHandler (MoveEvent, value); }
6634                 }
6635                 public event EventHandler PaddingChanged
6636                 {
6637                         add { Events.AddHandler (PaddingChangedEvent, value); }
6638                         remove { Events.RemoveHandler (PaddingChangedEvent, value); }
6639                 }
6640                 public event PaintEventHandler Paint {
6641                         add { Events.AddHandler (PaintEvent, value); }
6642                         remove { Events.RemoveHandler (PaintEvent, value); }
6643                 }
6644
6645                 public event EventHandler ParentChanged {
6646                         add { Events.AddHandler (ParentChangedEvent, value); }
6647                         remove { Events.RemoveHandler (ParentChangedEvent, value); }
6648                 }
6649
6650                 public event PreviewKeyDownEventHandler PreviewKeyDown {
6651                         add { Events.AddHandler (PreviewKeyDownEvent, value); }
6652                         remove { Events.RemoveHandler (PreviewKeyDownEvent, value); }
6653                 }
6654
6655                 public event QueryAccessibilityHelpEventHandler QueryAccessibilityHelp {
6656                         add { Events.AddHandler (QueryAccessibilityHelpEvent, value); }
6657                         remove { Events.RemoveHandler (QueryAccessibilityHelpEvent, value); }
6658                 }
6659
6660                 public event QueryContinueDragEventHandler QueryContinueDrag {
6661                         add { Events.AddHandler (QueryContinueDragEvent, value); }
6662                         remove { Events.RemoveHandler (QueryContinueDragEvent, value); }
6663                 }
6664
6665                 public event EventHandler RegionChanged {
6666                         add { Events.AddHandler (RegionChangedEvent, value); }
6667                         remove { Events.RemoveHandler (RegionChangedEvent, value); }
6668                 }
6669
6670                 [EditorBrowsable (EditorBrowsableState.Advanced)]
6671                 public event EventHandler Resize {
6672                         add { Events.AddHandler (ResizeEvent, value); }
6673                         remove { Events.RemoveHandler (ResizeEvent, value); }
6674                 }
6675
6676                 public event EventHandler RightToLeftChanged {
6677                         add { Events.AddHandler (RightToLeftChangedEvent, value); }
6678                         remove { Events.RemoveHandler (RightToLeftChangedEvent, value); }
6679                 }
6680
6681                 public event EventHandler SizeChanged {
6682                         add { Events.AddHandler (SizeChangedEvent, value); }
6683                         remove { Events.RemoveHandler (SizeChangedEvent, value); }
6684                 }
6685
6686                 public event EventHandler StyleChanged {
6687                         add { Events.AddHandler (StyleChangedEvent, value); }
6688                         remove { Events.RemoveHandler (StyleChangedEvent, value); }
6689                 }
6690
6691                 public event EventHandler SystemColorsChanged {
6692                         add { Events.AddHandler (SystemColorsChangedEvent, value); }
6693                         remove { Events.RemoveHandler (SystemColorsChangedEvent, value); }
6694                 }
6695
6696                 public event EventHandler TabIndexChanged {
6697                         add { Events.AddHandler (TabIndexChangedEvent, value); }
6698                         remove { Events.RemoveHandler (TabIndexChangedEvent, value); }
6699                 }
6700
6701                 public event EventHandler TabStopChanged {
6702                         add { Events.AddHandler (TabStopChangedEvent, value); }
6703                         remove { Events.RemoveHandler (TabStopChangedEvent, value); }
6704                 }
6705
6706                 public event EventHandler TextChanged {
6707                         add { Events.AddHandler (TextChangedEvent, value); }
6708                         remove { Events.RemoveHandler (TextChangedEvent, value); }
6709                 }
6710
6711                 public event EventHandler Validated {
6712                         add { Events.AddHandler (ValidatedEvent, value); }
6713                         remove { Events.RemoveHandler (ValidatedEvent, value); }
6714                 }
6715
6716                 public event CancelEventHandler Validating {
6717                         add { Events.AddHandler (ValidatingEvent, value); }
6718                         remove { Events.RemoveHandler (ValidatingEvent, value); }
6719                 }
6720
6721                 public event EventHandler VisibleChanged {
6722                         add { Events.AddHandler (VisibleChangedEvent, value); }
6723                         remove { Events.RemoveHandler (VisibleChangedEvent, value); }
6724                 }
6725
6726                 #endregion      // Events
6727         }
6728 }