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