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