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