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