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