2006-12-21 Rolf Bjarne Kvinge <RKvinge@novell.com>
[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 // COMPLETE 
34
35 #undef DebugRecreate
36 #undef DebugFocus
37
38 using System;
39 using System.ComponentModel;
40 using System.ComponentModel.Design;
41 using System.ComponentModel.Design.Serialization;
42 using System.Collections;
43 using System.Diagnostics;
44 using System.Drawing;
45 using System.Drawing.Drawing2D;
46 using System.Reflection;
47 using System.Runtime.InteropServices;
48 using System.Security;
49 using System.Threading;
50
51 namespace System.Windows.Forms
52 {
53 #if NET_2_0
54         [ComVisible(true)]
55         [ClassInterface (ClassInterfaceType.AutoDispatch)]
56 #endif
57         [Designer("System.Windows.Forms.Design.ControlDesigner, " + Consts.AssemblySystem_Design, "System.ComponentModel.Design.IDesigner")]
58         [DefaultProperty("Text")]
59         [DefaultEvent("Click")]
60         [DesignerSerializer("System.Windows.Forms.Design.ControlCodeDomSerializer, " + Consts.AssemblySystem_Design, "System.ComponentModel.Design.Serialization.CodeDomSerializer, " + Consts.AssemblySystem_Design)]
61         [ToolboxItemFilter("System.Windows.Forms")]
62         public class Control : Component, ISynchronizeInvoke, IWin32Window
63 #if NET_2_0
64                 , IBindableComponent, IDropTarget
65 #endif
66         {
67                 #region Local Variables
68
69                 // Basic
70                 internal Rectangle              bounds;                 // bounding rectangle for control (client area + decorations)
71                 Rectangle explicit_bounds; // explicitly set bounds
72                 internal object                 creator_thread;         // thread that created the control
73                 internal ControlNativeWindow    window;                 // object for native window handle
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                 Size client_size; // size of the client area (window excluding decorations)
92                 Rectangle client_rect; // rectangle with the client area (window excluding decorations)
93                 ControlStyles control_style; // rather win32-specific, style bits for control
94                 ImeMode ime_mode;
95                 bool layout_pending; // true if our parent needs to re-layout us
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
110                 // Layout
111                 int layout_suspended;
112                 internal AnchorStyles           anchor_style;           // anchoring requirements for our control
113                 internal DockStyle              dock_style;             // docking requirements for our control (supercedes anchoring)
114                 // Please leave the next 4 as internal until DefaultLayout (2.0) is rewritten
115                 internal int                    dist_left;              // distance to the left border of the parent
116                 internal int                    dist_top; // distance to the top border of the parent
117                 internal int                    dist_right; // distance to the right border of the parent
118                 internal int                    dist_bottom; // distance to the bottom border of the parent
119
120                 // to be categorized...
121                 ControlCollection child_controls; // our children
122                 Control parent; // our parent control
123                 AccessibleObject accessibility_object; // object that contains accessibility information about our control
124                 BindingContext binding_context;
125                 RightToLeft right_to_left; // drawing direction for control
126                 ContextMenu context_menu; // Context menu associated with the control
127
128                 // double buffering
129                 Graphics backbuffer_dc;
130                 object backbuffer;
131                 Region invalid_region;
132
133                 ControlBindingsCollection data_bindings;
134
135 #if NET_2_0
136                 internal bool use_compatible_text_rendering;
137                 static bool verify_thread_handle;
138                 Padding padding;
139                 ImageLayout backgroundimage_layout;
140                 Size maximum_size;
141                 Size minimum_size;
142                 Size preferred_size;
143                 Padding margin;
144                 Layout.LayoutEngine layout_engine;
145 #endif
146
147                 #endregion      // Local Variables
148
149                 #region Private Classes
150                 // This helper class allows us to dispatch messages to Control.WndProc
151                 internal class ControlNativeWindow : NativeWindow {
152                         private Control owner;
153
154                         public ControlNativeWindow(Control control) : base() {
155                                 this.owner=control;
156                         }
157
158
159                         public Control Owner {
160                                 get {
161                                         return owner;
162                                 }
163                         }
164
165                         static internal Control ControlFromHandle(IntPtr hWnd) {
166                                 ControlNativeWindow     window;
167
168                                 window = (ControlNativeWindow)window_collection[hWnd];
169                                 if (window != null) {
170                                         return window.owner;
171                                 }
172
173                                 return null;
174                         }
175
176                         static internal Control ControlFromChildHandle (IntPtr handle) {
177                                 ControlNativeWindow     window;
178
179                                 Hwnd hwnd = Hwnd.ObjectFromHandle (handle);
180                                 while (hwnd != null) {
181                                         window = (ControlNativeWindow)window_collection[hwnd.Handle];
182                                         if (window != null) {
183                                                 return window.owner;
184                                         }
185                                         hwnd = hwnd.Parent;
186                                 }
187
188                                 return null;
189                         }
190
191                         protected override void WndProc(ref Message m) {
192                                 owner.WndProc(ref m);
193                         }
194                 }
195                 #endregion
196                 
197                 #region Public Classes
198                 [ComVisible(true)]
199                 public class ControlAccessibleObject : AccessibleObject {
200                         Control owner;
201
202                         #region ControlAccessibleObject Constructors
203                         public ControlAccessibleObject(Control ownerControl)
204                                 : base (ownerControl)
205                         {
206                                 this.owner = ownerControl;
207                         }
208                         #endregion      // ControlAccessibleObject Constructors
209
210                         #region ControlAccessibleObject Public Instance Properties
211                         public override string DefaultAction {
212                                 get {
213                                         return base.DefaultAction;
214                                 }
215                         }
216
217                         public override string Description {
218                                 get {
219                                         return base.Description;
220                                 }
221                         }
222
223                         public IntPtr Handle {
224                                 get {
225                                         return owner.Handle;
226                                 }
227
228                                 set {
229                                         // We don't want to let them set it
230                                 }
231                         }
232
233                         public override string Help {
234                                 get {
235                                         return base.Help;
236                                 }
237                         }
238
239                         public override string KeyboardShortcut {
240                                 get {
241                                         return base.KeyboardShortcut;
242                                 }
243                         }
244
245                         public override string Name {
246                                 get {
247                                         return base.Name;
248                                 }
249
250                                 set {
251                                         base.Name = value;
252                                 }
253                         }
254
255                         public Control Owner {
256                                 get {
257                                         return owner;
258                                 }
259                         }
260
261                         public override AccessibleObject Parent {
262                                 get {
263                                         return base.Parent;
264                                 }
265                         }
266
267
268                         public override AccessibleRole Role {
269                                 get {
270                                         return base.Role;
271                                 }
272                         }
273                         #endregion      // ControlAccessibleObject Public Instance Properties
274
275                         #region ControlAccessibleObject Public Instance Methods
276                         public override int GetHelpTopic(out string FileName) {
277                                 return base.GetHelpTopic (out FileName);
278                         }
279
280                         [MonoTODO("Implement this and tie it into Control.AccessibilityNotifyClients")]
281                         public void NotifyClients(AccessibleEvents accEvent) {
282                                 throw new NotImplementedException();
283                         }
284
285                         [MonoTODO("Implement this and tie it into Control.AccessibilityNotifyClients")]
286                         public void NotifyClients(AccessibleEvents accEvent, int childID) {
287                                 throw new NotImplementedException();
288                         }
289
290                         public override string ToString() {
291                                 return "ControlAccessibleObject: Owner = " + owner.ToString() + ", Text: " + owner.text;
292                         }
293
294                         #endregion      // ControlAccessibleObject Public Instance Methods
295                 }
296
297 #if NET_2_0
298                 [ComVisible (false)]
299 #else
300                 [DesignerSerializer("System.Windows.Forms.Design.ControlCollectionCodeDomSerializer, " + Consts.AssemblySystem_Design, "System.ComponentModel.Design.Serialization.CodeDomSerializer, " + Consts.AssemblySystem_Design)]
301 #endif
302                 [ListBindable(false)]
303                 public class ControlCollection : IList, ICollection, ICloneable, IEnumerable {
304                         #region ControlCollection Local Variables
305                         ArrayList list;
306                         ArrayList impl_list;
307                         Control[] all_controls;
308                         Control owner;
309                         #endregion      // ControlCollection Local Variables
310
311                         #region ControlCollection Public Constructor
312                         public ControlCollection(Control owner) {
313                                 this.owner=owner;
314                                 this.list=new ArrayList();
315                         }
316                         #endregion
317
318                         #region ControlCollection Public Instance Properties
319                         public int Count {
320                                 get {
321                                         return list.Count;
322                                 }
323                         }
324
325                         public bool IsReadOnly {
326                                 get {
327                                         return list.IsReadOnly;
328                                 }
329                         }
330
331                         public virtual Control this[int index] {
332                                 get {
333                                         if (index < 0 || index >= list.Count) {
334                                                 throw new ArgumentOutOfRangeException("index", index, "ControlCollection does not have that many controls");
335                                         }
336                                         return (Control)list[index];
337                                 }
338                         }
339                         #endregion // ControlCollection Public Instance Properties
340                         
341                         #region ControlCollection Private Instance Methods
342                         public virtual void Add (Control value)
343                         {
344                                 if (value == null)
345                                         return;
346                                 
347                                 if (Contains (value)) {
348                                         owner.PerformLayout();
349                                         return;
350                                 }
351
352                                 if (value.tab_index == -1) {
353                                         int     end;
354                                         int     index;
355                                         int     use;
356
357                                         use = 0;
358                                         end = owner.child_controls.Count;
359                                         for (int i = 0; i < end; i++) {
360                                                 index = owner.child_controls[i].tab_index;
361                                                 if (index >= use) {
362                                                         use = index + 1;
363                                                 }
364                                         }
365                                         value.tab_index = use;
366                                 }
367
368                                 if (value.parent != null) {
369                                         value.parent.Controls.Remove(value);
370                                 }
371
372                                 all_controls = null;
373                                 list.Add (value);
374
375                                 value.ChangeParent(owner);
376
377                                 value.InitLayout();
378
379                                 owner.UpdateChildrenZOrder();
380                                 owner.PerformLayout(value, "Parent");
381                                 owner.OnControlAdded(new ControlEventArgs(value));
382                         }
383                         
384                         internal void AddToList (Control c)
385                         {
386                                 all_controls = null;
387                                 list.Add (c);
388                         }
389
390                         internal virtual void AddImplicit (Control control)
391                         {
392                                 if (impl_list == null)
393                                         impl_list = new ArrayList ();
394
395                                 if (AllContains (control))
396                                         return;
397
398                                 all_controls = null;
399                                 impl_list.Add (control);
400
401                                 control.ChangeParent (owner);
402                                 control.InitLayout ();
403                                 owner.UpdateChildrenZOrder ();
404                                 owner.PerformLayout (control, "Parent");
405                                 owner.OnControlAdded (new ControlEventArgs (control));
406                         }
407 #if NET_2_0
408                         [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
409 #endif
410                         public virtual void AddRange (Control[] controls)
411                         {
412                                 if (controls == null)
413                                         throw new ArgumentNullException ("controls");
414
415                                 owner.SuspendLayout ();
416
417                                 try {
418                                         for (int i = 0; i < controls.Length; i++) 
419                                                 Add (controls[i]);
420                                 } finally {
421                                         owner.ResumeLayout ();
422                                 }
423                         }
424
425                         internal virtual void AddRangeImplicit (Control [] controls)
426                         {
427                                 if (controls == null)
428                                         throw new ArgumentNullException ("controls");
429
430                                 owner.SuspendLayout ();
431
432                                 try {
433                                         for (int i = 0; i < controls.Length; i++)
434                                                 AddImplicit (controls [i]);
435                                 } finally {
436                                         owner.ResumeLayout ();
437                                 }
438                         }
439
440                         public virtual void Clear ()
441                         {
442                                 all_controls = null;
443
444                                 // MS sends remove events in reverse order
445                                 while (list.Count > 0) {
446                                         Remove((Control)list[list.Count - 1]);
447                                 }
448                         }
449
450                         internal virtual void ClearImplicit ()
451                         {
452                                 if (impl_list == null)
453                                         return;
454                                 all_controls = null;
455                                 impl_list.Clear ();
456                         }
457
458                         public bool Contains (Control value)
459                         {
460                                 for (int i = list.Count; i > 0; ) {
461                                         i--;
462                                         
463                                         if (list [i] == value) {
464                                                 // Do we need to do anything here?
465                                                 return true;
466                                         }
467                                 }
468                                 return false;
469                         }
470
471                         internal bool ImplicitContains (Control value)
472                         {
473                                 if (impl_list == null)
474                                         return false;
475
476                                 for (int i = impl_list.Count; i > 0; ) {
477                                         i--;
478                                         
479                                         if (impl_list [i] == value) {
480                                                 // Do we need to do anything here?
481                                                 return true;
482                                         }
483                                 }
484                                 return false;
485                         }
486
487                         internal bool AllContains (Control value)
488                         {
489                                 return Contains (value) || ImplicitContains (value);
490                         }
491
492                         public void CopyTo (Array array, int index)
493                         {
494                                 list.CopyTo(array, index);
495                         }
496
497                         public override bool Equals(object other) {
498                                 if (other is ControlCollection && (((ControlCollection)other).owner==this.owner)) {
499                                         return(true);
500                                 } else {
501                                         return(false);
502                                 }
503                         }
504
505                         public int GetChildIndex(Control child) {
506                                 return GetChildIndex(child, false);
507                         }
508
509                         public int GetChildIndex(Control child, bool throwException) {
510                                 int index;
511
512                                 index=list.IndexOf(child);
513
514                                 if (index==-1 && throwException) {
515                                         throw new ArgumentException("Not a child control", "child");
516                                 }
517                                 return index;
518                         }
519
520                         public IEnumerator GetEnumerator() {
521                                 return list.GetEnumerator();
522                         }
523
524                         internal IEnumerator GetAllEnumerator ()
525                         {
526                                 Control [] res = GetAllControls ();
527                                 return res.GetEnumerator ();
528                         }
529
530                         internal Control [] GetAllControls ()
531                         {
532                                 if (all_controls != null)
533                                         return all_controls;
534
535                                 if (impl_list == null) {
536                                         all_controls = (Control []) list.ToArray (typeof (Control));
537                                         return all_controls;
538                                 }
539                                 
540                                 all_controls = new Control [list.Count + impl_list.Count];
541                                 impl_list.CopyTo (all_controls);
542                                 list.CopyTo (all_controls, impl_list.Count);
543
544                                 return all_controls;
545                         }
546
547                         public override int GetHashCode() {
548                                 return base.GetHashCode();
549                         }
550
551                         public int IndexOf(Control control) {
552                                 return list.IndexOf(control);
553                         }
554
555                         public virtual void Remove(Control value) {
556                                 if (value == null)
557                                         return;
558
559                                 owner.PerformLayout(value, "Parent");
560                                 owner.OnControlRemoved(new ControlEventArgs(value));
561
562                                 all_controls = null;
563                                 list.Remove(value);
564
565                                 value.ChangeParent(null);
566
567                                 owner.UpdateChildrenZOrder();
568                         }
569
570                         internal virtual void RemoveImplicit (Control control)
571                         {
572                                 if (impl_list != null) {
573                                         all_controls = null;
574                                         owner.PerformLayout (control, "Parent");
575                                         owner.OnControlRemoved (new ControlEventArgs (control));
576                                         impl_list.Remove (control);
577                                 }
578                                 control.ChangeParent (null);
579                                 owner.UpdateChildrenZOrder ();
580                         }
581
582                         public void RemoveAt(int index) {
583                                 if (index < 0 || index >= list.Count) {
584                                         throw new ArgumentOutOfRangeException("index", index, "ControlCollection does not have that many controls");
585                                 }
586                                 Remove ((Control)list[index]);
587                         }
588
589                         public void SetChildIndex(Control child, int newIndex) {
590                                 if (child == null)
591                                         throw new ArgumentNullException ("child");
592
593                                 int     old_index;
594
595                                 old_index=list.IndexOf(child);
596                                 if (old_index==-1) {
597                                         throw new ArgumentException("Not a child control", "child");
598                                 }
599
600                                 if (old_index==newIndex) {
601                                         return;
602                                 }
603
604                                 all_controls = null;
605                                 list.RemoveAt(old_index);
606
607                                 if (newIndex>list.Count) {
608                                         list.Add(child);
609                                 } else {
610                                         list.Insert(newIndex, child);
611                                 }
612                                 child.UpdateZOrder();
613                                 owner.PerformLayout();
614                         }
615                         #endregion // ControlCollection Private Instance Methods
616
617                         #region ControlCollection Interface Properties
618                         object IList.this[int index] {
619                                 get {
620                                         if (index<0 || index>=list.Count) {
621                                                 throw new ArgumentOutOfRangeException("index", index, "ControlCollection does not have that many controls");
622                                         }
623                                         return this[index];
624                                 }
625
626                                 set {
627                                         if (!(value is Control)) {
628                                                 throw new ArgumentException("Object of type Control required", "value");
629                                         }
630
631                                         all_controls = null;
632                                         Control ctrl = (Control) value;
633                                         list[index]= ctrl;
634
635                                         ctrl.ChangeParent(owner);
636
637                                         ctrl.InitLayout();
638
639                                         owner.UpdateChildrenZOrder();
640                                         owner.PerformLayout(ctrl, "Parent");
641                                 }
642                         }
643
644                         bool IList.IsFixedSize {
645                                 get {
646                                         return false;
647                                 }
648                         }
649
650                         bool ICollection.IsSynchronized {
651                                 get {
652                                         return list.IsSynchronized;
653                                 }
654                         }
655
656                         object ICollection.SyncRoot {
657                                 get {
658                                         return list.SyncRoot;
659                                 }
660                         }
661                         #endregion // ControlCollection Interface Properties
662
663                         #region ControlCollection Interface Methods
664                         int IList.Add(object value) {
665                                 if (value == null) {
666                                         throw new ArgumentNullException("value", "Cannot add null controls");
667                                 }
668
669                                 if (!(value is Control)) {
670                                         throw new ArgumentException("Object of type Control required", "value");
671                                 }
672
673                                 return list.Add(value);
674                         }
675
676                         bool IList.Contains(object value) {
677                                 if (!(value is Control)) {
678                                         throw new ArgumentException("Object of type Control required", "value");
679                                 }
680
681                                 return this.Contains((Control) value);
682                         }
683
684                         int IList.IndexOf(object value) {
685                                 if (!(value is Control)) {
686                                         throw new ArgumentException("Object of type Control  required", "value");
687                                 }
688
689                                 return this.IndexOf((Control) value);
690                         }
691
692                         void IList.Insert(int index, object value) {
693                                 if (!(value is Control)) {
694                                         throw new ArgumentException("Object of type Control required", "value");
695                                 }
696                                 all_controls = null;
697                                 list.Insert(index, value);
698                         }
699
700                         void IList.Remove(object value) {
701                                 if (!(value is Control)) {
702                                         throw new ArgumentException("Object of type Control required", "value");
703                                 }
704                                 all_controls = null;
705                                 list.Remove(value);
706                         }
707
708                         Object ICloneable.Clone() {
709                                 ControlCollection clone = new ControlCollection(this.owner);
710                                 clone.list=(ArrayList)list.Clone();             // FIXME: Do we need this?
711                                 return clone;
712                         }
713                         #endregion // ControlCollection Interface Methods
714                 }
715                 #endregion      // ControlCollection Class
716                 
717                 #region Public Constructors
718                 public Control()
719                 {
720                         anchor_style = AnchorStyles.Top | AnchorStyles.Left;
721
722                         is_created = false;
723                         is_visible = true;
724                         is_captured = false;
725                         is_disposed = false;
726                         is_enabled = true;
727                         is_entered = false;
728                         layout_pending = false;
729                         is_toplevel = false;
730                         causes_validation = true;
731                         has_focus = false;
732                         layout_suspended = 0;
733                         mouse_clicks = 1;
734                         tab_index = -1;
735                         cursor = null;
736                         right_to_left = RightToLeft.Inherit;
737                         border_style = BorderStyle.None;
738                         background_color = Color.Empty;
739                         dist_left = 0;
740                         dist_right = 0;
741                         dist_top = 0;
742                         dist_bottom = 0;
743                         tab_stop = true;
744                         ime_mode = ImeMode.Inherit;
745
746 #if NET_2_0
747                         backgroundimage_layout = ImageLayout.Tile;
748                         use_compatible_text_rendering = Application.use_compatible_text_rendering;
749                         padding = new Padding(0);
750                         maximum_size = new Size();
751                         minimum_size = new Size();
752                         preferred_size = new Size();
753                         margin = this.DefaultMargin;
754                         layout_engine = this.LayoutEngine;
755 #endif
756
757                         control_style = ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | 
758                                         ControlStyles.Selectable | ControlStyles.StandardClick | 
759                                         ControlStyles.StandardDoubleClick;
760 #if NET_2_0
761                         control_style |= ControlStyles.UseTextForAccessibility;
762 #endif
763
764                         parent = null;
765                         background_image = null;
766                         text = string.Empty;
767                         name = string.Empty;
768
769                         window = new ControlNativeWindow(this);
770                         child_controls = CreateControlsInstance();
771                         client_size = new Size(DefaultSize.Width, DefaultSize.Height);
772                         client_rect = new Rectangle(0, 0, DefaultSize.Width, DefaultSize.Height);
773                         XplatUI.CalculateWindowRect(ref client_rect, CreateParams.Style, CreateParams.ExStyle, null, out bounds);
774                         if ((CreateParams.Style & (int)WindowStyles.WS_CHILD) == 0) {
775                                 bounds.X=-1;
776                                 bounds.Y=-1;
777                         }
778                 }
779
780                 public Control(Control parent, string text) : this() {
781                         Text=text;
782                         Parent=parent;
783                 }
784
785                 public Control(Control parent, string text, int left, int top, int width, int height) : this() {
786                         Parent=parent;
787                         bounds.X=left;
788                         bounds.Y=top;
789                         bounds.Width=width;
790                         bounds.Height=height;
791                         SetBounds(left, top, width, height, BoundsSpecified.All);
792                         Text=text;
793                 }
794
795                 public Control(string text) : this() {
796                         Text=text;
797                 }
798
799                 public Control(string text, int left, int top, int width, int height) : this() {
800                         bounds.X=left;
801                         bounds.Y=top;
802                         bounds.Width=width;
803                         bounds.Height=height;
804                         SetBounds(left, top, width, height, BoundsSpecified.All);
805                         Text=text;
806                 }
807
808                 private delegate void RemoveDelegate(object c);
809
810                 protected override void Dispose(bool disposing) {
811                         if (!is_disposed && disposing) {
812                                 Capture = false;
813
814                                 DisposeBackBuffer ();
815
816                                 if (invalid_region!=null) {
817                                         invalid_region.Dispose();
818                                         invalid_region=null;
819                                 }
820                                 if (this.InvokeRequired) {
821                                         if (Application.MessageLoop) {
822                                                 this.BeginInvokeInternal(new MethodInvoker(DestroyHandle), null, true);
823                                         }
824                                 } else {
825                                         DestroyHandle();
826                                 }
827
828                                 if (parent != null) {
829                                         parent.Controls.Remove(this);
830                                 }
831
832                                 Control [] children = child_controls.GetAllControls ();
833                                 for (int i=0; i<children.Length; i++) {
834                                         children[i].parent = null;      // Need to set to null or our child will try and remove from ourselves and crash
835                                         children[i].Dispose();
836                                 }
837                         }
838                         is_disposed = true;
839                         is_visible = false;
840                         base.Dispose(disposing);
841                 }
842                 #endregion      // Public Constructors
843
844                 #region Internal Properties
845                 internal BorderStyle InternalBorderStyle {
846                         get {
847                                 return border_style;
848                         }
849
850                         set {
851                                 if (!Enum.IsDefined (typeof (BorderStyle), value))
852                                         throw new InvalidEnumArgumentException (string.Format("Enum argument value '{0}' is not valid for BorderStyle", value));
853
854                                 if (border_style != value) {
855                                         border_style = value;
856
857                                         if (IsHandleCreated) {
858                                                 XplatUI.SetBorderStyle(window.Handle, (FormBorderStyle)border_style);
859                                                 Refresh();
860                                         }
861                                 }
862                         }
863                 }
864                 #endregion      // Internal Properties
865
866                 #region Private & Internal Methods
867                 
868 #if NET_2_0
869                 void IDropTarget.OnDragDrop (DragEventArgs e)
870                 {
871                         OnDragDrop (e);
872                 }
873                 
874                 void IDropTarget.OnDragEnter (DragEventArgs e)
875                 {
876                         OnDragEnter (e);
877                 }
878                 
879                 void IDropTarget.OnDragLeave (EventArgs e)
880                 {
881                         OnDragLeave (e);
882                 }
883
884                 void IDropTarget.OnDragOver (DragEventArgs e)
885                 {
886                         OnDragOver (e);
887                 }
888 #endif
889
890                 internal IAsyncResult BeginInvokeInternal (Delegate method, object [] args, bool disposing) {
891                         AsyncMethodResult       result;
892                         AsyncMethodData         data;
893
894                         if (!disposing) {
895                                 Control p = this;
896                                 do {
897                                         if (!p.IsHandleCreated) {
898                                                 throw new InvalidOperationException("Cannot call Invoke or InvokeAsync on a control until the window handle is created");
899                                         }
900                                         p = p.parent;
901                                 } while (p != null);
902                         }
903
904                         result = new AsyncMethodResult ();
905                         data = new AsyncMethodData ();
906
907                         data.Handle = window.Handle;
908                         data.Method = method;
909                         data.Args = args;
910                         data.Result = result;
911
912 #if NET_2_0
913                         if (!ExecutionContext.IsFlowSuppressed ()) {
914                                 data.Context = ExecutionContext.Capture ();
915                         }
916 #else
917 #if !MWF_ON_MSRUNTIME
918                         if (SecurityManager.SecurityEnabled) {
919                                 data.Stack = CompressedStack.GetCompressedStack ();
920                         }
921 #endif
922 #endif
923
924                         XplatUI.SendAsyncMethod (data);
925                         return result;
926                 }
927
928                 
929                 internal void PointToClient (ref int x, ref int y)
930                 {
931                         XplatUI.ScreenToClient (Handle, ref x, ref y);
932                 }
933
934                 internal void PointToScreen (ref int x, ref int y)
935                 {
936                         XplatUI.ClientToScreen (Handle, ref x, ref y);
937                 }
938
939                 internal bool IsRecreating {
940                         get {
941                                 return is_recreating;
942                         }
943                 }
944
945                 internal Graphics DeviceContext {
946                         get { return Hwnd.bmp_g; }
947                 }
948
949                 private void InvalidateBackBuffer ()
950                 {
951                         if (invalid_region != null)
952                                 invalid_region.Dispose();
953                         invalid_region = new Region (ClientRectangle);
954                 }
955
956                 private void CreateBackBuffer ()
957                 {
958                         if (backbuffer != null)
959                                 return;
960
961                         int width = Width;
962                         int height = Height;
963
964                         if (width < 1) width = 1;
965                         if (height < 1) height = 1;
966
967                         XplatUI.CreateOffscreenDrawable (Handle, width, height, out backbuffer, out backbuffer_dc);
968                         InvalidateBackBuffer ();
969                 }
970
971                 private void DisposeBackBuffer ()
972                 {
973                         if (backbuffer == null)
974                                 return;
975
976                         XplatUI.DestroyOffscreenDrawable (backbuffer, backbuffer_dc);
977                         backbuffer = null;
978                         backbuffer_dc = null;
979
980
981                         if (invalid_region != null)
982                                 invalid_region.Dispose ();
983                         invalid_region = null;
984                 }
985
986                 internal static void SetChildColor(Control parent) {
987                         Control child;
988
989                         for (int i=0; i < parent.child_controls.Count; i++) {
990                                 child=parent.child_controls[i];
991                                 if (child.child_controls.Count>0) {
992                                         SetChildColor(child);
993                                 }
994                         }
995                 }
996
997                 internal bool Select(Control control) {
998                         IContainerControl       container;
999
1000                         if (control == null) {
1001                                 return false;
1002                         }
1003
1004                         container = GetContainerControl();
1005                         if (container != null) {
1006                                 container.ActiveControl = control;
1007                         }
1008                         if (control.IsHandleCreated) {
1009                                 XplatUI.SetFocus(control.window.Handle);
1010                         }
1011                         return true;
1012                 }
1013
1014                 internal void SelectChild (Control control)
1015                 {
1016                         if (control.IsHandleCreated)
1017                                 XplatUI.SetFocus (control.window.Handle);
1018                 }
1019
1020                 internal virtual void DoDefaultAction() {
1021                         // Only here to be overriden by our actual controls; this is needed by the accessibility class
1022                 }
1023
1024                 internal static IntPtr MakeParam (int low, int high){
1025                         return new IntPtr (high << 16 | low & 0xffff);
1026                 }
1027
1028                 internal static int LowOrder (int param) {
1029                         return ((int)(short)(param & 0xffff));
1030                 }
1031
1032                 internal static int HighOrder (int param) {
1033                         return ((int)(short)(param >> 16));
1034                 }
1035
1036                 // This method exists so controls overriding OnPaintBackground can have default background painting done
1037                 internal virtual void PaintControlBackground (PaintEventArgs pevent)
1038                 {
1039                         if (GetStyle(ControlStyles.SupportsTransparentBackColor) && (BackColor.A != 0xff)) {
1040                                 if (parent != null) {
1041                                         PaintEventArgs  parent_pe;
1042                                         GraphicsState   state;
1043
1044                                         parent_pe = new PaintEventArgs(pevent.Graphics, new Rectangle(pevent.ClipRectangle.X + Left, pevent.ClipRectangle.Y + Top, pevent.ClipRectangle.Width, pevent.ClipRectangle.Height));
1045
1046                                         state = parent_pe.Graphics.Save();
1047                                         parent_pe.Graphics.TranslateTransform(-Left, -Top);
1048                                         parent.OnPaintBackground(parent_pe);
1049                                         parent_pe.Graphics.Restore(state);
1050
1051                                         state = parent_pe.Graphics.Save();
1052                                         parent_pe.Graphics.TranslateTransform(-Left, -Top);
1053                                         parent.OnPaint(parent_pe);
1054                                         parent_pe.Graphics.Restore(state);
1055                                         parent_pe.SetGraphics(null);
1056                                 }
1057                         }
1058
1059                         if ((clip_region != null) && (XplatUI.UserClipWontExposeParent)) {
1060                                 if (parent != null) {
1061                                         PaintEventArgs  parent_pe;
1062                                         Region          region;
1063                                         GraphicsState   state;
1064                                         Hwnd            hwnd;
1065
1066                                         hwnd = Hwnd.ObjectFromHandle(Handle);
1067
1068                                         if (hwnd != null) {
1069                                                 parent_pe = new PaintEventArgs(pevent.Graphics, new Rectangle(pevent.ClipRectangle.X + Left, pevent.ClipRectangle.Y + Top, pevent.ClipRectangle.Width, pevent.ClipRectangle.Height));
1070
1071                                                 region = new Region ();
1072                                                 region.MakeEmpty();
1073                                                 region.Union(ClientRectangle);
1074
1075                                                 foreach (Rectangle r in hwnd.ClipRectangles) {
1076                                                         region.Union (r);
1077                                                 }
1078
1079                                                 state = parent_pe.Graphics.Save();
1080                                                 parent_pe.Graphics.Clip = region;
1081
1082                                                 parent_pe.Graphics.TranslateTransform(-Left, -Top);
1083                                                 parent.OnPaintBackground(parent_pe);
1084                                                 parent_pe.Graphics.Restore(state);
1085
1086                                                 state = parent_pe.Graphics.Save();
1087                                                 parent_pe.Graphics.Clip = region;
1088
1089                                                 parent_pe.Graphics.TranslateTransform(-Left, -Top);
1090                                                 parent.OnPaint(parent_pe);
1091                                                 parent_pe.Graphics.Restore(state);
1092                                                 parent_pe.SetGraphics(null);
1093
1094                                                 region.Intersect(clip_region);
1095                                                 pevent.Graphics.Clip = region;
1096                                         }
1097                                 }
1098                         }
1099
1100                         if (background_image == null) {
1101                                 pevent.Graphics.FillRectangle(ThemeEngine.Current.ResPool.GetSolidBrush(BackColor), new Rectangle(pevent.ClipRectangle.X - 1, pevent.ClipRectangle.Y - 1, pevent.ClipRectangle.Width + 2, pevent.ClipRectangle.Height + 2));
1102                                 return;
1103                         }
1104
1105                         DrawBackgroundImage (pevent.Graphics);
1106                 }
1107
1108                 void DrawBackgroundImage (Graphics g)
1109                 {
1110 #if NET_2_0
1111                         Rectangle drawing_rectangle = new Rectangle ();
1112                         g.FillRectangle (ThemeEngine.Current.ResPool.GetSolidBrush (BackColor), ClientRectangle);
1113                                 
1114                         switch (backgroundimage_layout)
1115                         {
1116                         case ImageLayout.Tile:
1117                                 using (TextureBrush b = new TextureBrush (background_image, WrapMode.Tile)) {
1118                                         g.FillRectangle (b, ClientRectangle);
1119                                 }
1120                                 return;
1121                         case ImageLayout.Center:
1122                                 drawing_rectangle.Location = new Point (ClientSize.Width / 2 - background_image.Width / 2, ClientSize.Height / 2 - background_image.Height / 2);
1123                                 drawing_rectangle.Size = background_image.Size;
1124                                 break;
1125                         case ImageLayout.None:
1126                                 drawing_rectangle.Location = Point.Empty;
1127                                 drawing_rectangle.Size = background_image.Size;
1128                                 break;
1129                         case ImageLayout.Stretch:
1130                                 drawing_rectangle = ClientRectangle;
1131                                 break;
1132                         case ImageLayout.Zoom:
1133                                 drawing_rectangle = ClientRectangle;
1134                                 if ((float)background_image.Width / (float)background_image.Height < (float)drawing_rectangle.Width / (float) drawing_rectangle.Height) {
1135                                         drawing_rectangle.Width = (int) (background_image.Width * ((float)drawing_rectangle.Height / (float)background_image.Height));
1136                                         drawing_rectangle.X = (ClientRectangle.Width - drawing_rectangle.Width) / 2;
1137                                 } else {
1138                                         drawing_rectangle.Height = (int) (background_image.Height * ((float)drawing_rectangle.Width / (float)background_image.Width));
1139                                         drawing_rectangle.Y = (ClientRectangle.Height - drawing_rectangle.Height) / 2;
1140                                 }
1141                                 break;
1142                         default:
1143                                 return;
1144                         }
1145
1146                         g.DrawImage (background_image, drawing_rectangle);
1147
1148 #else
1149                         using (TextureBrush b = new TextureBrush (background_image, WrapMode.Tile)) {
1150                                 g.FillRectangle (b, ClientRectangle);
1151                         }
1152 #endif
1153                 }
1154
1155                 internal virtual void DndEnter (DragEventArgs e)
1156                 {
1157                         try {
1158                                 OnDragEnter (e);
1159                         } catch { }
1160                 }
1161
1162                 internal virtual void DndOver (DragEventArgs e)
1163                 {
1164                         try {
1165                                 OnDragOver (e);
1166                         } catch { }
1167                 }
1168
1169                 internal virtual void DndDrop (DragEventArgs e)
1170                 {
1171                         try {
1172                                 OnDragDrop (e);
1173                         } catch (Exception exc) {
1174                                 Console.Error.WriteLine ("MWF: Exception while dropping:");
1175                                 Console.Error.WriteLine (exc);
1176                         }
1177                 }
1178
1179                 internal virtual void DndLeave (EventArgs e)
1180                 {
1181                         try {
1182                                 OnDragLeave (e);
1183                         } catch { }
1184                 }
1185
1186                 internal virtual void DndFeedback(GiveFeedbackEventArgs e)
1187                 {
1188                         try {
1189                                 OnGiveFeedback(e);
1190                         } catch { }
1191                 }
1192
1193                 internal virtual void DndContinueDrag(QueryContinueDragEventArgs e)
1194                 {
1195                         try {
1196                                 OnQueryContinueDrag(e);
1197                         } catch { }
1198                 }
1199                 
1200                 internal static MouseButtons FromParamToMouseButtons (int param) {              
1201                         MouseButtons buttons = MouseButtons.None;
1202                                         
1203                         if ((param & (int) MsgButtons.MK_LBUTTON) != 0)
1204                                 buttons |= MouseButtons.Left;
1205                         
1206                         if ((param & (int) MsgButtons.MK_MBUTTON) != 0)
1207                                 buttons |= MouseButtons.Middle;
1208                                 
1209                         if ((param & (int) MsgButtons.MK_RBUTTON) != 0)
1210                                 buttons |= MouseButtons.Right;
1211                                 
1212                         return buttons;
1213
1214                 }
1215
1216                 internal void FireEnter ()
1217                 {
1218                         OnEnter (EventArgs.Empty);
1219                 }
1220
1221                 internal void FireLeave ()
1222                 {
1223                         OnLeave (EventArgs.Empty);
1224                 }
1225
1226                 internal void FireValidating (CancelEventArgs ce)
1227                 {
1228                         OnValidating (ce);
1229                 }
1230
1231                 internal void FireValidated ()
1232                 {
1233                         OnValidated (EventArgs.Empty);
1234                 }
1235
1236                 internal virtual bool ProcessControlMnemonic(char charCode) {
1237                         return ProcessMnemonic(charCode);
1238                 }
1239
1240                 private static Control FindFlatForward(Control container, Control start) {
1241                         Control found;
1242                         int     index;
1243                         int     end;
1244
1245                         found = null;
1246                         end = container.child_controls.Count;
1247
1248                         if (start != null) {
1249                                 index = start.tab_index;
1250                         } else {
1251                                 index = -1;
1252                         }
1253
1254                         for (int i = 0, pos = -1; i < end; i++) {
1255                                 if (start == container.child_controls[i]) {
1256                                         pos = i;
1257                                         continue;
1258                                 }
1259
1260                                 if (found == null) {
1261                                         if (container.child_controls[i].tab_index > index || (pos > -1 && pos < i && container.child_controls[i].tab_index == index)) {
1262                                                 found = container.child_controls[i];
1263                                         }
1264                                 } else if (found.tab_index > container.child_controls[i].tab_index) {
1265                                         if (container.child_controls[i].tab_index > index) {
1266                                                 found = container.child_controls[i];
1267                                         }
1268                                 }
1269                         }
1270                         return found;
1271                 }
1272
1273                 private static Control FindControlForward(Control container, Control start) {
1274                         Control found;
1275
1276                         found = null;
1277
1278                         if (start == null) {
1279                                 return FindFlatForward(container, start);
1280                         }
1281
1282                         if (start.child_controls != null && start.child_controls.Count > 0 && 
1283                                 (start == container || !((start is IContainerControl) &&  start.GetStyle(ControlStyles.ContainerControl)))) {
1284                                 return FindControlForward(start, null);
1285                         }
1286                         else {
1287                                 while (start != container) {
1288                                         found = FindFlatForward(start.parent, start);
1289                                         if (found != null) {
1290                                                 return found;
1291                                         }
1292                                         start = start.parent;
1293                                 }
1294                         }
1295                         return null;
1296                 }
1297
1298                 private static Control FindFlatBackward(Control container, Control start) {
1299                         Control found;
1300                         int     index;
1301                         int     end;
1302
1303                         found = null;
1304                         end = container.child_controls.Count;
1305
1306                         if (start != null) {
1307                                 index = start.tab_index;
1308                         } else {
1309                                 // FIXME: Possible speed-up: Keep the highest taborder index in the container
1310                                 index = -1;
1311                                 for (int i = 0; i < end; i++) {
1312                                         if (container.child_controls[i].tab_index > index) {
1313                                                 index = container.child_controls[i].tab_index;
1314                                         }
1315                                 }
1316                                 index++;
1317                         }
1318
1319                         bool hit = false;
1320                                         
1321                         for (int i = end - 1; i >= 0; i--) {
1322                                 if (start == container.child_controls[i]) {
1323                                         hit = true;
1324                                         continue;
1325                                 }
1326
1327                                 if (found == null || found.tab_index < container.child_controls[i].tab_index) {
1328                                         if (container.child_controls[i].tab_index < index || (hit && container.child_controls[i].tab_index == index))
1329                                                 found = container.child_controls[i];
1330
1331                                 }
1332                         }
1333                         return found;
1334                 }
1335
1336                 private static Control FindControlBackward(Control container, Control start) {
1337
1338                         Control found = null;
1339
1340                         if (start == null) {
1341                                 found = FindFlatBackward(container, start);
1342                         }
1343                         else if (start != container) {
1344                                 if (start.parent != null) {
1345                                         found = FindFlatBackward(start.parent, start);
1346
1347                                         if (found == null) {
1348                                                 if (start.parent != container)
1349                                                         return start.parent;
1350                                                 return null;
1351                                         }
1352                                 }
1353                         }
1354                 
1355                         if (found == null || start.parent == null)
1356                                 found = start;
1357
1358                         while (found != null && (found == container || (!((found is IContainerControl) && found.GetStyle(ControlStyles.ContainerControl))) &&
1359                                 found.child_controls != null && found.child_controls.Count > 0)) {
1360 //                              while (ctl.child_controls != null && ctl.child_controls.Count > 0 && 
1361 //                                      (ctl == this || (!((ctl is IContainerControl) && ctl.GetStyle(ControlStyles.ContainerControl))))) {
1362                                 found = FindFlatBackward(found, null);
1363                         }
1364
1365                         return found;
1366
1367 /*
1368                         Control found;
1369
1370                         found = null;
1371
1372                         if (start != null) {
1373                                 found = FindFlatBackward(start.parent, start);
1374                                 if (found == null) {
1375                                         if (start.parent != container) {
1376                                                 return start.parent;
1377                                         }
1378                                 }
1379                         }
1380                         if (found == null) {
1381                                 found = FindFlatBackward(container, start);
1382                         }
1383
1384                         if (container != start) {
1385                                 while ((found != null) && (!found.Contains(start)) && found.child_controls != null && found.child_controls.Count > 0 && !(found is IContainerControl)) {// || found.GetStyle(ControlStyles.ContainerControl))) {
1386                                         found = FindControlBackward(found, null);
1387                                          if (found != null) {
1388                                                 return found;
1389                                         }
1390                                 }
1391                         }
1392                         return found;
1393 */                      
1394                 }
1395
1396                 internal virtual void HandleClick(int clicks, MouseEventArgs me) {
1397                         if (GetStyle(ControlStyles.StandardClick)) {
1398                                 if ((clicks > 1) && GetStyle(ControlStyles.StandardDoubleClick)) {
1399 #if !NET_2_0
1400                                         OnDoubleClick(EventArgs.Empty);
1401                                 } else {
1402                                         OnClick(EventArgs.Empty);
1403 #else
1404                                         OnDoubleClick(me);
1405                                 } else {
1406                                         OnClick(me);
1407 #endif
1408                                 }
1409                         }
1410                 }
1411                 
1412                 internal void CaptureWithConfine (Control ConfineWindow)
1413                 {
1414                         if (this.IsHandleCreated && !is_captured) {
1415                                 is_captured = true;
1416                                 XplatUI.GrabWindow (this.window.Handle, ConfineWindow.Handle);
1417                         }
1418                 }
1419
1420                 private void CheckDataBindings ()
1421                 {
1422                         if (data_bindings == null)
1423                                 return;
1424
1425                         BindingContext binding_context = BindingContext;
1426                         foreach (Binding binding in data_bindings) {
1427                                 binding.Check (binding_context);
1428                         }
1429                 }
1430
1431                 private void ChangeParent(Control new_parent) {
1432                         bool            pre_enabled;
1433                         bool            pre_visible;
1434                         Font            pre_font;
1435                         Color           pre_fore_color;
1436                         Color           pre_back_color;
1437                         RightToLeft     pre_rtl;
1438
1439                         // These properties are inherited from our parent
1440                         // Get them pre parent-change and then send events
1441                         // if they are changed after we have our new parent
1442                         pre_enabled = Enabled;
1443                         pre_visible = Visible;
1444                         pre_font = Font;
1445                         pre_fore_color = ForeColor;
1446                         pre_back_color = BackColor;
1447                         pre_rtl = RightToLeft;
1448                         // MS doesn't seem to send a CursorChangedEvent
1449
1450                         parent = new_parent;
1451
1452                         if (IsHandleCreated)
1453                                 XplatUI.SetParent(Handle,
1454                                                   (new_parent == null || !new_parent.IsHandleCreated) ? IntPtr.Zero : new_parent.Handle);
1455
1456                         OnParentChanged(EventArgs.Empty);
1457
1458                         if (pre_enabled != Enabled) {
1459                                 OnEnabledChanged(EventArgs.Empty);
1460                         }
1461
1462                         if (pre_visible != Visible) {
1463                                 OnVisibleChanged(EventArgs.Empty);
1464                         }
1465
1466                         if (pre_font != Font) {
1467                                 OnFontChanged(EventArgs.Empty);
1468                         }
1469
1470                         if (pre_fore_color != ForeColor) {
1471                                 OnForeColorChanged(EventArgs.Empty);
1472                         }
1473
1474                         if (pre_back_color != BackColor) {
1475                                 OnBackColorChanged(EventArgs.Empty);
1476                         }
1477
1478                         if (pre_rtl != RightToLeft) {
1479                                 // MS sneaks a OnCreateControl and OnHandleCreated in here, I guess
1480                                 // because when RTL changes they have to recreate the win32 control
1481                                 // We don't really need that (until someone runs into compatibility issues)
1482                                 OnRightToLeftChanged(EventArgs.Empty);
1483                         }
1484
1485                         if ((new_parent != null) && new_parent.Created && !Created) {
1486                                 CreateControl();
1487                         }
1488
1489                         if ((binding_context == null) && Created) {
1490                                 OnBindingContextChanged(EventArgs.Empty);
1491                         }
1492                 }
1493
1494                 private void UpdateDistances() {
1495                         if (parent != null) {
1496                                 dist_left = bounds.X;
1497                                 dist_top = bounds.Y;
1498                                 dist_right = parent.ClientSize.Width - bounds.X - bounds.Width;
1499                                 dist_bottom = parent.ClientSize.Height - bounds.Y - bounds.Height;
1500                         }
1501                 }
1502                 #endregion      // Private & Internal Methods
1503
1504                 #region Public Static Properties
1505                 public static Color DefaultBackColor {
1506                         get {
1507                                 return ThemeEngine.Current.DefaultControlBackColor;
1508                         }
1509                 }
1510
1511                 public static Font DefaultFont {
1512                         get {
1513                                 return ThemeEngine.Current.DefaultFont;
1514                         }
1515                 }
1516
1517                 public static Color DefaultForeColor {
1518                         get {
1519                                 return ThemeEngine.Current.DefaultControlForeColor;
1520                         }
1521                 }
1522
1523                 public static Keys ModifierKeys {
1524                         get {
1525                                 return XplatUI.State.ModifierKeys;
1526                         }
1527                 }
1528
1529                 public static MouseButtons MouseButtons {
1530                         get {
1531                                 return XplatUI.State.MouseButtons;
1532                         }
1533                 }
1534
1535                 public static Point MousePosition {
1536                         get {
1537                                 return Cursor.Position;
1538                         }
1539                 }
1540                 
1541 #if NET_2_0
1542                 [EditorBrowsable (EditorBrowsableState.Advanced)]
1543                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
1544                 [Browsable (false)]
1545                 [MonoTODO]
1546                 public static bool CheckForIllegalCrossThreadCalls 
1547                 {
1548                         get {
1549                                 return verify_thread_handle;
1550                         }
1551
1552                         set {
1553                                 verify_thread_handle = value;
1554                         }
1555                 }
1556 #endif
1557                 #endregion      // Public Static Properties
1558
1559                 #region Public Instance Properties
1560                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1561                 [Browsable(false)]
1562                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1563                 public AccessibleObject AccessibilityObject {
1564                         get {
1565                                 if (accessibility_object==null) {
1566                                         accessibility_object=CreateAccessibilityInstance();
1567                                 }
1568                                 return accessibility_object;
1569                         }
1570                 }
1571
1572                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1573                 [Browsable(false)]
1574                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1575                 public string AccessibleDefaultActionDescription {
1576                         get {
1577                                 return AccessibilityObject.default_action;
1578                         }
1579
1580                         set {
1581                                 AccessibilityObject.default_action=value;
1582                         }
1583                 }
1584
1585                 [Localizable(true)]
1586                 [DefaultValue(null)]
1587                 [MWFCategory("Accessibility")]
1588                 public string AccessibleDescription {
1589                         get {
1590                                 return AccessibilityObject.description;
1591                         }
1592
1593                         set {
1594                                 AccessibilityObject.description=value;
1595                         }
1596                 }
1597
1598                 [Localizable(true)]
1599                 [DefaultValue(null)]
1600                 [MWFCategory("Accessibility")]
1601                 public string AccessibleName {
1602                         get {
1603                                 return AccessibilityObject.Name;
1604                         }
1605
1606                         set {
1607                                 AccessibilityObject.Name=value;
1608                         }
1609                 }
1610
1611                 [DefaultValue(AccessibleRole.Default)]
1612                 [MWFDescription("Role of the control"), MWFCategory("Accessibility")]
1613                 public AccessibleRole AccessibleRole {
1614                         get {
1615                                 return AccessibilityObject.role;
1616                         }
1617
1618                         set {
1619                                 AccessibilityObject.role=value;
1620                         }
1621                 }
1622
1623                 [DefaultValue(false)]
1624                 [MWFCategory("Behavior")]
1625                 public virtual bool AllowDrop {
1626                         get {
1627                                 return allow_drop;
1628                         }
1629
1630                         set {
1631                                 if (allow_drop == value)
1632                                         return;
1633                                 allow_drop = value;
1634                                 if (IsHandleCreated) {
1635                                         UpdateStyles();
1636                                         XplatUI.SetAllowDrop (Handle, value);
1637                                 }
1638                         }
1639                 }
1640
1641                 [Localizable(true)]
1642                 [RefreshProperties(RefreshProperties.Repaint)]
1643                 [DefaultValue(AnchorStyles.Top | AnchorStyles.Left)]
1644                 [MWFCategory("Layout")]
1645                 public virtual AnchorStyles Anchor {
1646                         get {
1647                                 return anchor_style;
1648                         }
1649
1650                         set {
1651                                 anchor_style=value;
1652
1653                                 if (parent != null) {
1654                                         parent.PerformLayout(this, "Parent");
1655                                 }
1656                         }
1657                 }
1658
1659 #if NET_2_0
1660                 // XXX: Implement me!
1661                 bool auto_size;
1662                 
1663                 [RefreshProperties (RefreshProperties.All)]
1664                 [Localizable (true)]
1665                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
1666                 [Browsable (false)]
1667                 [EditorBrowsable (EditorBrowsableState.Never)]
1668                 [DefaultValue (false)]
1669                 public virtual bool AutoSize {
1670                         get {
1671                                 //Console.Error.WriteLine("Unimplemented: Control::get_AutoSize()");
1672                                 return auto_size;
1673                         }
1674                         set {
1675                                 Console.Error.WriteLine("Unimplemented: Control::set_AutoSize(bool)");
1676                                 auto_size = value;
1677                         }
1678                 }
1679                 
1680                 [AmbientValue (typeof(Size), "0, 0")]
1681                 public virtual Size MaximumSize {
1682                         get {
1683                                 return maximum_size;
1684                         }
1685                         set {
1686                                 maximum_size = value;
1687                         }
1688                 }
1689
1690                 public virtual Size MinimumSize {
1691                         get {
1692                                 return minimum_size;
1693                         }
1694                         set {
1695                                 minimum_size = value;
1696                         }
1697                 }
1698 #endif // NET_2_0
1699
1700                 [DispId(-501)]
1701                 [MWFCategory("Appearance")]
1702                 public virtual Color BackColor {
1703                         get {
1704                                 if (background_color.IsEmpty) {
1705                                         if (parent!=null) {
1706                                                 Color pcolor = parent.BackColor;
1707                                                 if (pcolor.A == 0xff || GetStyle(ControlStyles.SupportsTransparentBackColor))
1708                                                         return pcolor;
1709                                         }
1710                                         return DefaultBackColor;
1711                                 }
1712                                 return background_color;
1713                         }
1714
1715                         set {
1716                                 if (!value.IsEmpty && (value.A != 0xff) && !GetStyle(ControlStyles.SupportsTransparentBackColor)) {
1717                                         throw new ArgumentException("Transparent background colors are not supported on this control");
1718                                 }
1719
1720                                 if (background_color != value) {
1721                                         background_color=value;
1722                                         SetChildColor(this);
1723                                         OnBackColorChanged(EventArgs.Empty);
1724                                         Invalidate();
1725                                 }
1726                         }
1727                 }
1728
1729                 [Localizable(true)]
1730                 [DefaultValue(null)]
1731                 [MWFCategory("Appearance")]
1732                 public virtual Image BackgroundImage {
1733                         get {
1734                                 return background_image;
1735                         }
1736
1737                         set {
1738                                 if (background_image!=value) {
1739                                         background_image=value;
1740                                         OnBackgroundImageChanged(EventArgs.Empty);
1741                                         Invalidate ();
1742                                 }
1743                         }
1744                 }
1745
1746 #if NET_2_0
1747                 [DefaultValue (1)]
1748                 [Localizable (true)]
1749                 public virtual ImageLayout BackgroundImageLayout {
1750                         get {
1751                                 return backgroundimage_layout;
1752                         }
1753                         set {
1754                                 if (Array.IndexOf (Enum.GetValues (typeof (ImageLayout)), value) == -1)
1755                                         throw new InvalidEnumArgumentException ("value", (int) value, typeof(ImageLayout));
1756
1757                                 if (value != backgroundimage_layout) {
1758                                         backgroundimage_layout = value;
1759                                         Invalidate ();
1760                                 }
1761                                 
1762                         }
1763                 } 
1764 #endif
1765                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1766                 [Browsable(false)]
1767                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1768                 public virtual BindingContext BindingContext {
1769                         get {
1770                                 if (binding_context != null)
1771                                         return binding_context;
1772                                 if (Parent == null)
1773                                         return null;
1774                                 binding_context = Parent.BindingContext;
1775                                 return binding_context;
1776                         }
1777                         set {
1778                                 if (binding_context != value) {
1779                                         binding_context = value;
1780                                         OnBindingContextChanged(EventArgs.Empty);
1781                                 }
1782                         }
1783                 }
1784
1785                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1786                 [Browsable(false)]
1787                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1788                 public int Bottom {
1789                         get {
1790                                 return bounds.Y+bounds.Height;
1791                         }
1792                 }
1793
1794                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1795                 [Browsable(false)]
1796                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1797                 public Rectangle Bounds {
1798                         get {
1799                                 return this.bounds;
1800                         }
1801
1802                         set {
1803                                 SetBounds(value.Left, value.Top, value.Width, value.Height, BoundsSpecified.All);
1804                         }
1805                 }
1806
1807                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1808                 [Browsable(false)]
1809                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1810                 public bool CanFocus {
1811                         get {
1812                                 if (IsHandleCreated && Visible && Enabled) {
1813                                         return true;
1814                                 }
1815                                 return false;
1816                         }
1817                 }
1818
1819                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1820                 [Browsable(false)]
1821                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1822                 public bool CanSelect {
1823                         get {
1824                                 Control parent;
1825
1826                                 if (!GetStyle(ControlStyles.Selectable)) {
1827                                         return false;
1828                                 }
1829
1830                                 parent = this;
1831                                 while (parent != null) {
1832                                         if (!parent.is_visible || !parent.is_enabled) {
1833                                                 return false;
1834                                         }
1835
1836                                         parent = parent.parent;
1837                                 }
1838                                 return true;
1839                         }
1840                 }
1841
1842                 internal virtual bool InternalCapture {
1843                         get {
1844                                 return Capture;
1845                         }
1846
1847                         set {
1848                                 Capture = value;
1849                         }
1850                 }
1851
1852                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1853                 [Browsable(false)]
1854                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1855                 public bool Capture {
1856                         get {
1857                                 return this.is_captured;
1858                         }
1859
1860                         set {
1861                                 if (this.IsHandleCreated && value != is_captured) {
1862                                         if (value) {
1863                                                 is_captured = true;
1864                                                 XplatUI.GrabWindow(this.window.Handle, IntPtr.Zero);
1865                                         } else {
1866                                                 XplatUI.UngrabWindow(this.window.Handle);
1867                                                 is_captured = false;
1868                                         }
1869                                 }
1870                         }
1871                 }
1872
1873                 [DefaultValue(true)]
1874                 [MWFCategory("Focus")]
1875                 public bool CausesValidation {
1876                         get {
1877                                 return this.causes_validation;
1878                         }
1879
1880                         set {
1881                                 if (this.causes_validation != value) {
1882                                         causes_validation = value;
1883                                         OnCausesValidationChanged(EventArgs.Empty);
1884                                 }
1885                         }
1886                 }
1887
1888                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1889                 [Browsable(false)]
1890                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1891                 public Rectangle ClientRectangle {
1892                         get {
1893                                 client_rect.Width = client_size.Width;
1894                                 client_rect.Height = client_size.Height;
1895                                 return client_rect;
1896                         }
1897                 }
1898
1899                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1900                 [Browsable(false)]
1901                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1902                 public Size ClientSize {
1903                         get {
1904 #if notneeded
1905                                 if ((this is Form) && (((Form)this).form_parent_window != null)) {
1906                                         return ((Form)this).form_parent_window.ClientSize;
1907                                 }
1908 #endif
1909
1910                                 return client_size;
1911                         }
1912
1913                         set {
1914                                 this.SetClientSizeCore(value.Width, value.Height);
1915                         }
1916                 }
1917
1918                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1919                 [Browsable(false)]
1920                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1921                 [DescriptionAttribute("ControlCompanyNameDescr")]
1922                 public String CompanyName {
1923                         get {
1924                                 return "Mono Project, Novell, Inc.";
1925                         }
1926                 }
1927
1928                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1929                 [Browsable(false)]
1930                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1931                 public bool ContainsFocus {
1932                         get {
1933                                 IntPtr focused_window;
1934
1935                                 focused_window = XplatUI.GetFocus();
1936                                 if (IsHandleCreated) {
1937                                         if (focused_window == Handle) {
1938                                                 return true;
1939                                         }
1940
1941                                         for (int i=0; i < child_controls.Count; i++) {
1942                                                 if (child_controls[i].ContainsFocus) {
1943                                                         return true;
1944                                                 }
1945                                         }
1946                                 }
1947                                 return false;
1948                         }
1949                 }
1950 #if NET_2_0
1951                 [Browsable (false)]
1952 #endif
1953                 [DefaultValue(null)]
1954                 [MWFCategory("Behavior")]
1955                 public virtual ContextMenu ContextMenu {
1956                         get {
1957                                 return GetContextMenuInternal ();
1958                         }
1959
1960                         set {
1961                                 if (context_menu != value) {
1962                                         context_menu = value;
1963                                         OnContextMenuChanged(EventArgs.Empty);
1964                                 }
1965                         }
1966                 }
1967
1968                 internal virtual ContextMenu GetContextMenuInternal ()
1969                 {
1970                         return context_menu;
1971                 }
1972
1973                 [Browsable(false)]
1974                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
1975                 public ControlCollection Controls {
1976                         get {
1977                                 return this.child_controls;
1978                         }
1979                 }
1980
1981                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1982                 [Browsable(false)]
1983                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1984                 public bool Created {
1985                         get {
1986                                 return (!is_disposed && is_created);
1987                         }
1988                 }
1989
1990                 [AmbientValue(null)]
1991                 [MWFCategory("Appearance")]
1992                 public virtual Cursor Cursor {
1993                         get {
1994                                 if (cursor != null) {
1995                                         return cursor;
1996                                 }
1997
1998                                 if (parent != null) {
1999                                         return parent.Cursor;
2000                                 }
2001
2002                                 return Cursors.Default;
2003                         }
2004
2005                         set {
2006                                 if (cursor != value) {
2007                                         Point pt;
2008
2009                                         cursor = value;
2010                                         
2011                                         if (IsHandleCreated) {
2012                                                 pt = Cursor.Position;
2013
2014                                                 if (bounds.Contains(pt) || Capture) {
2015                                                         if (GetChildAtPoint(pt) == null) {
2016                                                                 if (cursor != null) {
2017                                                                         XplatUI.SetCursor(window.Handle, cursor.handle);
2018                                                                 } else {
2019                                                                         if (parent != null) {
2020                                                                                 XplatUI.SetCursor(window.Handle, parent.Cursor.handle);
2021                                                                         } else {
2022                                                                                 XplatUI.SetCursor(window.Handle, Cursors.Default.handle);
2023                                                                         }
2024                                                                 }
2025                                                         }
2026                                                 }
2027                                         }
2028
2029                                         OnCursorChanged(EventArgs.Empty);
2030                                 }
2031                         }
2032                 }
2033
2034
2035                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
2036                 [ParenthesizePropertyName(true)]
2037                 [RefreshProperties(RefreshProperties.All)]
2038                 [MWFCategory("Data")]
2039                 public ControlBindingsCollection DataBindings {
2040                         get {
2041                                 if (data_bindings == null)
2042                                         data_bindings = new ControlBindingsCollection (this);
2043                                 return data_bindings;
2044                         }
2045                 }
2046
2047                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2048                 [Browsable(false)]
2049                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2050                 public virtual Rectangle DisplayRectangle {
2051                         get {
2052                                 return ClientRectangle;
2053                         }
2054                 }
2055
2056                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2057                 [Browsable(false)]
2058                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2059                 public bool Disposing {
2060                         get {
2061                                 return is_disposed;
2062                         }
2063                 }
2064
2065                 [Localizable(true)]
2066                 [RefreshProperties(RefreshProperties.Repaint)]
2067                 [DefaultValue(DockStyle.None)]
2068                 [MWFCategory("Layout")]
2069                 public virtual DockStyle Dock {
2070                         get {
2071                                 return dock_style;
2072                         }
2073
2074                         set {
2075                                 if (dock_style == value) {
2076                                         return;
2077                                 }
2078
2079                                 if (!Enum.IsDefined (typeof (DockStyle), value)) {
2080                                         throw new InvalidEnumArgumentException ("value", (int) value,
2081                                                 typeof (DockStyle));
2082                                 }
2083
2084                                 dock_style = value;
2085
2086                                 if (dock_style == DockStyle.None) {
2087                                         if (explicit_bounds == Rectangle.Empty)
2088                                                 Bounds = new Rectangle (new Point (0, 0), DefaultSize);
2089                                         else
2090                                                 Bounds = explicit_bounds;
2091                                 }
2092
2093                                 if (parent != null) {
2094                                         parent.PerformLayout(this, "Parent");
2095                                 }
2096
2097                                 OnDockChanged(EventArgs.Empty);
2098                         }
2099                 }
2100
2101 #if NET_2_0
2102                 protected virtual bool DoubleBuffered {
2103                         get {
2104                                 return (control_style & ControlStyles.DoubleBuffer) != 0;
2105                         }
2106
2107                         set {
2108                                 SetStyle (ControlStyles.DoubleBuffer, value);
2109                         }
2110                 }
2111 #endif
2112                 
2113                 [DispId(-514)]
2114                 [Localizable(true)]
2115                 [MWFCategory("Behavior")]
2116                 public bool Enabled {
2117                         get {
2118                                 if (!is_enabled) {
2119                                         return false;
2120                                 }
2121
2122                                 if (parent != null) {
2123                                         return parent.Enabled;
2124                                 }
2125
2126                                 return true;
2127                         }
2128
2129                         set {
2130
2131                                 bool old_value = is_enabled;
2132
2133                                 is_enabled = value;
2134                                 if (old_value != value && !value && this.has_focus)
2135                                         SelectNextControl(this, true, true, true, true);
2136
2137                                 OnEnabledChanged (EventArgs.Empty);
2138                         }
2139                 }
2140
2141                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2142                 [Browsable(false)]
2143                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2144                 public virtual bool Focused {
2145                         get {
2146                                 return this.has_focus;
2147                         }
2148                 }
2149
2150                 [DispId(-512)]
2151                 [AmbientValue(null)]
2152                 [Localizable(true)]
2153                 [MWFCategory("Appearance")]
2154                 public virtual Font Font {
2155                         get {
2156                                 if (font != null) {
2157                                         return font;
2158                                 }
2159
2160                                 if (Parent != null && Parent.Font != null) {
2161                                         return Parent.Font;
2162                                 }
2163
2164                                 return DefaultFont;
2165                         }
2166
2167                         [param:MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(Font))]
2168                         set {
2169                                 if (font != null && font.Equals (value)) {
2170                                         return;
2171                                 }
2172
2173                                 font = value;
2174                                 Invalidate();
2175                                 OnFontChanged (EventArgs.Empty);
2176                         }
2177                 }
2178
2179                 [DispId(-513)]
2180                 [MWFCategory("Appearance")]
2181                 public virtual Color ForeColor {
2182                         get {
2183                                 if (foreground_color.IsEmpty) {
2184                                         if (parent!=null) {
2185                                                 return parent.ForeColor;
2186                                         }
2187                                         return DefaultForeColor;
2188                                 }
2189                                 return foreground_color;
2190                         }
2191
2192                         set {
2193                                 if (foreground_color != value) {
2194                                         foreground_color=value;
2195                                         Invalidate();
2196                                         OnForeColorChanged(EventArgs.Empty);
2197                                 }
2198                         }
2199                 }
2200
2201                 [DispId(-515)]
2202                 [Browsable(false)]
2203                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2204                 public IntPtr Handle {                                                  // IWin32Window
2205                         get {
2206 #if NET_2_0
2207                                 if (verify_thread_handle) {
2208                                         if (this.InvokeRequired) {
2209                                                 throw new InvalidOperationException("Cross-thread access of handle detected. Handle access only valid on thread that created the control");
2210                                         }
2211                                 }
2212 #endif
2213                                 if (!IsHandleCreated) {
2214                                         CreateHandle();
2215                                 }
2216                                 return window.Handle;
2217                         }
2218                 }
2219
2220                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2221                 [Browsable(false)]
2222                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2223                 public bool HasChildren {
2224                         get {
2225                                 if (this.child_controls.Count>0) {
2226                                         return true;
2227                                 }
2228                                 return false;
2229                         }
2230                 }
2231
2232                 [EditorBrowsable(EditorBrowsableState.Always)]
2233                 [Browsable(false)]
2234                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2235                 public int Height {
2236                         get {
2237                                 return this.bounds.Height;
2238                         }
2239
2240                         set {
2241                                 SetBounds(bounds.X, bounds.Y, bounds.Width, value, BoundsSpecified.Height);
2242                         }
2243                 }
2244
2245                 [AmbientValue(ImeMode.Inherit)]
2246                 [Localizable(true)]
2247                 [MWFCategory("Behavior")]
2248                 public ImeMode ImeMode {
2249                         get {
2250                                 if (ime_mode == ImeMode.Inherit) {
2251                                         if (parent != null)
2252                                                 return parent.ImeMode;
2253                                         else
2254                                                 return ImeMode.NoControl; // default value
2255                                 }
2256                                 return ime_mode;
2257                         }
2258
2259                         set {
2260                                 if (ime_mode != value) {
2261                                         ime_mode = value;
2262
2263                                         OnImeModeChanged(EventArgs.Empty);
2264                                 }
2265                         }
2266                 }
2267
2268                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2269                 [Browsable(false)]
2270                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2271                 public bool InvokeRequired {                                            // ISynchronizeInvoke
2272                         get {
2273                                 if (creator_thread != null && creator_thread!=Thread.CurrentThread) {
2274                                         return true;
2275                                 }
2276                                 return false;
2277                         }
2278                 }
2279
2280                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2281                 [Browsable(false)]
2282                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2283                 public bool IsAccessible {
2284                         get {
2285                                 return is_accessible;
2286                         }
2287
2288                         set {
2289                                 is_accessible = value;
2290                         }
2291                 }
2292
2293                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2294                 [Browsable(false)]
2295                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2296                 public bool IsDisposed {
2297                         get {
2298                                 return this.is_disposed;
2299                         }
2300                 }
2301
2302                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2303                 [Browsable(false)]
2304                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2305                 public bool IsHandleCreated {
2306                         get {
2307                                 if ((window != null) && (window.Handle != IntPtr.Zero)) {
2308                                         Hwnd hwnd = Hwnd.ObjectFromHandle (window.Handle);
2309                                         if (hwnd != null && !hwnd.zombie)
2310                                                 return true;
2311                                 }
2312
2313                                 return false;
2314                         }
2315                 }
2316
2317 #if NET_2_0
2318                 [Browsable (false)]
2319                 [EditorBrowsable (EditorBrowsableState.Advanced)]
2320                 public virtual Layout.LayoutEngine LayoutEngine {
2321                         get { return new Layout.DefaultLayout (); }
2322                 } 
2323 #endif
2324
2325                 [EditorBrowsable(EditorBrowsableState.Always)]
2326                 [Browsable(false)]
2327                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2328                 public int Left {
2329                         get {
2330                                 return this.bounds.X;
2331                         }
2332
2333                         set {
2334                                 SetBounds(value, bounds.Y, bounds.Width, bounds.Height, BoundsSpecified.X);
2335                         }
2336                 }
2337
2338                 [Localizable(true)]
2339                 [MWFCategory("Layout")]
2340                 public Point Location {
2341                         get {
2342                                 return new Point(bounds.X, bounds.Y);
2343                         }
2344
2345                         set {
2346                                 SetBounds(value.X, value.Y, bounds.Width, bounds.Height, BoundsSpecified.Location);
2347                         }
2348                 }
2349
2350 #if NET_2_0
2351                 [Localizable (true)]
2352                 public Padding Margin {
2353                         get { return this.margin; }
2354                         set { this.margin = value; }
2355                 }
2356 #endif
2357
2358                 [Browsable(false)]
2359                 public string Name {
2360                         get {
2361                                 return name;
2362                         }
2363
2364                         set {
2365                                 name = value;
2366                         }
2367                 }
2368
2369 #if NET_2_0
2370                 [Localizable(true)]
2371                 public Padding Padding {
2372                         get {
2373                                 return padding;
2374                         }
2375
2376                         set {
2377                                 padding = value;
2378                                 OnPaddingChanged (EventArgs.Empty);
2379                         }
2380                 }
2381 #endif
2382
2383                 [Browsable(false)]
2384                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2385                 public Control Parent {
2386                         get {
2387                                 return this.parent;
2388                         }
2389
2390                         set {
2391                                 if (value == this) {
2392                                         throw new ArgumentException("A circular control reference has been made. A control cannot be owned or parented to itself.");
2393                                 }
2394
2395                                 if (parent!=value) {
2396                                         if (value==null) {
2397                                                 parent.Controls.Remove(this);
2398                                                 parent = null;
2399                                                 return;
2400                                         }
2401
2402                                         value.Controls.Add(this);
2403                                 }
2404                         }
2405                 }
2406
2407                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2408                 [Browsable(false)]
2409                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2410                 public string ProductName {
2411                         get {
2412                                 Type t = typeof (AssemblyProductAttribute);
2413                                 Assembly assembly = GetType().Module.Assembly;
2414                                 object [] attrs = assembly.GetCustomAttributes (t, false);
2415                                 AssemblyProductAttribute a = null;
2416                                 // On MS we get a NullRefException if product attribute is not
2417                                 // set. 
2418                                 if (attrs != null && attrs.Length > 0)
2419                                         a = (AssemblyProductAttribute) attrs [0];
2420                                 return a.Product;
2421                         }
2422                 }
2423
2424                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2425                 [Browsable(false)]
2426                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2427                 public string ProductVersion {
2428                         get {
2429                                 Type t = typeof (AssemblyVersionAttribute);
2430                                 Assembly assembly = GetType().Module.Assembly;
2431                                 object [] attrs = assembly.GetCustomAttributes (t, false);
2432                                 if (attrs == null || attrs.Length < 1)
2433                                         return "1.0.0.0";
2434                                 return ((AssemblyVersionAttribute)attrs [0]).Version;
2435                         }
2436                 }
2437
2438                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2439                 [Browsable(false)]
2440                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2441                 public bool RecreatingHandle {
2442                         get {
2443                                 return is_recreating;
2444                         }
2445                 }
2446
2447                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2448                 [Browsable(false)]
2449                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2450                 public Region Region {
2451                         get {
2452                                 return clip_region;
2453                         }
2454
2455                         set {
2456                                 if (value != null && IsHandleCreated) {
2457                                         XplatUI.SetClipRegion(Handle, value);
2458                                 }
2459                                 clip_region = value;
2460                         }
2461                 }
2462
2463                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2464                 [Browsable(false)]
2465                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2466                 public int Right {
2467                         get {
2468                                 return this.bounds.X+this.bounds.Width;
2469                         }
2470                 }
2471
2472                 [AmbientValue(RightToLeft.Inherit)]
2473                 [Localizable(true)]
2474                 [MWFCategory("Appearance")]
2475                 public virtual RightToLeft RightToLeft {
2476                         get {
2477                                 if (right_to_left == RightToLeft.Inherit) {
2478                                         if (parent != null)
2479                                                 return parent.RightToLeft;
2480                                         else
2481                                                 return RightToLeft.No; // default value
2482                                 }
2483                                 return right_to_left;
2484                         }
2485
2486                         set {
2487                                 if (value != right_to_left) {
2488                                         right_to_left = value;
2489                                         OnRightToLeftChanged(EventArgs.Empty);
2490                                 }
2491                         }
2492                 }
2493
2494                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2495                 public override ISite Site {
2496                         get {
2497                                 return base.Site;
2498                         }
2499
2500                         set {
2501                                 base.Site = value;
2502
2503                                 if (value != null) {
2504                                         AmbientProperties ap = (AmbientProperties) value.GetService (typeof (AmbientProperties));
2505                                         if (ap != null) {
2506                                                 BackColor = ap.BackColor;
2507                                                 ForeColor = ap.ForeColor;
2508                                                 Cursor = ap.Cursor;
2509                                                 Font = ap.Font;
2510                                         }
2511                                 }
2512                         }
2513                 }
2514
2515                 [Localizable(true)]
2516                 [MWFCategory("Layout")]
2517                 public Size Size {
2518                         get {
2519                                 return new Size(Width, Height);
2520                         }
2521
2522                         set {
2523                                 SetBounds(bounds.X, bounds.Y, value.Width, value.Height, BoundsSpecified.Size);
2524                         }
2525                 }
2526
2527                 [Localizable(true)]
2528                 [MergableProperty(false)]
2529                 [MWFCategory("Behavior")]
2530                 public int TabIndex {
2531                         get {
2532                                 if (tab_index != -1) {
2533                                         return tab_index;
2534                                 }
2535                                 return 0;
2536                         }
2537
2538                         set {
2539                                 if (tab_index != value) {
2540                                         tab_index = value;
2541                                         OnTabIndexChanged(EventArgs.Empty);
2542                                 }
2543                         }
2544                 }
2545
2546                 [DispId(-516)]
2547                 [DefaultValue(true)]
2548                 [MWFCategory("Behavior")]
2549                 public bool TabStop {
2550                         get {
2551                                 return tab_stop;
2552                         }
2553
2554                         set {
2555                                 if (tab_stop != value) {
2556                                         tab_stop = value;
2557                                         OnTabStopChanged(EventArgs.Empty);
2558                                 }
2559                         }
2560                 }
2561
2562                 [Localizable(false)]
2563                 [Bindable(true)]
2564                 [TypeConverter(typeof(StringConverter))]
2565                 [DefaultValue(null)]
2566                 [MWFCategory("Data")]
2567                 public object Tag {
2568                         get {
2569                                 return control_tag;
2570                         }
2571
2572                         set {
2573                                 control_tag = value;
2574                         }
2575                 }
2576
2577                 [DispId(-517)]
2578                 [Localizable(true)]
2579                 [BindableAttribute(true)]
2580                 [MWFCategory("Appearance")]
2581                 public virtual string Text {
2582                         get {
2583                                 // Our implementation ignores ControlStyles.CacheText - we always cache
2584                                 return this.text;
2585                         }
2586
2587                         set {
2588                                 if (value == null) {
2589                                         value = String.Empty;
2590                                 }
2591
2592                                 if (text!=value) {
2593                                         text=value;
2594                                         if (IsHandleCreated) {
2595                                                 /* we need to call .SetWindowStyle here instead of just .Text
2596                                                    because the presence/absence of Text (== "" or not) can cause
2597                                                    other window style things to appear/disappear */
2598                                                 XplatUI.SetWindowStyle(window.Handle, CreateParams);
2599                                                 XplatUI.Text(Handle, text);
2600                                         }
2601                                         OnTextChanged (EventArgs.Empty);
2602                                 }
2603                         }
2604                 }
2605
2606                 [EditorBrowsable(EditorBrowsableState.Always)]
2607                 [Browsable(false)]
2608                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2609                 public int Top {
2610                         get {
2611                                 return this.bounds.Y;
2612                         }
2613
2614                         set {
2615                                 SetBounds(bounds.X, value, bounds.Width, bounds.Height, BoundsSpecified.Y);
2616                         }
2617                 }
2618
2619                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2620                 [Browsable(false)]
2621                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2622                 public Control TopLevelControl {
2623                         get {
2624                                 Control p = this;
2625
2626                                 while (p.parent != null) {
2627                                         p = p.parent;
2628                                 }
2629
2630                                 return p is Form ? p : null;
2631                         }
2632                 }
2633
2634                 [Localizable(true)]
2635                 [MWFCategory("Behavior")]
2636                 public bool Visible {
2637                         get {
2638                                 if (!is_visible) {
2639                                         return false;
2640                                 } else if (parent != null) {
2641                                         return parent.Visible;
2642                                 }
2643
2644                                 return true;
2645                         }
2646
2647                         set {
2648                                 SetVisibleCore(value);
2649                         }
2650                 }
2651
2652                 [EditorBrowsable(EditorBrowsableState.Always)]
2653                 [Browsable(false)]
2654                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2655                 public int Width {
2656                         get {
2657                                 return this.bounds.Width;
2658                         }
2659
2660                         set {
2661                                 SetBounds(bounds.X, bounds.Y, value, bounds.Height, BoundsSpecified.Width);
2662                         }
2663                 }
2664
2665                 [EditorBrowsable(EditorBrowsableState.Never)]
2666                 [Browsable(false)]
2667                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2668                 public IWindowTarget WindowTarget {
2669                         get {
2670                                 return null;
2671                         }
2672
2673                         set {
2674                                 ;       // MS Internal
2675                         }
2676                 }
2677                 #endregion      // Public Instance Properties
2678
2679                 #region Protected Instance Properties
2680                 protected virtual CreateParams CreateParams {
2681                         get {
2682                                 CreateParams create_params = new CreateParams();
2683
2684                                 try {
2685                                         create_params.Caption = Text;
2686                                 }
2687                                 catch {
2688                                         create_params.Caption = text;
2689                                 }
2690
2691                                 try {
2692                                         create_params.X = Left;
2693                                 }
2694                                 catch {
2695                                         create_params.X = this.bounds.X;
2696                                 }
2697
2698                                 try {
2699                                         create_params.Y = Top;
2700                                 }
2701                                 catch {
2702                                         create_params.Y = this.bounds.Y;
2703                                 }
2704
2705                                 try {
2706                                         create_params.Width = Width;
2707                                 }
2708                                 catch {
2709                                         create_params.Width = this.bounds.Width;
2710                                 }
2711
2712                                 try {
2713                                         create_params.Height = Height;
2714                                 }
2715                                 catch {
2716                                         create_params.Height = this.bounds.Height;
2717                                 }
2718
2719
2720                                 create_params.ClassName = XplatUI.DefaultClassName;
2721                                 create_params.ClassStyle = 0;
2722                                 create_params.ExStyle = 0;
2723                                 create_params.Param = 0;
2724
2725                                 if (allow_drop) {
2726                                         create_params.ExStyle |= (int)WindowExStyles.WS_EX_ACCEPTFILES;
2727                                 }
2728
2729                                 if ((parent!=null) && (parent.IsHandleCreated)) {
2730                                         create_params.Parent = parent.Handle;
2731                                 }
2732
2733                                 create_params.Style = (int)WindowStyles.WS_CHILD | (int)WindowStyles.WS_CLIPCHILDREN | (int)WindowStyles.WS_CLIPSIBLINGS;
2734
2735                                 if (is_visible) {
2736                                         create_params.Style |= (int)WindowStyles.WS_VISIBLE;
2737                                 }
2738
2739                                 if (!is_enabled) {
2740                                         create_params.Style |= (int)WindowStyles.WS_DISABLED;
2741                                 }
2742
2743                                 switch (border_style) {
2744                                 case BorderStyle.FixedSingle:
2745                                         create_params.Style |= (int) WindowStyles.WS_BORDER;
2746                                         break;
2747                                 case BorderStyle.Fixed3D:
2748                                         create_params.ExStyle |= (int) WindowExStyles.WS_EX_CLIENTEDGE;
2749                                         break;
2750                                 }
2751
2752                                 return create_params;
2753                         }
2754                 }
2755
2756                 protected virtual ImeMode DefaultImeMode {
2757                         get {
2758                                 return ImeMode.Inherit;
2759                         }
2760                 }
2761
2762 #if NET_2_0
2763                 protected virtual Padding DefaultMargin {
2764                         get { return new Padding (3); }
2765                 }
2766 #endif
2767
2768                 protected virtual Size DefaultSize {
2769                         get {
2770                                 return new Size(0, 0);
2771                         }
2772                 }
2773
2774                 protected int FontHeight {
2775                         get {
2776                                 return Font.Height;
2777                         }
2778
2779                         set {
2780                                 ;; // Nothing to do
2781                         }
2782                 }
2783 #if NET_2_0
2784                 [Obsolete ()]
2785 #endif
2786                 protected bool RenderRightToLeft {
2787                         get {
2788                                 return (this.right_to_left == RightToLeft.Yes);
2789                         }
2790                 }
2791
2792                 protected bool ResizeRedraw {
2793                         get {
2794                                 return GetStyle(ControlStyles.ResizeRedraw);
2795                         }
2796
2797                         set {
2798                                 SetStyle(ControlStyles.ResizeRedraw, value);
2799                         }
2800                 }
2801
2802                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2803                 [Browsable(false)]
2804                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2805                 protected virtual bool ShowFocusCues {
2806                         get {
2807                                 return true;
2808                         }
2809                 }
2810
2811                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2812                 [Browsable(false)]
2813                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2814                 protected bool ShowKeyboardCues {
2815                         get {
2816                                 return true;
2817                         }
2818                 }
2819                 #endregion      // Protected Instance Properties
2820
2821                 #region Public Static Methods
2822                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2823                 public static Control FromChildHandle(IntPtr handle) {
2824                         return Control.ControlNativeWindow.ControlFromChildHandle (handle);
2825                 }
2826
2827                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2828                 public static Control FromHandle(IntPtr handle) {
2829                         return Control.ControlNativeWindow.ControlFromHandle(handle);
2830                 }
2831
2832                 public static bool IsMnemonic(char charCode, string text) {
2833                         int amp;
2834
2835                         amp = text.IndexOf('&');
2836
2837                         if (amp != -1) {
2838                                 if (amp + 1 < text.Length) {
2839                                         if (text[amp + 1] != '&') {
2840                                                 if (Char.ToUpper(charCode) == Char.ToUpper(text.ToCharArray(amp + 1, 1)[0])) {
2841                                                         return true;
2842                                                 }       
2843                                         }
2844                                 }
2845                         }
2846                         return false;
2847                 }
2848                 #endregion
2849
2850                 #region Protected Static Methods
2851                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2852                 protected static bool ReflectMessage(IntPtr hWnd, ref Message m) {
2853                         Control c;
2854
2855                         c = Control.FromHandle(hWnd);
2856
2857                         if (c != null) {
2858                                 c.WndProc(ref m);
2859                                 return true;
2860                         }
2861                         return false;
2862                 }
2863                 #endregion
2864
2865                 #region Public Instance Methods
2866                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2867                 public IAsyncResult BeginInvoke(Delegate method) {
2868                         object [] prms = null;
2869                         if (method is EventHandler)
2870                                 prms = new object [] { this, EventArgs.Empty };
2871                         return BeginInvokeInternal(method, prms, false);
2872                 }
2873
2874                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2875                 public IAsyncResult BeginInvoke (Delegate method, object[] args) {
2876                         return BeginInvokeInternal (method, args, false);
2877                 }
2878
2879                 public void BringToFront() {
2880                         if (parent != null) {
2881                                 parent.child_controls.SetChildIndex(this, 0);
2882                                 parent.Refresh();
2883                         } else {
2884                                 XplatUI.SetZOrder(Handle, IntPtr.Zero, false, false);
2885                         }
2886                 }
2887
2888                 public bool Contains(Control ctl) {
2889                         while (ctl != null) {
2890                                 ctl = ctl.parent;
2891                                 if (ctl == this) {
2892                                         return true;
2893                                 }
2894                         }
2895                         return false;
2896                 }
2897
2898                 public void CreateControl() {
2899                         if (is_disposed) {
2900                                 throw new ObjectDisposedException(GetType().FullName.ToString());
2901                         }
2902                         if (is_created) {
2903                                 return;
2904                         }
2905
2906                         if (!IsHandleCreated) {
2907                                 CreateHandle();
2908                         }
2909
2910                         if (!is_created) {
2911                                 is_created = true;
2912                         }
2913
2914                         Control [] controls = child_controls.GetAllControls ();
2915                         for (int i=0; i<controls.Length; i++) {
2916                                 controls [i].CreateControl ();
2917                         }
2918
2919                         UpdateChildrenZOrder();
2920
2921                         if (binding_context == null) {  // seem to be sent whenever it's null?
2922                                 OnBindingContextChanged(EventArgs.Empty);
2923                         }
2924
2925                         OnCreateControl();
2926                 }
2927
2928                 public Graphics CreateGraphics() {
2929                         if (!IsHandleCreated) {
2930                                 this.CreateHandle();
2931                         }
2932                         return Graphics.FromHwnd(this.window.Handle);
2933                 }
2934
2935                 public DragDropEffects DoDragDrop(object data, DragDropEffects allowedEffects) {
2936                         return XplatUI.StartDrag(this.window.Handle, data, allowedEffects);
2937                 }
2938
2939                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2940                 public object EndInvoke (IAsyncResult async_result) {
2941                         AsyncMethodResult result = (AsyncMethodResult) async_result;
2942                         return result.EndInvoke ();
2943                 }
2944
2945                 public Form FindForm() {
2946                         Control c;
2947
2948                         c = this;
2949                         while (c != null) {
2950                                 if (c is Form) {
2951                                         return (Form)c;
2952                                 }
2953                                 c = c.Parent;
2954                         }
2955                         return null;
2956                 }
2957 #if NET_2_0
2958                 [EditorBrowsable (EditorBrowsableState.Advanced)]
2959 #endif
2960                 public bool Focus() {
2961                         if (CanFocus && IsHandleCreated && !has_focus && !is_focusing) {
2962                                 is_focusing = true;
2963                                 Select(this);
2964                                 is_focusing = false;
2965                         }
2966                         return has_focus;
2967                 }
2968
2969                 public Control GetChildAtPoint(Point pt) {
2970                         // Microsoft's version of this function doesn't seem to work, so I can't check
2971                         // if we only consider children or also grandchildren, etc.
2972                         // I'm gonna say 'children only'
2973                         for (int i=0; i<child_controls.Count; i++) {
2974                                 if (child_controls[i].Bounds.Contains(pt)) {
2975                                         return child_controls[i];
2976                                 }
2977                         }
2978                         return null;
2979                 }
2980
2981                 public IContainerControl GetContainerControl() {
2982                         Control current = this;
2983
2984                         while (current!=null) {
2985                                 if ((current is IContainerControl) && ((current.control_style & ControlStyles.ContainerControl)!=0)) {
2986                                         return (IContainerControl)current;
2987                                 }
2988                                 current = current.parent;
2989                         }
2990                         return null;
2991                 }
2992
2993                 public Control GetNextControl(Control ctl, bool forward) {
2994
2995                         if (!this.Contains(ctl)) {
2996                                 ctl = this;
2997                         }
2998
2999                         if (forward) {
3000                                 ctl = FindControlForward(this, ctl);
3001                         }
3002                         else {
3003                                 ctl = FindControlBackward(this, ctl);
3004                         }
3005
3006                         if (ctl != this) {
3007                                 return ctl;
3008                         }
3009                         return null;
3010                 }
3011
3012 #if NET_2_0
3013                 [EditorBrowsable (EditorBrowsableState.Advanced)]
3014                 public virtual Size GetPreferredSize (Size proposedSize) {
3015                         return preferred_size;
3016                 }
3017 #endif
3018
3019                 public void Hide() {
3020                         this.Visible = false;
3021                 }
3022
3023                 public void Invalidate() {
3024                         Invalidate(ClientRectangle, false);
3025                 }
3026
3027                 public void Invalidate(bool invalidateChildren) {
3028                         Invalidate(ClientRectangle, invalidateChildren);
3029                 }
3030
3031                 public void Invalidate(System.Drawing.Rectangle rc) {
3032                         Invalidate(rc, false);
3033                 }
3034
3035                 public void Invalidate(System.Drawing.Rectangle rc, bool invalidateChildren) {
3036                         if (!IsHandleCreated || !Visible || rc.Width == 0 || rc.Height == 0) {
3037                                 return;
3038                         }
3039
3040                         NotifyInvalidate(rc);
3041
3042                         XplatUI.Invalidate(Handle, rc, false);
3043
3044                         if (invalidateChildren) {
3045                                 Control [] controls = child_controls.GetAllControls ();
3046                                 for (int i=0; i<controls.Length; i++)
3047                                         controls [i].Invalidate ();
3048                         }
3049                         OnInvalidated(new InvalidateEventArgs(rc));
3050                 }
3051
3052                 public void Invalidate(System.Drawing.Region region) {
3053                         Invalidate(region, false);
3054                 }
3055
3056                 public void Invalidate(System.Drawing.Region region, bool invalidateChildren) {
3057                         RectangleF bounds = region.GetBounds (CreateGraphics ());
3058                         Invalidate (new Rectangle ((int) bounds.X, (int) bounds.Y, (int) bounds.Width, (int) bounds.Height),
3059                                         invalidateChildren);
3060                 }
3061
3062                 public object Invoke (Delegate method) {
3063                         object [] prms = null;
3064                         if (method is EventHandler)
3065                                 prms = new object [] { this, EventArgs.Empty };
3066
3067                         return Invoke(method, prms);
3068                 }
3069
3070                 public object Invoke (Delegate method, object[] args) {
3071                         if (!this.InvokeRequired) {
3072                                 return method.DynamicInvoke(args);
3073                         }
3074
3075                         IAsyncResult result = BeginInvoke (method, args);
3076                         return EndInvoke(result);
3077                 }
3078
3079                 internal object InvokeInternal (Delegate method, bool disposing) {
3080                         return InvokeInternal(method, null, disposing);
3081                 }
3082
3083                 internal object InvokeInternal (Delegate method, object[] args, bool disposing) {
3084                         if (!this.InvokeRequired) {
3085                                 return method.DynamicInvoke(args);
3086                         }
3087
3088                         IAsyncResult result = BeginInvokeInternal (method, args, disposing);
3089                         return EndInvoke(result);
3090                 }
3091
3092                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3093                 public void PerformLayout() {
3094                         PerformLayout(null, null);
3095                 }
3096
3097 #if !NET_2_0
3098                 private void SetImplicitBounds (int x, int y, int width, int height)
3099                 {
3100                         Rectangle saved_bounds = explicit_bounds;
3101                         SetBounds (x, y, width, height);
3102                         explicit_bounds = saved_bounds;
3103                 }
3104 #endif
3105
3106                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3107                 public void PerformLayout(Control affectedControl, string affectedProperty) {
3108                         LayoutEventArgs levent = new LayoutEventArgs(affectedControl, affectedProperty);
3109
3110                         if (layout_suspended > 0) {
3111                                 layout_pending = true;
3112                                 return;
3113                         }
3114
3115                         layout_pending = false;
3116
3117                         // Prevent us from getting messed up
3118                         layout_suspended++;
3119
3120                         // Perform all Dock and Anchor calculations
3121                         try {
3122
3123 #if NET_2_0
3124                         this.layout_engine.Layout(this, levent);
3125 #else           
3126                                 // This has been moved to Layout/DefaultLayout.cs for 2.0, please duplicate any changes/fixes there.
3127                                 Control         child;
3128                                 AnchorStyles    anchor;
3129                                 Rectangle       space;
3130
3131                                 space = DisplayRectangle;
3132
3133                                 // Deal with docking; go through in reverse, MS docs say that lowest Z-order is closest to edge
3134                                 Control [] controls = child_controls.GetAllControls ();
3135                                 for (int i = controls.Length - 1; i >= 0; i--) {
3136                                         child = controls [i];
3137
3138                                         if (!child.Visible) {
3139                                                 continue;
3140                                         }
3141
3142                                         switch (child.Dock) {
3143                                                 case DockStyle.None: {
3144                                                         // Do nothing
3145                                                         break;
3146                                                 }
3147
3148                                                 case DockStyle.Left: {
3149                                                         child.SetImplicitBounds(space.Left, space.Y, child.Width, space.Height);
3150                                                         space.X+=child.Width;
3151                                                         space.Width-=child.Width;
3152                                                         break;
3153                                                 }
3154
3155                                                 case DockStyle.Top: {
3156                                                         child.SetImplicitBounds(space.Left, space.Y, space.Width, child.Height);
3157                                                         space.Y+=child.Height;
3158                                                         space.Height-=child.Height;
3159                                                         break;
3160                                                 }
3161                                         
3162                                                 case DockStyle.Right: {
3163                                                         child.SetImplicitBounds(space.Right-child.Width, space.Y, child.Width, space.Height);
3164                                                         space.Width-=child.Width;
3165                                                         break;
3166                                                 }
3167
3168                                                 case DockStyle.Bottom: {
3169                                                         child.SetImplicitBounds(space.Left, space.Bottom-child.Height, space.Width, child.Height);
3170                                                         space.Height-=child.Height;
3171                                                         break;
3172                                                 }
3173                                         }
3174                                 }
3175
3176                                 for (int i = controls.Length - 1; i >= 0; i--) {
3177                                         child=controls[i];
3178
3179                                         //if (child.Visible && (child.Dock == DockStyle.Fill)) {
3180                                         if (child.Dock == DockStyle.Fill) {
3181                                                 child.SetImplicitBounds(space.Left, space.Top, space.Width, space.Height);
3182                                         }
3183                                 }
3184
3185                                 space = DisplayRectangle;
3186
3187                                 for (int i=0; i < controls.Length; i++) {
3188                                         int left;
3189                                         int top;
3190                                         int width;
3191                                         int height;
3192
3193                                         child = controls[i];
3194
3195                                         // If the control is docked we don't need to do anything
3196                                         if (child.Dock != DockStyle.None) {
3197                                                 continue;
3198                                         }
3199
3200                                         anchor = child.Anchor;
3201
3202                                         left = child.Left;
3203                                         top = child.Top;
3204                                         width = child.Width;
3205                                         height = child.Height;
3206
3207                                         if ((anchor & AnchorStyles.Left) !=0 ) {
3208                                                 if ((anchor & AnchorStyles.Right) != 0) {
3209                                                         width = space.Width - child.dist_right - left;
3210                                                 } else {
3211                                                         ; // Left anchored only, nothing to be done
3212                                                 }
3213                                         } else if ((anchor & AnchorStyles.Right) != 0) {
3214                                                 left = space.Width - child.dist_right - width;
3215                                         } else {
3216                                                 // left+=diff_width/2 will introduce rounding errors (diff_width removed from svn after r51780)
3217                                                 // This calculates from scratch every time:
3218                                                 left = child.dist_left + (space.Width - (child.dist_left + width + child.dist_right)) / 2;
3219                                         }
3220
3221                                         if ((anchor & AnchorStyles.Top) !=0 ) {
3222                                                 if ((anchor & AnchorStyles.Bottom) != 0) {
3223                                                         height = space.Height - child.dist_bottom - top;
3224                                                 } else {
3225                                                         ; // Top anchored only, nothing to be done
3226                                                 }
3227                                         } else if ((anchor & AnchorStyles.Bottom) != 0) {
3228                                                 top = space.Height - child.dist_bottom - height;
3229                                         } else {
3230                                                 // top += diff_height/2 will introduce rounding errors (diff_height removed from after r51780)
3231                                                 // This calculates from scratch every time:
3232                                                 top = child.dist_top + (space.Height - (child.dist_top + height + child.dist_bottom)) / 2;
3233                                         }
3234                                         
3235                                         // Sanity
3236                                         if (width < 0) {
3237                                                 width=0;
3238                                         }
3239
3240                                         if (height < 0) {
3241                                                 height=0;
3242                                         }
3243
3244                                         child.SetImplicitBounds(left, top, width, height);
3245                                 }
3246 #endif
3247
3248                                 // Let everyone know
3249                                 OnLayout(levent);
3250                         }
3251
3252                                 // Need to make sure we decremend layout_suspended
3253                         finally {
3254                                 layout_suspended--;
3255                         }
3256                 }
3257
3258                 public Point PointToClient (Point p) {
3259                         int x = p.X;
3260                         int y = p.Y;
3261
3262                         XplatUI.ScreenToClient (Handle, ref x, ref y);
3263
3264                         return new Point (x, y);
3265                 }
3266
3267                 public Point PointToScreen(Point p) {
3268                         int x = p.X;
3269                         int y = p.Y;
3270
3271                         XplatUI.ClientToScreen(Handle, ref x, ref y);
3272
3273                         return new Point(x, y);
3274                 }
3275
3276                 public virtual bool PreProcessMessage(ref Message msg) {
3277                         return InternalPreProcessMessage (ref msg);
3278                 }
3279
3280                 internal virtual bool InternalPreProcessMessage (ref Message msg) {
3281                         Keys key_data;
3282
3283                         if ((msg.Msg == (int)Msg.WM_KEYDOWN) || (msg.Msg == (int)Msg.WM_SYSKEYDOWN)) {
3284                                 key_data = (Keys)msg.WParam.ToInt32() | XplatUI.State.ModifierKeys;
3285
3286                                 if (!ProcessCmdKey(ref msg, key_data)) {
3287                                         if (IsInputKey(key_data)) {
3288                                                 return false;
3289                                         }
3290
3291                                         return ProcessDialogKey(key_data);
3292                                 }
3293
3294                                 return true;
3295                         } else if (msg.Msg == (int)Msg.WM_CHAR) {
3296                                 if (IsInputChar((char)msg.WParam)) {
3297                                         return false;
3298                                 }
3299                                 return ProcessDialogChar((char)msg.WParam);
3300                         } else if (msg.Msg == (int)Msg.WM_SYSCHAR) {
3301                                 return ProcessDialogChar((char)msg.WParam);
3302                         }
3303                         return false;
3304                 }
3305
3306                 public Rectangle RectangleToClient(Rectangle r) {
3307                         return new Rectangle(PointToClient(r.Location), r.Size);
3308                 }
3309
3310                 public Rectangle RectangleToScreen(Rectangle r) {
3311                         return new Rectangle(PointToScreen(r.Location), r.Size);
3312                 }
3313
3314                 public virtual void Refresh() {                 
3315                         if (IsHandleCreated == true) {
3316                                 Invalidate();
3317                                 XplatUI.UpdateWindow(window.Handle);
3318
3319                                 Control [] controls = child_controls.GetAllControls ();
3320                                 for (int i=0; i < controls.Length; i++) {
3321                                         controls[i].Refresh();
3322                                 }
3323                                 
3324                         }
3325                 }
3326
3327                 [EditorBrowsable(EditorBrowsableState.Never)]
3328                 public virtual void ResetBackColor() {
3329                         BackColor = Color.Empty;
3330                 }
3331
3332                 [EditorBrowsable(EditorBrowsableState.Never)]
3333                 public void ResetBindings() {
3334                         data_bindings.Clear();
3335                 }
3336
3337                 [EditorBrowsable(EditorBrowsableState.Never)]
3338                 public virtual void ResetCursor() {
3339                         Cursor = null;
3340                 }
3341
3342                 [EditorBrowsable(EditorBrowsableState.Never)]
3343                 public virtual void ResetFont() {
3344                         font = null;
3345                 }
3346
3347                 [EditorBrowsable(EditorBrowsableState.Never)]
3348                 public virtual void ResetForeColor() {
3349                         foreground_color = Color.Empty;
3350                 }
3351
3352                 [EditorBrowsable(EditorBrowsableState.Never)]
3353                 public void ResetImeMode() {
3354                         ime_mode = DefaultImeMode;
3355                 }
3356
3357                 [EditorBrowsable(EditorBrowsableState.Never)]
3358                 public virtual void ResetRightToLeft() {
3359                         right_to_left = RightToLeft.Inherit;
3360                 }
3361
3362                 public virtual void ResetText() {
3363                         text = String.Empty;
3364                 }
3365
3366                 public void ResumeLayout() {
3367                         ResumeLayout (true);
3368                 }
3369
3370                 public void ResumeLayout(bool performLayout) {
3371                         if (layout_suspended > 0) {
3372                                 layout_suspended--;
3373                         }
3374
3375                         if (layout_suspended == 0) {
3376                                 Control [] controls = child_controls.GetAllControls ();
3377                                 if (performLayout && layout_pending) {
3378                                         PerformLayout();
3379                                 }
3380                         }
3381                 }
3382 #if NET_2_0
3383                 [EditorBrowsable (EditorBrowsableState.Never)]
3384                 [Obsolete ()]
3385 #endif
3386                 public void Scale(float ratio) {
3387                         ScaleCore(ratio, ratio);
3388                 }
3389                 
3390 #if NET_2_0
3391                 [EditorBrowsable (EditorBrowsableState.Never)]
3392                 [Obsolete ()]
3393 #endif
3394                 public void Scale(float dx, float dy) {
3395                         ScaleCore(dx, dy);
3396                 }
3397
3398 #if NET_2_0
3399                 [EditorBrowsable (EditorBrowsableState.Advanced)]
3400                 public void Scale(SizeF factor) {
3401                         ScaleCore(factor.Width, factor.Height);
3402                 }
3403 #endif
3404
3405                 public void Select() {
3406                         Select(false, false);
3407                 }
3408
3409 #if DebugFocus
3410                 private void printTree(Control c, string t) {
3411                         foreach(Control i in c.child_controls) {
3412                                 Console.WriteLine("{2}{0}.TabIndex={1}", i, i.tab_index, t);
3413                                 printTree(i, t+"\t");
3414                         }
3415                 }
3416 #endif
3417                 public bool SelectNextControl(Control ctl, bool forward, bool tabStopOnly, bool nested, bool wrap) {
3418                         Control c;
3419
3420 #if DebugFocus
3421                         Console.WriteLine("{0}", this.FindForm());
3422                         printTree(this, "\t");
3423 #endif
3424
3425                         if (!this.Contains(ctl) || (!nested && (ctl.parent != this))) {
3426                                 ctl = null;
3427                         }
3428                         c = ctl;
3429                         do {
3430                                 c = GetNextControl(c, forward);
3431                                 if (c == null) {
3432                                         if (wrap) {
3433                                                 wrap = false;
3434                                                 continue;
3435                                         }
3436                                         break;
3437                                 }
3438
3439                                 if (c.CanSelect && ((c.parent == this) || nested) && (c.tab_stop || !tabStopOnly)) {
3440                                         c.Select (true, true);
3441                                         return true;
3442                                 }
3443                         } while (c != ctl); // If we wrap back to ourselves we stop
3444
3445                         return false;
3446                 }
3447
3448                 public void SendToBack() {
3449                         if (parent != null) {
3450                                 parent.child_controls.SetChildIndex(this, parent.child_controls.Count);
3451                         }
3452                 }
3453
3454                 public void SetBounds(int x, int y, int width, int height) {
3455                         SetBounds(x, y, width, height, BoundsSpecified.All);
3456                 }
3457
3458                 public void SetBounds(int x, int y, int width, int height, BoundsSpecified specified) {
3459                         if ((specified & BoundsSpecified.X) != BoundsSpecified.X) {
3460                                 x = Left;
3461                         }
3462
3463                         if ((specified & BoundsSpecified.Y) != BoundsSpecified.Y) {
3464                                 y = Top;
3465                         }
3466
3467                         if ((specified & BoundsSpecified.Width) != BoundsSpecified.Width) {
3468                                 width = Width;
3469                         }
3470
3471                         if ((specified & BoundsSpecified.Height) != BoundsSpecified.Height) {
3472                                 height = Height;
3473                         }
3474
3475                         SetBoundsCore(x, y, width, height, specified);
3476                         if (parent != null) {
3477                                 parent.PerformLayout(this, "Bounds");
3478                         }
3479                 }
3480
3481                 public void Show() {
3482                         if (!is_created) {
3483                                 this.CreateControl();
3484                         }
3485
3486                         this.Visible=true;
3487                 }
3488
3489                 public void SuspendLayout() {
3490                         layout_suspended++;
3491                 }
3492
3493                 public void Update() {
3494                         if (IsHandleCreated) {
3495                                 XplatUI.UpdateWindow(window.Handle);
3496                         }
3497                 }
3498                 #endregion      // Public Instance Methods
3499
3500                 #region Protected Instance Methods
3501                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3502                 [MonoTODO("Implement this and tie it into Control.ControlAccessibleObject.NotifyClients")]
3503                 protected void AccessibilityNotifyClients(AccessibleEvents accEvent, int childID) {
3504                         throw new NotImplementedException();
3505                 }
3506
3507                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3508                 protected virtual AccessibleObject CreateAccessibilityInstance() {
3509                         return new Control.ControlAccessibleObject(this);
3510                 }
3511
3512                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3513                 protected virtual ControlCollection CreateControlsInstance() {
3514                         return new ControlCollection(this);
3515                 }
3516
3517                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3518                 protected virtual void CreateHandle() {
3519                         if (IsDisposed) {
3520                                 throw new ObjectDisposedException(GetType().FullName.ToString());
3521                         }
3522
3523                         if (IsHandleCreated && !is_recreating) {
3524                                 return;
3525                         }
3526
3527                         window.CreateHandle(CreateParams);
3528
3529                         if (window.Handle != IntPtr.Zero) {
3530                                 creator_thread = Thread.CurrentThread;
3531
3532                                 XplatUI.EnableWindow(window.Handle, is_enabled);
3533                                 XplatUI.SetVisible(window.Handle, is_visible, true);
3534
3535                                 if (clip_region != null) {
3536                                         XplatUI.SetClipRegion(Handle, clip_region);
3537                                 }
3538
3539                                 // Set our handle with our parent
3540                                 if ((parent != null) && (parent.IsHandleCreated)) {
3541                                         XplatUI.SetParent(window.Handle, parent.Handle);
3542                                 }
3543
3544                                 // Set our handle as parent for our children
3545                                 Control [] children;
3546
3547                                 children = child_controls.GetAllControls ();
3548                                 for (int i = 0; i < children.Length; i++ ) {
3549                                         if (!children[i].RecreatingHandle)
3550                                                 XplatUI.SetParent(children[i].Handle, window.Handle); 
3551                                 }
3552
3553                                 UpdateStyles();
3554                                 XplatUI.SetAllowDrop (Handle, allow_drop);
3555
3556                                 // Find out where the window manager placed us
3557                                 if ((CreateParams.Style & (int)WindowStyles.WS_CHILD) != 0) {
3558                                         XplatUI.SetBorderStyle(window.Handle, (FormBorderStyle)border_style);
3559                                 }
3560                                 UpdateBounds();
3561
3562                                 OnHandleCreated(EventArgs.Empty);
3563                         }
3564                 }
3565
3566                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3567                 protected virtual void DefWndProc(ref Message m) {
3568                         window.DefWndProc(ref m);
3569                 }
3570
3571                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3572                 protected virtual void DestroyHandle() {
3573                         if (IsHandleCreated) {
3574                                 if (window != null) {
3575                                         window.DestroyHandle();
3576                                 }
3577                         }
3578                 }
3579
3580                 protected internal bool GetStyle(ControlStyles flag) {
3581                         return (control_style & flag) != 0;
3582                 }
3583
3584                 protected bool GetTopLevel() {
3585                         return is_toplevel;
3586                 }
3587
3588                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3589                 protected virtual void InitLayout() {
3590                         UpdateDistances();
3591                 }
3592
3593                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3594                 protected void InvokeGotFocus(Control toInvoke, EventArgs e) {
3595                         toInvoke.OnGotFocus(e);
3596                 }
3597
3598                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3599                 protected void InvokeLostFocus(Control toInvoke, EventArgs e) {
3600                         toInvoke.OnLostFocus(e);
3601                 }
3602
3603                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3604                 protected void InvokeOnClick(Control toInvoke, EventArgs e) {
3605                         toInvoke.OnClick(e);
3606                 }
3607
3608                 protected void InvokePaint(Control toInvoke, PaintEventArgs e) {
3609                         toInvoke.OnPaint(e);
3610                 }
3611
3612                 protected void InvokePaintBackground(Control toInvoke, PaintEventArgs e) {
3613                         toInvoke.OnPaintBackground(e);
3614                 }
3615
3616                 protected virtual bool IsInputChar (char charCode) {
3617                         return true;
3618                 }
3619
3620                 protected virtual bool IsInputKey (Keys keyData) {
3621                         // Doc says this one calls IsInputChar; not sure what to do with that
3622                         return false;
3623                 }
3624
3625                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3626                 protected virtual void NotifyInvalidate(Rectangle invalidatedArea) {
3627                         // override me?
3628                 }
3629
3630                 protected virtual bool ProcessCmdKey(ref Message msg, Keys keyData) {
3631                         if ((context_menu != null) && context_menu.ProcessCmdKey(ref msg, keyData)) {
3632                                 return true;
3633                         }
3634
3635                         if (parent != null) {
3636                                 return parent.ProcessCmdKey(ref msg, keyData);
3637                         }
3638
3639                         return false;
3640                 }
3641
3642                 protected virtual bool ProcessDialogChar(char charCode) {
3643                         if (parent != null) {
3644                                 return parent.ProcessDialogChar (charCode);
3645                         }
3646
3647                         return false;
3648                 }
3649
3650                 protected virtual bool ProcessDialogKey (Keys keyData) {
3651                         if (parent != null) {
3652                                 return parent.ProcessDialogKey (keyData);
3653                         }
3654
3655                         return false;
3656                 }
3657
3658                 protected virtual bool ProcessKeyEventArgs (ref Message msg)
3659                 {
3660                         KeyEventArgs            key_event;
3661
3662                         switch (msg.Msg) {
3663                                 case (int)Msg.WM_SYSKEYDOWN:
3664                                 case (int)Msg.WM_KEYDOWN: {
3665                                         key_event = new KeyEventArgs ((Keys)msg.WParam.ToInt32 ());
3666                                         OnKeyDown (key_event);
3667                                         return key_event.Handled;
3668                                 }
3669
3670                                 case (int)Msg.WM_SYSKEYUP:
3671                                 case (int)Msg.WM_KEYUP: {
3672                                         key_event = new KeyEventArgs ((Keys)msg.WParam.ToInt32 ());
3673                                         OnKeyUp (key_event);
3674                                         return key_event.Handled;
3675                                 }
3676
3677                                 case (int)Msg.WM_SYSCHAR:
3678                                 case (int)Msg.WM_CHAR: {
3679                                         KeyPressEventArgs       key_press_event;
3680
3681                                         key_press_event = new KeyPressEventArgs((char)msg.WParam);
3682                                         OnKeyPress(key_press_event);
3683 #if NET_2_0
3684                                         msg.WParam = (IntPtr)key_press_event.KeyChar;
3685 #endif
3686                                         return key_press_event.Handled;
3687                                 }
3688
3689                                 default: {
3690                                         break;
3691                                 }
3692                         }
3693
3694                         return false;
3695                 }
3696
3697                 protected internal virtual bool ProcessKeyMessage(ref Message msg) {
3698                         if (parent != null) {
3699                                 if (parent.ProcessKeyPreview(ref msg)) {
3700                                         return true;
3701                                 }
3702                         }
3703
3704                         return ProcessKeyEventArgs(ref msg);
3705                 }
3706
3707                 protected virtual bool ProcessKeyPreview(ref Message msg) {
3708                         if (parent != null) {
3709                                 return parent.ProcessKeyPreview(ref msg);
3710                         }
3711
3712                         return false;
3713                 }
3714
3715                 protected virtual bool ProcessMnemonic(char charCode) {
3716                         // override me
3717                         return false;
3718                 }
3719
3720                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3721                 protected void RaiseDragEvent(object key, DragEventArgs e) {
3722                         // MS Internal
3723                 }
3724
3725                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3726                 protected void RaiseKeyEvent(object key, KeyEventArgs e) {
3727                         // MS Internal
3728                 }
3729
3730                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3731                 protected void RaiseMouseEvent(object key, MouseEventArgs e) {
3732                         // MS Internal
3733                 }
3734
3735                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3736                 protected void RaisePaintEvent(object key, PaintEventArgs e) {
3737                         // MS Internal
3738                 }
3739
3740                 private void SetIsRecreating ()
3741                 {
3742                         is_recreating=true;
3743
3744                         foreach (Control c in Controls.GetAllControls()) {
3745                                 c.SetIsRecreating ();
3746                         }
3747                 }
3748
3749                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3750                 protected void RecreateHandle() {
3751 #if DebugRecreate
3752                         Console.WriteLine("Recreating control {0}", XplatUI.Window(window.Handle));
3753 #endif
3754
3755                         SetIsRecreating ();
3756
3757                         if (IsHandleCreated) {
3758 #if DebugRecreate
3759                                 Console.WriteLine(" + handle is created, destroying it.");
3760 #endif
3761                                 DestroyHandle();
3762                                 // WM_DESTROY will CreateHandle for us
3763                         } else {
3764 #if DebugRecreate
3765                                 Console.WriteLine(" + handle is not created, creating it.");
3766 #endif
3767                                 if (!is_created) {
3768                                         CreateControl();
3769                                 } else {
3770                                         CreateHandle();
3771                                 }
3772
3773                                 is_recreating = false;
3774 #if DebugRecreate
3775                                 Console.WriteLine (" + new handle = {0:X}", Handle.ToInt32());
3776 #endif
3777                         }
3778
3779                 }
3780
3781                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3782                 protected void ResetMouseEventArgs() {
3783                         // MS Internal
3784                 }
3785
3786                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3787                 protected ContentAlignment RtlTranslateAlignment(ContentAlignment align) {
3788                         if (right_to_left == RightToLeft.No) {
3789                                 return align;
3790                         }
3791
3792                         switch (align) {
3793                                 case ContentAlignment.TopLeft: {
3794                                         return ContentAlignment.TopRight;
3795                                 }
3796
3797                                 case ContentAlignment.TopRight: {
3798                                         return ContentAlignment.TopLeft;
3799                                 }
3800
3801                                 case ContentAlignment.MiddleLeft: {
3802                                         return ContentAlignment.MiddleRight;
3803                                 }
3804
3805                                 case ContentAlignment.MiddleRight: {
3806                                         return ContentAlignment.MiddleLeft;
3807                                 }
3808
3809                                 case ContentAlignment.BottomLeft: {
3810                                         return ContentAlignment.BottomRight;
3811                                 }
3812
3813                                 case ContentAlignment.BottomRight: {
3814                                         return ContentAlignment.BottomLeft;
3815                                 }
3816
3817                                 default: {
3818                                         // if it's center it doesn't change
3819                                         return align;
3820                                 }
3821                         }
3822                 }
3823
3824                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3825                 protected HorizontalAlignment RtlTranslateAlignment(HorizontalAlignment align) {
3826                         if ((right_to_left == RightToLeft.No) || (align == HorizontalAlignment.Center)) {
3827                                 return align;
3828                         }
3829
3830                         if (align == HorizontalAlignment.Left) {
3831                                 return HorizontalAlignment.Right;
3832                         }
3833
3834                         // align must be HorizontalAlignment.Right
3835                         return HorizontalAlignment.Left;
3836                 }
3837
3838                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3839                 protected LeftRightAlignment RtlTranslateAlignment(LeftRightAlignment align) {
3840                         if (right_to_left == RightToLeft.No) {
3841                                 return align;
3842                         }
3843
3844                         if (align == LeftRightAlignment.Left) {
3845                                 return LeftRightAlignment.Right;
3846                         }
3847
3848                         // align must be LeftRightAlignment.Right;
3849                         return LeftRightAlignment.Left;
3850                 }
3851
3852                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3853                 protected ContentAlignment RtlTranslateContent(ContentAlignment align) {
3854                         return RtlTranslateAlignment(align);
3855                 }
3856
3857                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3858                 protected HorizontalAlignment RtlTranslateHorizontal(HorizontalAlignment align) {
3859                         return RtlTranslateAlignment(align);
3860                 }
3861
3862                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3863                 protected LeftRightAlignment RtlTranslateLeftRight(LeftRightAlignment align) {
3864                         return RtlTranslateAlignment(align);
3865                 }
3866
3867                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3868                 protected virtual void ScaleCore(float dx, float dy) {
3869                         Point   location;
3870                         Size    size;
3871
3872                         SuspendLayout();
3873
3874                         location = new Point((int)(Left * dx), (int)(Top * dy));
3875                         size = this.ClientSize;
3876
3877                         if (!GetStyle(ControlStyles.FixedWidth)) {
3878                                 size.Width = (int)(size.Width * dx);
3879                         }
3880
3881                         if (!GetStyle(ControlStyles.FixedHeight)) {
3882                                 size.Height = (int)(size.Height * dy);
3883                         }
3884
3885                         SetBounds(location.X, location.Y, size.Width, size.Height, BoundsSpecified.All);
3886
3887                         /* Now scale our children */
3888                         Control [] controls = child_controls.GetAllControls ();
3889                         for (int i=0; i < controls.Length; i++) {
3890                                 controls[i].Scale(dx, dy);
3891                         }
3892
3893                         ResumeLayout();
3894                 }
3895
3896                 protected virtual void Select(bool directed, bool forward) {
3897                         IContainerControl       container;
3898                         
3899                         container = GetContainerControl();
3900                         if (container != null)
3901                                 container.ActiveControl = this;
3902                 }
3903
3904                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3905                 protected virtual void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) {
3906                         // SetBoundsCore updates the Win32 control itself. UpdateBounds updates the controls variables and fires events, I'm guessing - pdb
3907                         if (IsHandleCreated) {
3908                                 XplatUI.SetWindowPos(Handle, x, y, width, height);
3909
3910                                 // Win32 automatically changes negative width/height to 0.
3911                                 // The control has already been sent a WM_WINDOWPOSCHANGED message and it has the correct
3912                                 // data, but it'll be overwritten when we call UpdateBounds unless we get the updated
3913                                 // size.
3914                                 if (width < 0 || height < 0) {
3915                                         int cw, ch, ix, iy;
3916                                         XplatUI.GetWindowPos(Handle, this is Form, out ix, out iy, out width, out height, out cw, out ch);
3917                                 }
3918                         }
3919
3920                         UpdateBounds(x, y, width, height);
3921
3922                         UpdateDistances();
3923                 }
3924
3925                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3926                 protected virtual void SetClientSizeCore(int x, int y) {
3927                         // Calculate the actual window size from the client size (it usually stays the same or grows)
3928                         Rectangle       ClientRect;
3929                         Rectangle       WindowRect;
3930                         CreateParams    cp;
3931
3932                         ClientRect = new Rectangle(0, 0, x, y);
3933                         cp = this.CreateParams;
3934
3935                         if (XplatUI.CalculateWindowRect(ref ClientRect, cp.Style, cp.ExStyle, null, out WindowRect)==false) {
3936                                 return;
3937                         }
3938
3939                         SetBounds(bounds.X, bounds.Y, WindowRect.Width, WindowRect.Height, BoundsSpecified.Size);
3940                 }
3941
3942                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3943                 protected internal void SetStyle(ControlStyles flag, bool value) {
3944                         if (value) {
3945                                 control_style |= flag;
3946                         } else {
3947                                 control_style &= ~flag;
3948                         }
3949                 }
3950
3951                 protected void SetTopLevel(bool value) {
3952                         if ((GetTopLevel() != value) && (parent != null)) {
3953                                 throw new Exception();
3954                         }
3955
3956                         if (this is Form) {
3957                                 if (value == true) {
3958                                         if (!Visible) {
3959                                                 Visible = true;
3960                                         }
3961                                 } else {
3962                                         if (Visible) {
3963                                                 Visible = false;
3964                                         }
3965                                 }
3966                         }
3967                         is_toplevel = value;
3968                 }
3969
3970                 protected virtual void SetVisibleCore(bool value) {
3971                         if (value!=is_visible) {
3972                                 if (value && (window.Handle == IntPtr.Zero) || !is_created) {
3973                                         CreateControl();
3974                                 }
3975
3976                                 is_visible=value;
3977
3978                                 if (IsHandleCreated) {
3979                                         XplatUI.SetVisible(Handle, value, true);
3980                                         // Explicitly move Toplevel windows to where we want them;
3981                                         // apparently moving unmapped toplevel windows doesn't work
3982                                         if (is_visible && (this is Form)) {
3983                                                 XplatUI.SetWindowPos(window.Handle, bounds.X, bounds.Y, bounds.Width, bounds.Height);
3984                                         }
3985                                 }
3986
3987                                 OnVisibleChanged(EventArgs.Empty);
3988
3989                                 if (value == false && parent != null && Focused) {
3990                                         Control container;
3991
3992                                         // Need to start at parent, GetContainerControl might return ourselves if we're a container
3993                                         container = (Control)parent.GetContainerControl();
3994                                         if (container != null) {
3995                                                 container.SelectNextControl(this, true, true, true, true);
3996                                         }
3997                                 }
3998
3999                                 if (parent != null) {
4000                                         parent.PerformLayout(this, "visible");
4001                                 } else {
4002                                         PerformLayout(this, "visible");
4003                                 }
4004                         }
4005                 }
4006         
4007                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4008                 protected void UpdateBounds() {
4009                         int     x;
4010                         int     y;
4011                         int     width;
4012                         int     height;
4013                         int     client_width;
4014                         int     client_height;
4015
4016                         if (!IsHandleCreated) {
4017                                 CreateHandle();
4018                         }
4019
4020                         XplatUI.GetWindowPos(this.Handle, this is Form, out x, out y, out width, out height, out client_width, out client_height);
4021
4022                         UpdateBounds(x, y, width, height, client_width, client_height);
4023                 }
4024
4025                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4026                 protected void UpdateBounds(int x, int y, int width, int height) {
4027                         CreateParams    cp;
4028                         Rectangle       rect;
4029
4030                         // Calculate client rectangle
4031                         rect = new Rectangle(0, 0, 0, 0);
4032                         cp = CreateParams;
4033
4034                         XplatUI.CalculateWindowRect(ref rect, cp.Style, cp.ExStyle, cp.menu, out rect);
4035                         UpdateBounds(x, y, width, height, width - (rect.Right - rect.Left), height - (rect.Bottom - rect.Top));
4036                 }
4037
4038                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4039                 protected void UpdateBounds(int x, int y, int width, int height, int clientWidth, int clientHeight) {
4040                         // UpdateBounds only seems to set our sizes and fire events but not update the GUI window to match
4041                         bool    moved   = false;
4042                         bool    resized = false;
4043
4044                         // Needed to generate required notifications
4045                         if ((this.bounds.X!=x) || (this.bounds.Y!=y)) {
4046                                 moved=true;
4047                         }
4048
4049                         if ((this.Bounds.Width!=width) || (this.Bounds.Height!=height)) {
4050                                 resized=true;
4051                         }
4052
4053                         bounds.X=x;
4054                         bounds.Y=y;
4055                         bounds.Width=width;
4056                         bounds.Height=height;
4057
4058                         // Assume explicit bounds set. SetImplicitBounds will restore old bounds
4059                         explicit_bounds = bounds;
4060
4061                         client_size.Width=clientWidth;
4062                         client_size.Height=clientHeight;
4063
4064                         if (moved) {
4065                                 OnLocationChanged(EventArgs.Empty);
4066                         }
4067
4068                         if (resized) {
4069                                 OnSizeChanged(EventArgs.Empty);
4070                         }
4071                 }
4072
4073                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4074                 protected void UpdateStyles() {
4075                         if (!IsHandleCreated) {
4076                                 return;
4077                         }
4078
4079                         XplatUI.SetWindowStyle(window.Handle, CreateParams);
4080                         OnStyleChanged(EventArgs.Empty);
4081                 }
4082
4083                 private void UpdateZOrderOfChild(Control child) {
4084                         if (IsHandleCreated && child.IsHandleCreated && (child.parent == this)) {
4085                                 int     index;
4086
4087                                 index = child_controls.IndexOf(child);
4088
4089                                 if (index > 0) {
4090                                         XplatUI.SetZOrder(child.Handle, child_controls[index - 1].Handle, false, false);
4091                                 } else {
4092                                         IntPtr after = AfterTopMostControl ();
4093                                         if (after != IntPtr.Zero)
4094                                                 XplatUI.SetZOrder (child.Handle, after, false, false);
4095                                         else
4096                                                 XplatUI.SetZOrder (child.Handle, IntPtr.Zero, true, false);
4097                                 }
4098                         }
4099                 }
4100                 
4101                 // Override this if there is a control that shall always remain on
4102                 // top of other controls (such as scrollbars). If there are several
4103                 // of these controls, the bottom-most should be returned.
4104                 internal virtual IntPtr AfterTopMostControl ()
4105                 {
4106                         return IntPtr.Zero;
4107                 }
4108
4109                 private void UpdateChildrenZOrder() {
4110                         Control [] controls;
4111
4112                         if (!IsHandleCreated) {
4113                                 return;
4114                         }
4115
4116                         controls = child_controls.GetAllControls ();
4117                         for (int i = 1; i < controls.Length; i++ ) {
4118                                 XplatUI.SetZOrder(controls[i].Handle, controls[i-1].Handle, false, false);
4119                         }
4120                 }
4121
4122                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4123                 protected void UpdateZOrder() {
4124                         if (parent != null) {
4125                                 parent.UpdateZOrderOfChild(this);
4126                         }
4127                 }
4128
4129                 protected virtual void WndProc(ref Message m) {
4130 #if debug
4131                         Console.WriteLine("Control {0} received message {1}", window.Handle == IntPtr.Zero ? this.Text : XplatUI.Window(window.Handle), m.ToString ());
4132 #endif
4133                         if ((this.control_style & ControlStyles.EnableNotifyMessage) != 0) {
4134                                 OnNotifyMessage(m);
4135                         }
4136
4137                         switch((Msg)m.Msg) {
4138                         case Msg.WM_DESTROY: {
4139                                 OnHandleDestroyed(EventArgs.Empty);
4140 #if DebugRecreate
4141                                 IntPtr handle = window.Handle;
4142 #endif
4143                                 window.InvalidateHandle();
4144
4145                                 if (is_recreating) {
4146 #if DebugRecreate
4147                                         Console.WriteLine ("Creating handle for {0:X}", handle.ToInt32());
4148 #endif
4149                                         CreateHandle();
4150 #if DebugRecreate
4151                                         Console.WriteLine (" + new handle = {0:X}", Handle.ToInt32());
4152 #endif
4153                                         is_recreating = false;
4154                                 }
4155                                 return;
4156                         }
4157
4158                         case Msg.WM_WINDOWPOSCHANGED: {
4159                                 if (Visible) {
4160                                         Rectangle save_bounds = explicit_bounds;
4161                                         UpdateBounds();
4162                                         explicit_bounds = save_bounds;
4163                                         if (GetStyle(ControlStyles.ResizeRedraw)) {
4164                                                 Invalidate();
4165                                         }
4166                                 }
4167                                 return;
4168                         }
4169
4170                         // Nice description of what should happen when handling WM_PAINT
4171                         // can be found here: http://pluralsight.com/wiki/default.aspx/Craig/FlickerFreeControlDrawing.html
4172                         // and here http://msdn.microsoft.com/msdnmag/issues/06/03/WindowsFormsPerformance/
4173                         case Msg.WM_PAINT: {
4174                                 PaintEventArgs  paint_event;
4175
4176                                 paint_event = XplatUI.PaintEventStart(Handle, true);
4177
4178                                 if (paint_event == null) {
4179                                         return;
4180                                 }
4181
4182                                 if (invalid_region != null && !invalid_region.IsVisible (paint_event.ClipRectangle)) {
4183
4184                                         // Just blit the previous image
4185                                         XplatUI.BlitFromOffscreen (Handle, paint_event.Graphics, backbuffer, backbuffer_dc, paint_event.ClipRectangle);
4186                                         XplatUI.PaintEventEnd (Handle, true);
4187                                         return;
4188                                 }
4189
4190                                 Graphics dc = null;
4191                                 Graphics back_dc = null;
4192                                 object back = null;
4193                                 if (ThemeEngine.Current.DoubleBufferingSupported) {
4194                                         if ((control_style & ControlStyles.DoubleBuffer) != 0) {
4195                                                 CreateBackBuffer ();
4196                                                 back = backbuffer;
4197                                                 back_dc = backbuffer_dc;
4198                                                 dc = paint_event.SetGraphics (back_dc);
4199                                         }
4200                                 }
4201
4202                                 if (!GetStyle(ControlStyles.Opaque)) {
4203                                         OnPaintBackground(paint_event);
4204                                 }
4205
4206                                 // Button-derived controls choose to ignore their Opaque style, give them a chance to draw their background anyways
4207                                 OnPaintBackgroundInternal(paint_event);
4208
4209                                 OnPaintInternal(paint_event);
4210                                 if (!paint_event.Handled) {
4211                                         OnPaint(paint_event);
4212                                 }
4213
4214                                 if (ThemeEngine.Current.DoubleBufferingSupported)
4215                                         if ((control_style & ControlStyles.DoubleBuffer) != 0) {
4216                                                 XplatUI.BlitFromOffscreen (Handle, dc, back, back_dc, paint_event.ClipRectangle);
4217                                                 paint_event.SetGraphics (dc);
4218                                                 invalid_region.Exclude (paint_event.ClipRectangle);
4219
4220                                                 if (back != backbuffer)
4221                                                         XplatUI.DestroyOffscreenDrawable (back, back_dc);
4222                                         }
4223
4224                                 XplatUI.PaintEventEnd(Handle, true);
4225
4226                                 return;
4227                         }
4228                                         
4229                         case Msg.WM_ERASEBKGND: {
4230                                 // The DefWndProc will never have to handle this, we always paint the background in managed code
4231                                 // In theory this code would look at ControlStyles.AllPaintingInWmPaint and and call OnPaintBackground
4232                                 // here but it just makes things more complicated...
4233                                 m.Result = (IntPtr)1;
4234                                 return;
4235                         }
4236
4237                         case Msg.WM_LBUTTONUP: {
4238                                 MouseEventArgs me;
4239
4240                                 me = new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()) | MouseButtons.Left, 
4241                                                          mouse_clicks, 
4242                                                          LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
4243                                                          0);
4244
4245                                 HandleClick(mouse_clicks, me);
4246                                 OnMouseUp (me);
4247
4248                                 if (InternalCapture) {
4249                                         InternalCapture = false;
4250                                 }
4251
4252                                 if (mouse_clicks > 1) {
4253                                         mouse_clicks = 1;
4254                                 }
4255                                 return;
4256                         }
4257                                         
4258                         case Msg.WM_LBUTTONDOWN: {
4259                                 if (CanSelect) {
4260                                         Select (true, true);
4261                                 }
4262                                 InternalCapture = true;
4263                                 OnMouseDown (new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()), 
4264                                                                  mouse_clicks, LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
4265                                                                  0));
4266                                 
4267                                 return;
4268                         }
4269
4270                         case Msg.WM_LBUTTONDBLCLK: {
4271                                 InternalCapture = true;
4272                                 mouse_clicks++;
4273                                 OnMouseDown (new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()), 
4274                                                                  mouse_clicks, LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
4275                                                                  0));
4276                                 return;
4277                         }
4278
4279                         case Msg.WM_MBUTTONUP: {
4280                                 MouseEventArgs me;
4281
4282                                 me = new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()) | MouseButtons.Middle, 
4283                                                          mouse_clicks, 
4284                                                          LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
4285                                                          0);
4286
4287                                 HandleClick(mouse_clicks, me);
4288                                 OnMouseUp (me);
4289                                 if (InternalCapture) {
4290                                         InternalCapture = false;
4291                                 }
4292                                 if (mouse_clicks > 1) {
4293                                         mouse_clicks = 1;
4294                                 }
4295                                 return;
4296                         }
4297                                         
4298                         case Msg.WM_MBUTTONDOWN: {                                      
4299                                 InternalCapture = true;
4300                                 OnMouseDown (new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()), 
4301                                                                  mouse_clicks, LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
4302                                                                  0));
4303                                 return;
4304                         }
4305
4306                         case Msg.WM_MBUTTONDBLCLK: {
4307                                 InternalCapture = true;
4308                                 mouse_clicks++;
4309                                 OnMouseDown (new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()), 
4310                                                                  mouse_clicks, LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
4311                                                                  0));
4312                                 return;
4313                         }
4314
4315                         case Msg.WM_RBUTTONUP: {
4316                                 MouseEventArgs  me;
4317                                 Point           pt;
4318
4319                                 pt = new Point(LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()));
4320                                 pt = PointToScreen(pt);
4321
4322                                 XplatUI.SendMessage(m.HWnd, Msg.WM_CONTEXTMENU, m.HWnd, (IntPtr)(pt.X + (pt.Y << 16)));
4323
4324                                 me = new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()) | MouseButtons.Right, 
4325                                                          mouse_clicks, 
4326                                                          LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
4327                                                          0);
4328
4329                                 HandleClick(mouse_clicks, me);
4330                                 OnMouseUp (me);
4331
4332                                 if (InternalCapture) {
4333                                         InternalCapture = false;
4334                                 }
4335
4336                                 if (mouse_clicks > 1) {
4337                                         mouse_clicks = 1;
4338                                 }
4339                                 return;
4340                         }
4341                                         
4342                         case Msg.WM_RBUTTONDOWN: {                                      
4343                                 InternalCapture = true;
4344                                 OnMouseDown (new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()), 
4345                                                                  mouse_clicks, LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
4346                                                                  0));
4347                                 return;
4348                         }
4349
4350                         case Msg.WM_RBUTTONDBLCLK: {
4351                                 InternalCapture = true;
4352                                 mouse_clicks++;
4353                                 OnMouseDown (new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()), 
4354                                                                  mouse_clicks, LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
4355                                                                  0));
4356                                 return;
4357                         }
4358
4359                         case Msg.WM_CONTEXTMENU: {
4360                                 if (context_menu != null) {
4361                                         Point   pt;
4362
4363                                         pt = new Point(LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()));
4364                                         context_menu.Show(this, PointToClient(pt));
4365                                         return;
4366                                 }
4367
4368                                 DefWndProc(ref m);
4369                                 return;
4370                         }
4371
4372                         case Msg.WM_MOUSEWHEEL: {                               
4373                                 DefWndProc(ref m);
4374                                 OnMouseWheel (new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()), 
4375                                                                   mouse_clicks, LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
4376                                                                   HighOrder(m.WParam.ToInt32())));
4377                                 return;
4378                         }
4379
4380
4381                         case Msg.WM_MOUSEMOVE: {                                        
4382                                 OnMouseMove  (new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()), 
4383                                                                   mouse_clicks, 
4384                                                                   LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
4385                                                                   0));
4386                                 return;
4387                         }
4388
4389                         case Msg.WM_MOUSE_ENTER: {
4390                                 if (is_entered) {
4391                                         return;
4392                                 }
4393                                 is_entered = true;
4394                                 OnMouseEnter(EventArgs.Empty);
4395                                 return;
4396                         }
4397
4398                         case Msg.WM_MOUSE_LEAVE: {
4399                                 is_entered=false;
4400                                 OnMouseLeave(EventArgs.Empty);
4401                                 return;
4402                         }
4403
4404                         case Msg.WM_MOUSEHOVER: {
4405                                 OnMouseHover(EventArgs.Empty);
4406                                 return;
4407                         }
4408
4409                         case Msg.WM_SYSKEYUP: {
4410                                 if (ProcessKeyMessage(ref m)) {
4411                                         m.Result = IntPtr.Zero;
4412                                         return;
4413                                 }
4414
4415                                 if ((m.WParam.ToInt32() & (int)Keys.KeyCode) == (int)Keys.Menu) {
4416                                         Form    form;
4417
4418                                         form = FindForm();
4419                                         if (form != null && form.ActiveMenu != null) {
4420                                                 form.ActiveMenu.ProcessCmdKey(ref m, (Keys)m.WParam.ToInt32());
4421                                         }
4422                                 }
4423
4424                                 DefWndProc (ref m);
4425                                 return;
4426                         }
4427
4428                         case Msg.WM_SYSKEYDOWN:
4429                         case Msg.WM_KEYDOWN:
4430                         case Msg.WM_KEYUP:
4431                         case Msg.WM_SYSCHAR:
4432                         case Msg.WM_CHAR: {
4433                                 if (ProcessKeyMessage(ref m)) {
4434                                         m.Result = IntPtr.Zero;
4435                                         return;
4436                                 }
4437                                 DefWndProc (ref m);
4438                                 return;
4439                         }
4440
4441                         case Msg.WM_HELP: {
4442                                 Point   mouse_pos;
4443                                 if (m.LParam != IntPtr.Zero) {
4444                                         HELPINFO        hi;
4445
4446                                         hi = new HELPINFO();
4447
4448                                         hi = (HELPINFO) Marshal.PtrToStructure (m.LParam, typeof (HELPINFO));
4449                                         mouse_pos = new Point(hi.MousePos.x, hi.MousePos.y);
4450                                 } else {
4451                                         mouse_pos = Control.MousePosition;
4452                                 }
4453                                 OnHelpRequested(new HelpEventArgs(mouse_pos));
4454                                 m.Result = (IntPtr)1;
4455                                 return;
4456                         }
4457
4458                         case Msg.WM_KILLFOCUS: {
4459                                 this.has_focus = false;
4460                                 OnLostFocusInternal (EventArgs.Empty);
4461                                 return;
4462                         }
4463
4464                         case Msg.WM_SETFOCUS: {
4465                                 if (!has_focus) {
4466                                         this.has_focus = true;
4467                                         OnGotFocusInternal (EventArgs.Empty);
4468                                 }
4469                                 return;
4470                         }
4471                                         
4472                         case Msg.WM_SYSCOLORCHANGE: {
4473                                 ThemeEngine.Current.ResetDefaults();
4474                                 OnSystemColorsChanged(EventArgs.Empty);
4475                                 return;
4476                         }
4477
4478                         case Msg.WM_SETCURSOR: {
4479                                 if ((cursor == null) || ((HitTest)(m.LParam.ToInt32() & 0xffff) != HitTest.HTCLIENT)) {
4480                                         DefWndProc(ref m);
4481                                         return;
4482                                 }
4483
4484                                 XplatUI.SetCursor(window.Handle, cursor.handle);
4485                                 m.Result = (IntPtr)1;
4486
4487                                 return;
4488                         }
4489
4490                         default:
4491                                 DefWndProc(ref m);
4492                                 return;
4493                         }
4494                 }
4495                 #endregion      // Public Instance Methods
4496
4497                 #region OnXXX methods
4498                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4499                 protected virtual void OnBackColorChanged(EventArgs e) {
4500                         EventHandler eh = (EventHandler)(Events [BackColorChangedEvent]);
4501                         if (eh != null)
4502                                 eh (this, e);
4503                         for (int i=0; i<child_controls.Count; i++) child_controls[i].OnParentBackColorChanged(e);
4504                 }
4505
4506                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4507                 protected virtual void OnBackgroundImageChanged(EventArgs e) {
4508                         EventHandler eh = (EventHandler)(Events [BackgroundImageChangedEvent]);
4509                         if (eh != null)
4510                                 eh (this, e);
4511                         for (int i=0; i<child_controls.Count; i++) child_controls[i].OnParentBackgroundImageChanged(e);
4512                 }
4513
4514                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4515                 protected virtual void OnBindingContextChanged(EventArgs e) {
4516                         CheckDataBindings ();
4517                         EventHandler eh = (EventHandler)(Events [BindingContextChangedEvent]);
4518                         if (eh != null)
4519                                 eh (this, e);
4520                         for (int i=0; i<child_controls.Count; i++) child_controls[i].OnParentBindingContextChanged(e);
4521                 }
4522
4523                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4524                 protected virtual void OnCausesValidationChanged(EventArgs e) {
4525                         EventHandler eh = (EventHandler)(Events [CausesValidationChangedEvent]);
4526                         if (eh != null)
4527                                 eh (this, e);
4528                 }
4529
4530                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4531                 protected virtual void OnChangeUICues(UICuesEventArgs e) {
4532                         UICuesEventHandler eh = (UICuesEventHandler)(Events [ChangeUICuesEvent]);
4533                         if (eh != null)
4534                                 eh (this, e);
4535                 }
4536
4537                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4538                 protected virtual void OnClick(EventArgs e) {
4539                         EventHandler eh = (EventHandler)(Events [ClickEvent]);
4540                         if (eh != null)
4541                                 eh (this, e);
4542                 }
4543
4544                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4545                 protected virtual void OnContextMenuChanged(EventArgs e) {
4546                         EventHandler eh = (EventHandler)(Events [ContextMenuChangedEvent]);
4547                         if (eh != null)
4548                                 eh (this, e);
4549                 }
4550
4551                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4552                 protected virtual void OnControlAdded(ControlEventArgs e) {
4553                         ControlEventHandler eh = (ControlEventHandler)(Events [ControlAddedEvent]);
4554                         if (eh != null)
4555                                 eh (this, e);
4556                 }
4557
4558                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4559                 protected virtual void OnControlRemoved(ControlEventArgs e) {
4560                         ControlEventHandler eh = (ControlEventHandler)(Events [ControlRemovedEvent]);
4561                         if (eh != null)
4562                                 eh (this, e);
4563                 }
4564
4565                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4566                 protected virtual void OnCreateControl() {
4567                         // Override me!
4568                 }
4569
4570                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4571                 protected virtual void OnCursorChanged(EventArgs e) {
4572                         EventHandler eh = (EventHandler)(Events [CursorChangedEvent]);
4573                         if (eh != null)
4574                                 eh (this, e);
4575                 }
4576
4577                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4578                 protected virtual void OnDockChanged(EventArgs e) {
4579                         EventHandler eh = (EventHandler)(Events [DockChangedEvent]);
4580                         if (eh != null)
4581                                 eh (this, e);
4582                 }
4583
4584                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4585                 protected virtual void OnDoubleClick(EventArgs e) {
4586                         EventHandler eh = (EventHandler)(Events [DoubleClickEvent]);
4587                         if (eh != null)
4588                                 eh (this, e);
4589                 }
4590
4591                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4592                 protected virtual void OnDragDrop(DragEventArgs drgevent) {
4593                         DragEventHandler eh = (DragEventHandler)(Events [DragDropEvent]);
4594                         if (eh != null)
4595                                 eh (this, drgevent);
4596                 }
4597
4598                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4599                 protected virtual void OnDragEnter(DragEventArgs drgevent) {
4600                         DragEventHandler eh = (DragEventHandler)(Events [DragEnterEvent]);
4601                         if (eh != null)
4602                                 eh (this, drgevent);
4603                 }
4604
4605                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4606                 protected virtual void OnDragLeave(EventArgs e) {
4607                         EventHandler eh = (EventHandler)(Events [DragLeaveEvent]);
4608                         if (eh != null)
4609                                 eh (this, e);
4610                 }
4611
4612                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4613                 protected virtual void OnDragOver(DragEventArgs drgevent) {
4614                         DragEventHandler eh = (DragEventHandler)(Events [DragOverEvent]);
4615                         if (eh != null)
4616                                 eh (this, drgevent);
4617                 }
4618
4619                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4620                 protected virtual void OnEnabledChanged(EventArgs e) {
4621                         if (IsHandleCreated) {
4622                                 if (this is Form) {
4623                                         if (((Form)this).context == null) {
4624                                                 XplatUI.EnableWindow(window.Handle, Enabled);
4625                                         }
4626                                 } else {
4627                                         XplatUI.EnableWindow(window.Handle, Enabled);
4628                                 }
4629                                 Refresh();
4630                         }
4631
4632                         EventHandler eh = (EventHandler)(Events [EnabledChangedEvent]);
4633                         if (eh != null)
4634                                 eh (this, e);
4635
4636                         for (int i=0; i<child_controls.Count; i++) {
4637                                 child_controls[i].OnParentEnabledChanged(e);
4638                         }
4639                 }
4640
4641                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4642                 protected virtual void OnEnter(EventArgs e) {
4643                         EventHandler eh = (EventHandler)(Events [EnterEvent]);
4644                         if (eh != null)
4645                                 eh (this, e);
4646                 }
4647
4648                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4649                 protected virtual void OnFontChanged(EventArgs e) {
4650                         EventHandler eh = (EventHandler)(Events [FontChangedEvent]);
4651                         if (eh != null)
4652                                 eh (this, e);
4653                         for (int i=0; i<child_controls.Count; i++) child_controls[i].OnParentFontChanged(e);
4654                 }
4655
4656                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4657                 protected virtual void OnForeColorChanged(EventArgs e) {
4658                         EventHandler eh = (EventHandler)(Events [ForeColorChangedEvent]);
4659                         if (eh != null)
4660                                 eh (this, e);
4661                         for (int i=0; i<child_controls.Count; i++) child_controls[i].OnParentForeColorChanged(e);
4662                 }
4663
4664                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4665                 protected virtual void OnGiveFeedback(GiveFeedbackEventArgs gfbevent) {
4666                         GiveFeedbackEventHandler eh = (GiveFeedbackEventHandler)(Events [GiveFeedbackEvent]);
4667                         if (eh != null)
4668                                 eh (this, gfbevent);
4669                 }
4670                 
4671                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4672                 protected virtual void OnGotFocus(EventArgs e) {
4673                         EventHandler eh = (EventHandler)(Events [GotFocusEvent]);
4674                         if (eh != null)
4675                                 eh (this, e);
4676                 }
4677
4678                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4679                 protected virtual void OnHandleCreated(EventArgs e) {
4680                         EventHandler eh = (EventHandler)(Events [HandleCreatedEvent]);
4681                         if (eh != null)
4682                                 eh (this, e);
4683                 }
4684
4685                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4686                 protected virtual void OnHandleDestroyed(EventArgs e) {
4687                         EventHandler eh = (EventHandler)(Events [HandleDestroyedEvent]);
4688                         if (eh != null)
4689                                 eh (this, e);
4690                 }
4691
4692                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4693                 protected virtual void OnHelpRequested(HelpEventArgs hevent) {
4694                         HelpEventHandler eh = (HelpEventHandler)(Events [HelpRequestedEvent]);
4695                         if (eh != null)
4696                                 eh (this, hevent);
4697                 }
4698
4699                 protected virtual void OnImeModeChanged(EventArgs e) {
4700                         EventHandler eh = (EventHandler)(Events [ImeModeChangedEvent]);
4701                         if (eh != null)
4702                                 eh (this, e);
4703                 }
4704
4705                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4706                 protected virtual void OnInvalidated(InvalidateEventArgs e) {
4707                         if (ThemeEngine.Current.DoubleBufferingSupported)
4708                                 if ((control_style & ControlStyles.DoubleBuffer) != 0) {
4709                                         // should this block be here?  seems like it
4710                                         // would be more at home in
4711                                         // NotifyInvalidated..
4712                                         if (e.InvalidRect == ClientRectangle) {
4713                                                 InvalidateBackBuffer ();
4714                                         }
4715                                         else {
4716                                                 // we need this Inflate call here so
4717                                                 // that the border of the rectangle is
4718                                                 // considered Visible (the
4719                                                 // invalid_region.IsVisible call) in
4720                                                 // the WM_PAINT handling below.
4721                                                 Rectangle r = Rectangle.Inflate(e.InvalidRect, 1,1);
4722                                                 if (invalid_region == null)
4723                                                         invalid_region = new Region (r);
4724                                                 else
4725                                                         invalid_region.Union (r);
4726                                         }
4727                                 }
4728
4729                         InvalidateEventHandler eh = (InvalidateEventHandler)(Events [InvalidatedEvent]);
4730                         if (eh != null)
4731                                 eh (this, e);
4732                 }
4733
4734                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4735                 protected virtual void OnKeyDown(KeyEventArgs e) {
4736                         KeyEventHandler eh = (KeyEventHandler)(Events [KeyDownEvent]);
4737                         if (eh != null)
4738                                 eh (this, e);
4739                 }
4740
4741                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4742                 protected virtual void OnKeyPress(KeyPressEventArgs e) {
4743                         KeyPressEventHandler eh = (KeyPressEventHandler)(Events [KeyPressEvent]);
4744                         if (eh != null)
4745                                 eh (this, e);
4746                 }
4747
4748                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4749                 protected virtual void OnKeyUp(KeyEventArgs e) {
4750                         KeyEventHandler eh = (KeyEventHandler)(Events [KeyUpEvent]);
4751                         if (eh != null)
4752                                 eh (this, e);
4753                 }
4754
4755                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4756                 protected virtual void OnLayout(LayoutEventArgs levent) {
4757                         LayoutEventHandler eh = (LayoutEventHandler)(Events [LayoutEvent]);
4758                         if (eh != null)
4759                                 eh (this, levent);
4760                 }
4761
4762                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4763                 protected virtual void OnLeave(EventArgs e) {
4764                         EventHandler eh = (EventHandler)(Events [LeaveEvent]);
4765                         if (eh != null)
4766                                 eh (this, e);
4767                 }
4768
4769                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4770                 protected virtual void OnLocationChanged(EventArgs e) {
4771                         OnMove(e);
4772                         EventHandler eh = (EventHandler)(Events [LocationChangedEvent]);
4773                         if (eh != null)
4774                                 eh (this, e);
4775                 }
4776
4777                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4778                 protected virtual void OnLostFocus(EventArgs e) {
4779                         EventHandler eh = (EventHandler)(Events [LostFocusEvent]);
4780                         if (eh != null)
4781                                 eh (this, e);
4782                 }
4783
4784                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4785                 protected virtual void OnMouseDown(MouseEventArgs e) {
4786                         MouseEventHandler eh = (MouseEventHandler)(Events [MouseDownEvent]);
4787                         if (eh != null)
4788                                 eh (this, e);
4789                 }
4790
4791                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4792                 protected virtual void OnMouseEnter(EventArgs e) {
4793                         EventHandler eh = (EventHandler)(Events [MouseEnterEvent]);
4794                         if (eh != null)
4795                                 eh (this, e);
4796                 }
4797
4798                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4799                 protected virtual void OnMouseHover(EventArgs e) {
4800                         EventHandler eh = (EventHandler)(Events [MouseHoverEvent]);
4801                         if (eh != null)
4802                                 eh (this, e);
4803                 }
4804
4805                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4806                 protected virtual void OnMouseLeave(EventArgs e) {
4807                         EventHandler eh = (EventHandler)(Events [MouseLeaveEvent]);
4808                         if (eh != null)
4809                                 eh (this, e);
4810                 }
4811
4812                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4813                 protected virtual void OnMouseMove(MouseEventArgs e) {
4814                         MouseEventHandler eh = (MouseEventHandler)(Events [MouseMoveEvent]);
4815                         if (eh != null)
4816                                 eh (this, e);
4817                 }
4818
4819                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4820                 protected virtual void OnMouseUp(MouseEventArgs e) {
4821                         MouseEventHandler eh = (MouseEventHandler)(Events [MouseUpEvent]);
4822                         if (eh != null)
4823                                 eh (this, e);
4824                 }
4825
4826                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4827                 protected virtual void OnMouseWheel(MouseEventArgs e) {
4828                         MouseEventHandler eh = (MouseEventHandler)(Events [MouseWheelEvent]);
4829                         if (eh != null)
4830                                 eh (this, e);
4831                 }
4832
4833                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4834                 protected virtual void OnMove(EventArgs e) {
4835                         EventHandler eh = (EventHandler)(Events [MoveEvent]);
4836                         if (eh != null)
4837                                 eh (this, e);
4838                 }
4839
4840                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4841                 protected virtual void OnNotifyMessage(Message m) {
4842                         // Override me!
4843                 }
4844
4845 #if NET_2_0
4846                 protected virtual void OnPaddingChanged (EventArgs e) {
4847                         EventHandler eh = (EventHandler) (Events [PaddingChangedEvent]);
4848                         if (eh != null)
4849                                 eh (this, e);
4850                 }
4851 #endif
4852
4853                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4854                 protected virtual void OnPaint(PaintEventArgs e) {
4855                         PaintEventHandler eh = (PaintEventHandler)(Events [PaintEvent]);
4856                         if (eh != null)
4857                                 eh (this, e);
4858                 }
4859
4860                 internal virtual void OnPaintBackgroundInternal(PaintEventArgs e) {
4861                         // Override me
4862                 }
4863
4864                 internal virtual void OnPaintInternal(PaintEventArgs e) {
4865                         // Override me
4866                 }
4867
4868                 internal virtual void OnGotFocusInternal (EventArgs e)
4869                 {
4870                         OnGotFocus (e);
4871                 }
4872
4873                 internal virtual void OnLostFocusInternal (EventArgs e)
4874                 {
4875                         OnLostFocus (e);
4876                 }
4877
4878                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4879                 protected virtual void OnPaintBackground(PaintEventArgs pevent) {
4880                         PaintControlBackground (pevent);
4881                 }
4882
4883                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4884                 protected virtual void OnParentBackColorChanged(EventArgs e) {
4885                         if (background_color.IsEmpty && background_image==null) {
4886                                 Invalidate();
4887                                 OnBackColorChanged(e);
4888                         }
4889                 }
4890
4891                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4892                 protected virtual void OnParentBackgroundImageChanged(EventArgs e) {
4893                         if (background_color.IsEmpty && background_image==null) {
4894                                 Invalidate();
4895                                 OnBackgroundImageChanged(e);
4896                         }
4897                 }
4898
4899                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4900                 protected virtual void OnParentBindingContextChanged(EventArgs e) {
4901                         if (binding_context==null) {
4902                                 binding_context=Parent.binding_context;
4903                                 OnBindingContextChanged(e);
4904                         }
4905                 }
4906
4907                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4908                 protected virtual void OnParentChanged(EventArgs e) {
4909                         EventHandler eh = (EventHandler)(Events [ParentChangedEvent]);
4910                         if (eh != null)
4911                                 eh (this, e);
4912                 }
4913
4914                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4915                 protected virtual void OnParentEnabledChanged(EventArgs e) {
4916                         if (is_enabled) {
4917                                 OnEnabledChanged(e);
4918                         }
4919                 }
4920
4921                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4922                 protected virtual void OnParentFontChanged(EventArgs e) {
4923                         if (font==null) {
4924                                 Invalidate();
4925                                 OnFontChanged(e);
4926                         }
4927                 }
4928
4929                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4930                 protected virtual void OnParentForeColorChanged(EventArgs e) {
4931                         if (foreground_color.IsEmpty) {
4932                                 Invalidate();
4933                                 OnForeColorChanged(e);
4934                         }
4935                 }
4936
4937                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4938                 protected virtual void OnParentRightToLeftChanged(EventArgs e) {
4939                         if (right_to_left==RightToLeft.Inherit) {
4940                                 Invalidate();
4941                                 OnRightToLeftChanged(e);
4942                         }
4943                 }
4944
4945                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4946                 protected virtual void OnParentVisibleChanged(EventArgs e) {
4947                         if (is_visible) {
4948                                 OnVisibleChanged(e);
4949                         }
4950                 }
4951
4952                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4953                 protected virtual void OnQueryContinueDrag(QueryContinueDragEventArgs e) {
4954                         QueryContinueDragEventHandler eh = (QueryContinueDragEventHandler)(Events [QueryContinueDragEvent]);
4955                         if (eh != null)
4956                                 eh (this, e);
4957                 }
4958
4959                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4960                 protected virtual void OnResize(EventArgs e) {
4961                         EventHandler eh = (EventHandler)(Events [ResizeEvent]);
4962                         if (eh != null)
4963                                 eh (this, e);
4964
4965                         PerformLayout(this, "bounds");
4966
4967                         if (parent != null) {
4968                                 parent.PerformLayout();
4969                         }
4970                 }
4971
4972                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4973                 protected virtual void OnRightToLeftChanged(EventArgs e) {
4974                         EventHandler eh = (EventHandler)(Events [RightToLeftChangedEvent]);
4975                         if (eh != null)
4976                                 eh (this, e);
4977                         for (int i=0; i<child_controls.Count; i++) child_controls[i].OnParentRightToLeftChanged(e);
4978                 }
4979
4980                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4981                 protected virtual void OnSizeChanged(EventArgs e) {
4982                         DisposeBackBuffer ();
4983                         OnResize(e);
4984                         EventHandler eh = (EventHandler)(Events [SizeChangedEvent]);
4985                         if (eh != null)
4986                                 eh (this, e);
4987                 }
4988
4989                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4990                 protected virtual void OnStyleChanged(EventArgs e) {
4991                         EventHandler eh = (EventHandler)(Events [StyleChangedEvent]);
4992                         if (eh != null)
4993                                 eh (this, e);
4994                 }
4995
4996                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4997                 protected virtual void OnSystemColorsChanged(EventArgs e) {
4998                         EventHandler eh = (EventHandler)(Events [SystemColorsChangedEvent]);
4999                         if (eh != null)
5000                                 eh (this, e);
5001                 }
5002
5003                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5004                 protected virtual void OnTabIndexChanged(EventArgs e) {
5005                         EventHandler eh = (EventHandler)(Events [TabIndexChangedEvent]);
5006                         if (eh != null)
5007                                 eh (this, e);
5008                 }
5009
5010                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5011                 protected virtual void OnTabStopChanged(EventArgs e) {
5012                         EventHandler eh = (EventHandler)(Events [TabStopChangedEvent]);
5013                         if (eh != null)
5014                                 eh (this, e);
5015                 }
5016
5017                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5018                 protected virtual void OnTextChanged(EventArgs e) {
5019                         EventHandler eh = (EventHandler)(Events [TextChangedEvent]);
5020                         if (eh != null)
5021                                 eh (this, e);
5022                 }
5023
5024                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5025                 protected virtual void OnValidated(EventArgs e) {
5026                         EventHandler eh = (EventHandler)(Events [ValidatedEvent]);
5027                         if (eh != null)
5028                                 eh (this, e);
5029                 }
5030
5031                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5032                 protected virtual void OnValidating(System.ComponentModel.CancelEventArgs e) {
5033                         CancelEventHandler eh = (CancelEventHandler)(Events [ValidatingEvent]);
5034                         if (eh != null)
5035                                 eh (this, e);
5036                 }
5037
5038                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5039                 protected virtual void OnVisibleChanged(EventArgs e) {
5040                         if ((parent != null) && !Created && Visible) {
5041                                 if (!is_disposed) {
5042                                         CreateControl();
5043                                         PerformLayout();
5044                                 }
5045                         }
5046
5047                         EventHandler eh = (EventHandler)(Events [VisibleChangedEvent]);
5048                         if (eh != null)
5049                                 eh (this, e);
5050
5051                         // We need to tell our kids
5052                         for (int i=0; i<child_controls.Count; i++) {
5053                                 if (child_controls[i].Visible) {
5054                                         child_controls[i].OnParentVisibleChanged(e);
5055                                 }
5056                         }
5057                 }
5058                 #endregion      // OnXXX methods
5059
5060                 #region Events
5061                 static object BackColorChangedEvent = new object ();
5062                 static object BackgroundImageChangedEvent = new object ();
5063 #if NET_2_0
5064                 static object BackgroundImageLayoutChangedEvent = new object ();
5065 #endif
5066                 static object BindingContextChangedEvent = new object ();
5067                 static object CausesValidationChangedEvent = new object ();
5068                 static object ChangeUICuesEvent = new object ();
5069                 static object ClickEvent = new object ();
5070                 static object ContextMenuChangedEvent = new object ();
5071                 static object ControlAddedEvent = new object ();
5072                 static object ControlRemovedEvent = new object ();
5073                 static object CursorChangedEvent = new object ();
5074                 static object DockChangedEvent = new object ();
5075                 static object DoubleClickEvent = new object ();
5076                 static object DragDropEvent = new object ();
5077                 static object DragEnterEvent = new object ();
5078                 static object DragLeaveEvent = new object ();
5079                 static object DragOverEvent = new object ();
5080                 static object EnabledChangedEvent = new object ();
5081                 static object EnterEvent = new object ();
5082                 static object FontChangedEvent = new object ();
5083                 static object ForeColorChangedEvent = new object ();
5084                 static object GiveFeedbackEvent = new object ();
5085                 static object GotFocusEvent = new object ();
5086                 static object HandleCreatedEvent = new object ();
5087                 static object HandleDestroyedEvent = new object ();
5088                 static object HelpRequestedEvent = new object ();
5089                 static object ImeModeChangedEvent = new object ();
5090                 static object InvalidatedEvent = new object ();
5091                 static object KeyDownEvent = new object ();
5092                 static object KeyPressEvent = new object ();
5093                 static object KeyUpEvent = new object ();
5094                 static object LayoutEvent = new object ();
5095                 static object LeaveEvent = new object ();
5096                 static object LocationChangedEvent = new object ();
5097                 static object LostFocusEvent = new object ();
5098 #if NET_2_0
5099                 static object MouseClickEvent = new object ();
5100                 static object MouseDoubleClickEvent = new object ();
5101 #endif
5102                 static object MouseDownEvent = new object ();
5103                 static object MouseEnterEvent = new object ();
5104                 static object MouseHoverEvent = new object ();
5105                 static object MouseLeaveEvent = new object ();
5106                 static object MouseMoveEvent = new object ();
5107                 static object MouseUpEvent = new object ();
5108                 static object MouseWheelEvent = new object ();
5109                 static object MoveEvent = new object ();
5110 #if NET_2_0
5111                 static object PaddingChangedEvent = new object ();
5112 #endif
5113                 static object PaintEvent = new object ();
5114                 static object ParentChangedEvent = new object ();
5115                 static object QueryAccessibilityHelpEvent = new object ();
5116                 static object QueryContinueDragEvent = new object ();
5117                 static object ResizeEvent = new object ();
5118                 static object RightToLeftChangedEvent = new object ();
5119                 static object SizeChangedEvent = new object ();
5120                 static object StyleChangedEvent = new object ();
5121                 static object SystemColorsChangedEvent = new object ();
5122                 static object TabIndexChangedEvent = new object ();
5123                 static object TabStopChangedEvent = new object ();
5124                 static object TextChangedEvent = new object ();
5125                 static object ValidatedEvent = new object ();
5126                 static object ValidatingEvent = new object ();
5127                 static object VisibleChangedEvent = new object ();
5128
5129                 public event EventHandler BackColorChanged {
5130                         add { Events.AddHandler (BackColorChangedEvent, value); }
5131                         remove { Events.RemoveHandler (BackColorChangedEvent, value); }
5132                 }
5133
5134                 public event EventHandler BackgroundImageChanged {
5135                         add { Events.AddHandler (BackgroundImageChangedEvent, value); }
5136                         remove { Events.RemoveHandler (BackgroundImageChangedEvent, value); }
5137                 }
5138
5139 #if NET_2_0     
5140                 public event EventHandler BackgroundImageLayoutChanged {
5141                         add {Events.AddHandler (BackgroundImageLayoutChangedEvent, value);}
5142                         remove {Events.RemoveHandler (BackgroundImageLayoutChangedEvent, value);}
5143                 }
5144 #endif
5145
5146                 public event EventHandler BindingContextChanged {
5147                         add { Events.AddHandler (BindingContextChangedEvent, value); }
5148                         remove { Events.RemoveHandler (BindingContextChangedEvent, value); }
5149                 }
5150
5151                 public event EventHandler CausesValidationChanged {
5152                         add { Events.AddHandler (CausesValidationChangedEvent, value); }
5153                         remove { Events.RemoveHandler (CausesValidationChangedEvent, value); }
5154                 }
5155
5156                 public event UICuesEventHandler ChangeUICues {
5157                         add { Events.AddHandler (ChangeUICuesEvent, value); }
5158                         remove { Events.RemoveHandler (ChangeUICuesEvent, value); }
5159                 }
5160
5161                 public event EventHandler Click {
5162                         add { Events.AddHandler (ClickEvent, value); }
5163                         remove { Events.RemoveHandler (ClickEvent, value); }
5164                 }
5165 #if NET_2_0
5166                 [Browsable (false)]
5167 #endif
5168                 public event EventHandler ContextMenuChanged {
5169                         add { Events.AddHandler (ContextMenuChangedEvent, value); }
5170                         remove { Events.RemoveHandler (ContextMenuChangedEvent, value); }
5171                 }
5172
5173                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5174 #if NET_2_0
5175                 [Browsable(true)]
5176 #else 
5177                 [Browsable(false)]
5178 #endif
5179                 public event ControlEventHandler ControlAdded {
5180                         add { Events.AddHandler (ControlAddedEvent, value); }
5181                         remove { Events.RemoveHandler (ControlAddedEvent, value); }
5182                 }
5183
5184                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5185 #if NET_2_0
5186                 [Browsable(true)]
5187 #else 
5188                 [Browsable(false)]
5189 #endif
5190                 public event ControlEventHandler ControlRemoved {
5191                         add { Events.AddHandler (ControlRemovedEvent, value); }
5192                         remove { Events.RemoveHandler (ControlRemovedEvent, value); }
5193                 }
5194
5195                 [MWFDescription("Fired when the cursor for the control has been changed"), MWFCategory("PropertyChanged")]
5196                 public event EventHandler CursorChanged {
5197                         add { Events.AddHandler (CursorChangedEvent, value); }
5198                         remove { Events.RemoveHandler (CursorChangedEvent, value); }
5199                 }
5200                 public event EventHandler DockChanged {
5201                         add { Events.AddHandler (DockChangedEvent, value); }
5202                         remove { Events.RemoveHandler (DockChangedEvent, value); }
5203                 }
5204
5205                 public event EventHandler DoubleClick {
5206                         add { Events.AddHandler (DoubleClickEvent, value); }
5207                         remove { Events.RemoveHandler (DoubleClickEvent, value); }
5208                 }
5209
5210                 public event DragEventHandler DragDrop {
5211                         add { Events.AddHandler (DragDropEvent, value); }
5212                         remove { Events.RemoveHandler (DragDropEvent, value); }
5213                 }
5214
5215                 public event DragEventHandler DragEnter {
5216                         add { Events.AddHandler (DragEnterEvent, value); }
5217                         remove { Events.RemoveHandler (DragEnterEvent, value); }
5218                 }
5219
5220                 public event EventHandler DragLeave {
5221                         add { Events.AddHandler (DragLeaveEvent, value); }
5222                         remove { Events.RemoveHandler (DragLeaveEvent, value); }
5223                 }
5224
5225                 public event DragEventHandler DragOver {
5226                         add { Events.AddHandler (DragOverEvent, value); }
5227                         remove { Events.RemoveHandler (DragOverEvent, value); }
5228                 }
5229
5230                 public event EventHandler EnabledChanged {
5231                         add { Events.AddHandler (EnabledChangedEvent, value); }
5232                         remove { Events.RemoveHandler (EnabledChangedEvent, value); }
5233                 }
5234
5235                 public event EventHandler Enter {
5236                         add { Events.AddHandler (EnterEvent, value); }
5237                         remove { Events.RemoveHandler (EnterEvent, value); }
5238                 }
5239
5240                 public event EventHandler FontChanged {
5241                         add { Events.AddHandler (FontChangedEvent, value); }
5242                         remove { Events.RemoveHandler (FontChangedEvent, value); }
5243                 }
5244
5245                 public event EventHandler ForeColorChanged {
5246                         add { Events.AddHandler (ForeColorChangedEvent, value); }
5247                         remove { Events.RemoveHandler (ForeColorChangedEvent, value); }
5248                 }
5249
5250                 public event GiveFeedbackEventHandler GiveFeedback {
5251                         add { Events.AddHandler (GiveFeedbackEvent, value); }
5252                         remove { Events.RemoveHandler (GiveFeedbackEvent, value); }
5253                 }
5254
5255                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5256                 [Browsable(false)]
5257                 public event EventHandler GotFocus {
5258                         add { Events.AddHandler (GotFocusEvent, value); }
5259                         remove { Events.RemoveHandler (GotFocusEvent, value); }
5260                 }
5261
5262
5263                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5264                 [Browsable(false)]
5265                 public event EventHandler HandleCreated {
5266                         add { Events.AddHandler (HandleCreatedEvent, value); }
5267                         remove { Events.RemoveHandler (HandleCreatedEvent, value); }
5268                 }
5269
5270                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5271                 [Browsable(false)]
5272                 public event EventHandler HandleDestroyed {
5273                         add { Events.AddHandler (HandleDestroyedEvent, value); }
5274                         remove { Events.RemoveHandler (HandleDestroyedEvent, value); }
5275                 }
5276
5277                 public event HelpEventHandler HelpRequested {
5278                         add { Events.AddHandler (HelpRequestedEvent, value); }
5279                         remove { Events.RemoveHandler (HelpRequestedEvent, value); }
5280                 }
5281
5282                 public event EventHandler ImeModeChanged {
5283                         add { Events.AddHandler (ImeModeChangedEvent, value); }
5284                         remove { Events.RemoveHandler (ImeModeChangedEvent, value); }
5285                 }
5286
5287                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5288                 [Browsable(false)]
5289                 public event InvalidateEventHandler Invalidated {
5290                         add { Events.AddHandler (InvalidatedEvent, value); }
5291                         remove { Events.RemoveHandler (InvalidatedEvent, value); }
5292                 }
5293
5294                 public event KeyEventHandler KeyDown {
5295                         add { Events.AddHandler (KeyDownEvent, value); }
5296                         remove { Events.RemoveHandler (KeyDownEvent, value); }
5297                 }
5298
5299                 public event KeyPressEventHandler KeyPress {
5300                         add { Events.AddHandler (KeyPressEvent, value); }
5301                         remove { Events.RemoveHandler (KeyPressEvent, value); }
5302                 }
5303
5304                 public event KeyEventHandler KeyUp {
5305                         add { Events.AddHandler (KeyUpEvent, value); }
5306                         remove { Events.RemoveHandler (KeyUpEvent, value); }
5307                 }
5308
5309                 public event LayoutEventHandler Layout {
5310                         add { Events.AddHandler (LayoutEvent, value); }
5311                         remove { Events.RemoveHandler (LayoutEvent, value); }
5312                 }
5313
5314                 public event EventHandler Leave {
5315                         add { Events.AddHandler (LeaveEvent, value); }
5316                         remove { Events.RemoveHandler (LeaveEvent, value); }
5317                 }
5318
5319                 public event EventHandler LocationChanged {
5320                         add { Events.AddHandler (LocationChangedEvent, value); }
5321                         remove { Events.RemoveHandler (LocationChangedEvent, value); }
5322                 }
5323
5324                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5325                 [Browsable(false)]
5326                 public event EventHandler LostFocus {
5327                         add { Events.AddHandler (LostFocusEvent, value); }
5328                         remove { Events.RemoveHandler (LostFocusEvent, value); }
5329                 }
5330
5331 #if NET_2_0
5332                 public event MouseEventHandler MouseClick
5333                 {
5334                         add { Events.AddHandler (MouseClickEvent, value); }
5335                         remove { Events.RemoveHandler (MouseClickEvent, value); }
5336                 }
5337                 public event MouseEventHandler MouseDoubleClick
5338                 {
5339                         add { Events.AddHandler (MouseDoubleClickEvent, value); }
5340                         remove { Events.RemoveHandler (MouseDoubleClickEvent, value); }
5341                 }
5342 #endif
5343                 public event MouseEventHandler MouseDown {
5344                         add { Events.AddHandler (MouseDownEvent, value); }
5345                         remove { Events.RemoveHandler (MouseDownEvent, value); }
5346                 }
5347
5348                 public event EventHandler MouseEnter {
5349                         add { Events.AddHandler (MouseEnterEvent, value); }
5350                         remove { Events.RemoveHandler (MouseEnterEvent, value); }
5351                 }
5352
5353                 public event EventHandler MouseHover {
5354                         add { Events.AddHandler (MouseHoverEvent, value); }
5355                         remove { Events.RemoveHandler (MouseHoverEvent, value); }
5356                 }
5357
5358                 public event EventHandler MouseLeave {
5359                         add { Events.AddHandler (MouseLeaveEvent, value); }
5360                         remove { Events.RemoveHandler (MouseLeaveEvent, value); }
5361                 }
5362
5363                 public event MouseEventHandler MouseMove {
5364                         add { Events.AddHandler (MouseMoveEvent, value); }
5365                         remove { Events.RemoveHandler (MouseMoveEvent, value); }
5366                 }
5367
5368                 public event MouseEventHandler MouseUp {
5369                         add { Events.AddHandler (MouseUpEvent, value); }
5370                         remove { Events.RemoveHandler (MouseUpEvent, value); }
5371                 }
5372
5373                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5374                 [Browsable(false)]
5375                 public event MouseEventHandler MouseWheel {
5376                         add { Events.AddHandler (MouseWheelEvent, value); }
5377                         remove { Events.RemoveHandler (MouseWheelEvent, value); }
5378                 }
5379
5380                 public event EventHandler Move {
5381                         add { Events.AddHandler (MoveEvent, value); }
5382                         remove { Events.RemoveHandler (MoveEvent, value); }
5383                 }
5384 #if NET_2_0
5385                 public event EventHandler PaddingChanged
5386                 {
5387                         add { Events.AddHandler (PaddingChangedEvent, value); }
5388                         remove { Events.RemoveHandler (PaddingChangedEvent, value); }
5389                 }
5390 #endif
5391                 public event PaintEventHandler Paint {
5392                         add { Events.AddHandler (PaintEvent, value); }
5393                         remove { Events.RemoveHandler (PaintEvent, value); }
5394                 }
5395
5396                 public event EventHandler ParentChanged {
5397                         add { Events.AddHandler (ParentChangedEvent, value); }
5398                         remove { Events.RemoveHandler (ParentChangedEvent, value); }
5399                 }
5400
5401                 public event QueryAccessibilityHelpEventHandler QueryAccessibilityHelp {
5402                         add { Events.AddHandler (QueryAccessibilityHelpEvent, value); }
5403                         remove { Events.RemoveHandler (QueryAccessibilityHelpEvent, value); }
5404                 }
5405
5406                 public event QueryContinueDragEventHandler QueryContinueDrag {
5407                         add { Events.AddHandler (QueryContinueDragEvent, value); }
5408                         remove { Events.RemoveHandler (QueryContinueDragEvent, value); }
5409                 }
5410
5411 #if NET_2_0     
5412                 [EditorBrowsable (EditorBrowsableState.Advanced)]
5413 #endif
5414                 public event EventHandler Resize {
5415                         add { Events.AddHandler (ResizeEvent, value); }
5416                         remove { Events.RemoveHandler (ResizeEvent, value); }
5417                 }
5418
5419                 public event EventHandler RightToLeftChanged {
5420                         add { Events.AddHandler (RightToLeftChangedEvent, value); }
5421                         remove { Events.RemoveHandler (RightToLeftChangedEvent, value); }
5422                 }
5423
5424                 public event EventHandler SizeChanged {
5425                         add { Events.AddHandler (SizeChangedEvent, value); }
5426                         remove { Events.RemoveHandler (SizeChangedEvent, value); }
5427                 }
5428
5429                 public event EventHandler StyleChanged {
5430                         add { Events.AddHandler (StyleChangedEvent, value); }
5431                         remove { Events.RemoveHandler (StyleChangedEvent, value); }
5432                 }
5433
5434                 public event EventHandler SystemColorsChanged {
5435                         add { Events.AddHandler (SystemColorsChangedEvent, value); }
5436                         remove { Events.RemoveHandler (SystemColorsChangedEvent, value); }
5437                 }
5438
5439                 public event EventHandler TabIndexChanged {
5440                         add { Events.AddHandler (TabIndexChangedEvent, value); }
5441                         remove { Events.RemoveHandler (TabIndexChangedEvent, value); }
5442                 }
5443
5444                 public event EventHandler TabStopChanged {
5445                         add { Events.AddHandler (TabStopChangedEvent, value); }
5446                         remove { Events.RemoveHandler (TabStopChangedEvent, value); }
5447                 }
5448
5449                 public event EventHandler TextChanged {
5450                         add { Events.AddHandler (TextChangedEvent, value); }
5451                         remove { Events.RemoveHandler (TextChangedEvent, value); }
5452                 }
5453
5454                 public event EventHandler Validated {
5455                         add { Events.AddHandler (ValidatedEvent, value); }
5456                         remove { Events.RemoveHandler (ValidatedEvent, value); }
5457                 }
5458
5459                 public event CancelEventHandler Validating {
5460                         add { Events.AddHandler (ValidatingEvent, value); }
5461                         remove { Events.RemoveHandler (ValidatingEvent, value); }
5462                 }
5463
5464                 public event EventHandler VisibleChanged {
5465                         add { Events.AddHandler (VisibleChangedEvent, value); }
5466                         remove { Events.RemoveHandler (VisibleChangedEvent, value); }
5467                 }
5468
5469                 #endregion      // Events
5470         }
5471 }