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