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