Fix bug #395
[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 #undef DebugRecreate
34 #undef DebugFocus
35 #undef DebugMessages
36
37 using System;
38 using System.ComponentModel;
39 using System.ComponentModel.Design;
40 using System.ComponentModel.Design.Serialization;
41 using System.Collections;
42 using System.Diagnostics;
43 using System.Drawing;
44 using System.Drawing.Drawing2D;
45 using System.Reflection;
46 using System.Runtime.InteropServices;
47 using System.Security;
48 using System.Threading;
49
50 namespace System.Windows.Forms
51 {
52         [ComVisible(true)]
53         [ClassInterface (ClassInterfaceType.AutoDispatch)]
54         [Designer("System.Windows.Forms.Design.ControlDesigner, " + Consts.AssemblySystem_Design, "System.ComponentModel.Design.IDesigner")]
55         [DefaultProperty("Text")]
56         [DefaultEvent("Click")]
57         [DesignerSerializer("System.Windows.Forms.Design.ControlCodeDomSerializer, " + Consts.AssemblySystem_Design, "System.ComponentModel.Design.Serialization.CodeDomSerializer, " + Consts.AssemblySystem_Design)]
58         [ToolboxItemFilter("System.Windows.Forms")]
59         public class Control : Component, ISynchronizeInvoke, IWin32Window
60                 , IBindableComponent, IDropTarget, IBounds
61         {
62                 #region Local Variables
63
64                 // Basic
65                 internal Rectangle              bounds;                 // bounding rectangle for control (client area + decorations)
66                 Rectangle               explicit_bounds; // explicitly set bounds
67                 internal object                 creator_thread;         // thread that created the control
68                 internal                ControlNativeWindow     window;                 // object for native window handle
69                 private                 IWindowTarget window_target;
70                 string                  name; // for object naming
71
72                 // State
73                 bool                    is_created; // true if OnCreateControl has been sent
74                 internal bool           has_focus;              // true if control has focus
75                 internal bool           is_visible;             // true if control is visible
76                 internal bool           is_entered;             // is the mouse inside the control?
77                 internal bool           is_enabled;             // true if control is enabled (usable/not grayed out)
78                 bool                    is_accessible; // true if the control is visible to accessibility applications
79                 bool                    is_captured; // tracks if the control has captured the mouse
80                 internal bool                   is_toplevel;            // tracks if the control is a toplevel window
81                 bool                    is_recreating; // tracks if the handle for the control is being recreated
82                 bool                    causes_validation; // tracks if validation is executed on changes
83                 bool                    is_focusing; // tracks if Focus has been called on the control and has not yet finished
84                 int                     tab_index; // position in tab order of siblings
85                 bool                    tab_stop; // is the control a tab stop?
86                 bool                    is_disposed; // has the window already been disposed?
87                 bool                    is_disposing; // is the window getting disposed?
88                 Size                    client_size; // size of the client area (window excluding decorations)
89                 Rectangle               client_rect; // rectangle with the client area (window excluding decorations)
90                 ControlStyles           control_style; // rather win32-specific, style bits for control
91                 ImeMode                 ime_mode;
92                 object                  control_tag; // object that contains data about our control
93                 internal int                    mouse_clicks;           // Counter for mouse clicks
94                 Cursor                  cursor; // Cursor for the window
95                 internal bool                   allow_drop;             // true if the control accepts droping objects on it   
96                 Region                  clip_region; // User-specified clip region for the window
97
98                 // Visuals
99                 internal Color                  foreground_color;       // foreground color for control
100                 internal Color                  background_color;       // background color for control
101                 Image                   background_image; // background image for control
102                 internal Font                   font;                   // font for control
103                 string                  text; // window/title text for control
104                 internal                BorderStyle             border_style;           // Border style of control
105                 bool                    show_keyboard_cues; // Current keyboard cues 
106                 internal bool           show_focus_cues; // Current focus cues 
107                 internal bool           force_double_buffer;    // Always doublebuffer regardless of ControlStyle
108
109                 // Layout
110                 internal enum LayoutType {
111                         Anchor,
112                         Dock
113                 }
114                 Layout.LayoutEngine layout_engine;
115                 internal int layout_suspended;
116                 bool layout_pending; // true if our parent needs to re-layout us
117                 internal AnchorStyles anchor_style; // anchoring requirements for our control
118                 internal DockStyle dock_style; // docking requirements for our control
119                 LayoutType layout_type;
120                 private bool recalculate_distances = true;  // Delay anchor calculations
121
122                 // Please leave the next 2 as internal until DefaultLayout (2.0) is rewritten
123                 internal int                    dist_right; // distance to the right border of the parent
124                 internal int                    dist_bottom; // distance to the bottom border of the parent
125
126                 // to be categorized...
127                 ControlCollection       child_controls; // our children
128                 Control                 parent; // our parent control
129                 BindingContext          binding_context;
130                 RightToLeft             right_to_left; // drawing direction for control
131                 ContextMenu             context_menu; // Context menu associated with the control
132                 internal bool           use_compatible_text_rendering;
133                 private bool            use_wait_cursor;
134
135                 //accessibility
136                 string accessible_name;
137                 string accessible_description;
138                 string accessible_default_action;
139                 AccessibleRole accessible_role = AccessibleRole.Default;
140                 AccessibleObject accessibility_object; // object that contains accessibility information about our control
141
142                 // double buffering
143                 DoubleBuffer            backbuffer;
144
145                 ControlBindingsCollection data_bindings;
146
147                 static bool verify_thread_handle;
148                 Padding padding;
149                 ImageLayout backgroundimage_layout;
150                 Size maximum_size;
151                 Size minimum_size;
152                 Padding margin;
153                 private ContextMenuStrip context_menu_strip;
154                 private bool nested_layout = false;
155                 Point auto_scroll_offset;
156                 private AutoSizeMode auto_size_mode;
157                 private bool suppressing_key_press;
158
159                 #endregion      // Local Variables
160
161                 #region Private Classes
162                 // This helper class allows us to dispatch messages to Control.WndProc
163                 internal class ControlNativeWindow : NativeWindow {
164                         private Control owner;
165
166                         public ControlNativeWindow(Control control) : base() {
167                                 this.owner=control;
168                         }
169
170
171                         public Control Owner {
172                                 get {
173                                         return owner;
174                                 }
175                         }
176
177                         protected override void OnHandleChange()
178                         {
179                                 this.owner.WindowTarget.OnHandleChange(this.owner.Handle);
180                         }
181
182                         static internal Control ControlFromHandle(IntPtr hWnd) {
183                                 ControlNativeWindow     window;
184
185                                 window = (ControlNativeWindow)NativeWindow.FromHandle (hWnd);
186                                 if (window != null) {
187                                         return window.owner;
188                                 }
189
190                                 return null;
191                         }
192
193                         static internal Control ControlFromChildHandle (IntPtr handle) {
194                                 ControlNativeWindow     window;
195
196                                 Hwnd hwnd = Hwnd.ObjectFromHandle (handle);
197                                 while (hwnd != null) {
198                                         window = (ControlNativeWindow)NativeWindow.FromHandle (handle);
199                                         if (window != null) {
200                                                 return window.owner;
201                                         }
202                                         hwnd = hwnd.Parent;
203                                 }
204
205                                 return null;
206                         }
207
208                         protected override void WndProc(ref Message m) {
209                                 owner.WindowTarget.OnMessage(ref m);
210                         }
211                 }
212
213                 private class ControlWindowTarget : IWindowTarget
214                 {
215                         private Control control;
216
217                         public ControlWindowTarget(Control control)
218                         {
219                                 this.control = control;
220                         }
221
222                         public void OnHandleChange(IntPtr newHandle) 
223                         {
224                         }
225
226                         public void OnMessage(ref Message m) 
227                         {
228                                 control.WndProc(ref m);
229                         }
230                 }
231                 #endregion
232                 
233                 #region Public Classes
234                 [ComVisible(true)]
235                 public class ControlAccessibleObject : AccessibleObject {
236                         IntPtr handle;
237
238                         #region ControlAccessibleObject Constructors
239                         public ControlAccessibleObject(Control ownerControl)
240                                 : base (ownerControl)
241                         {
242                                 if (ownerControl == null)
243                                         throw new ArgumentNullException ("owner");
244
245                                 handle = ownerControl.Handle;
246                         }
247                         #endregion      // ControlAccessibleObject Constructors
248
249                         #region ControlAccessibleObject Public Instance Properties
250                         public override string DefaultAction {
251                                 get {
252                                         return base.DefaultAction;
253                                 }
254                         }
255
256                         public override string Description {
257                                 get {
258                                         return base.Description;
259                                 }
260                         }
261
262                         public IntPtr Handle {
263                                 get {
264                                         return handle;
265                                 }
266
267                                 set {
268                                         // We don't want to let them set it
269                                 }
270                         }
271
272                         public override string Help {
273                                 get {
274                                         return base.Help;
275                                 }
276                         }
277
278                         public override string KeyboardShortcut {
279                                 get {
280                                         return base.KeyboardShortcut;
281                                 }
282                         }
283
284                         public override string Name {
285                                 get {
286                                         return base.Name;
287                                 }
288
289                                 set {
290                                         base.Name = value;
291                                 }
292                         }
293
294                         public Control Owner {
295                                 get {
296                                         return base.owner;
297                                 }
298                         }
299
300                         public override AccessibleObject Parent {
301                                 get {
302                                         return base.Parent;
303                                 }
304                         }
305
306
307                         public override AccessibleRole Role {
308                                 get {
309                                         return base.Role;
310                                 }
311                         }
312                         #endregion      // ControlAccessibleObject Public Instance Properties
313
314                         #region ControlAccessibleObject Public Instance Methods
315                         public override int GetHelpTopic (out string fileName)
316                         {
317                                 return base.GetHelpTopic (out fileName);
318                         }
319
320                         [MonoTODO ("Stub, does nothing")]
321                         public void NotifyClients (AccessibleEvents accEvent)
322                         {
323                         }
324
325                         [MonoTODO ("Stub, does nothing")]
326                         public void NotifyClients (AccessibleEvents accEvent, int childID)
327                         {
328                         }
329
330                         [MonoTODO ("Stub, does nothing")]
331                         public void NotifyClients (AccessibleEvents accEvent, int objectID, int childID)
332                         {
333                         }
334
335                         public override string ToString() {
336                                 return "ControlAccessibleObject: Owner = " + owner.ToString() + ", Text: " + owner.text;
337                         }
338
339                         #endregion      // ControlAccessibleObject Public Instance Methods
340                 }
341
342                 private class DoubleBuffer : IDisposable
343                 {
344                         public Region InvalidRegion;
345                         private Stack real_graphics;
346                         private object back_buffer;
347                         private Control parent;
348                         private bool pending_disposal;
349                         
350                         public DoubleBuffer (Control parent) {
351                                 this.parent = parent;
352                                 real_graphics = new Stack ();
353                                 int width = parent.Width;
354                                 int height = parent.Height;
355
356                                 if (width < 1) width = 1;
357                                 if (height < 1) height = 1;
358
359                                 XplatUI.CreateOffscreenDrawable (parent.Handle, width, height, out back_buffer);
360                                 Invalidate ();
361                         }
362                         
363                         public void Blit (PaintEventArgs pe) {
364                                 Graphics buffered_graphics;
365                                 buffered_graphics = XplatUI.GetOffscreenGraphics (back_buffer);
366                                 XplatUI.BlitFromOffscreen (parent.Handle, pe.Graphics, back_buffer, buffered_graphics, pe.ClipRectangle);
367                                 buffered_graphics.Dispose ();
368                         }
369                         
370                         public void Start (PaintEventArgs pe) {
371                                 // We need to get the graphics for every paint.
372                                 real_graphics.Push(pe.SetGraphics (XplatUI.GetOffscreenGraphics (back_buffer)));
373                         }
374
375                         public void End (PaintEventArgs pe) {
376                                 Graphics buffered_graphics;
377                                 buffered_graphics = pe.SetGraphics ((Graphics) real_graphics.Pop ());
378
379                                 if (pending_disposal) 
380                                         Dispose ();
381                                 else {
382                                         XplatUI.BlitFromOffscreen (parent.Handle, pe.Graphics, back_buffer, buffered_graphics, pe.ClipRectangle);
383                                         InvalidRegion.Exclude (pe.ClipRectangle);
384                                 }
385                                 buffered_graphics.Dispose ();
386                         }
387                         
388                         public void Invalidate ()
389                         {
390                                 if (InvalidRegion != null)
391                                         InvalidRegion.Dispose ();
392                                 InvalidRegion = new Region (parent.ClientRectangle);
393                         }
394                         
395                         public void Dispose () {
396                                 if (real_graphics.Count > 0) {
397                                         pending_disposal = true;
398                                         return;
399                                 }
400                                 
401                                 XplatUI.DestroyOffscreenDrawable (back_buffer);
402
403                                 if (InvalidRegion != null)
404                                         InvalidRegion.Dispose ();
405                                 InvalidRegion = null;
406                                 back_buffer = null;
407                                 GC.SuppressFinalize (this);
408                         }
409
410                         #region IDisposable Members
411                         void IDisposable.Dispose () {
412                                 Dispose ();
413                         }
414                         #endregion
415                         
416                         ~DoubleBuffer () {
417                                 Dispose ();
418                         }
419                 }
420
421                 [ListBindable (false)]
422                 [ComVisible (false)]
423                 public class ControlCollection : Layout.ArrangedElementCollection, IList, ICollection, ICloneable, IEnumerable {
424                         #region ControlCollection Local Variables
425                         ArrayList impl_list;
426                         Control [] all_controls;
427                         Control owner;
428                         #endregion // ControlCollection Local Variables
429
430                         #region ControlCollection Public Constructor
431                         public ControlCollection (Control owner)
432                         {
433                                 this.owner = owner;
434                         }
435                         #endregion
436
437                         #region ControlCollection Public Instance Properties
438
439
440                         public Control Owner {
441                                 get { return this.owner; }
442                         }
443                         
444                         public virtual Control this[string key] {
445                                 get { 
446                                         int index = IndexOfKey (key);
447                                         
448                                         if (index >= 0)
449                                                 return this[index];
450                                                 
451                                         return null;
452                                 }
453                         }
454                         
455                         new public virtual Control this[int index] {
456                                 get {
457                                         if (index < 0 || index >= list.Count) {
458                                                 throw new ArgumentOutOfRangeException("index", index, "ControlCollection does not have that many controls");
459                                         }
460                                         return (Control)list[index];
461                                 }
462                                 
463                                 
464                         }
465
466                         #endregion // ControlCollection Public Instance Properties
467                         
468                         #region ControlCollection Instance Methods
469
470                         public virtual void Add (Control value)
471                         {
472                                 if (value == null)
473                                         return;
474
475                                 Form form_value = value as Form;
476                                 Form form_owner = owner as Form;
477                                 bool owner_permits_toplevels = (owner is MdiClient) || (form_owner != null && form_owner.IsMdiContainer);
478                                 bool child_is_toplevel = value.GetTopLevel();
479                                 bool child_is_mdichild = form_value != null && form_value.IsMdiChild;
480
481                                 if (child_is_toplevel && !(owner_permits_toplevels && child_is_mdichild))
482                                         throw new ArgumentException("Cannot add a top level control to a control.", "value");
483                                 
484                                 if (child_is_mdichild && form_value.MdiParent != null && form_value.MdiParent != owner && form_value.MdiParent != owner.Parent) {
485                                         throw new ArgumentException ("Form cannot be added to the Controls collection that has a valid MDI parent.", "value");
486                                 }
487                                 
488                                 value.recalculate_distances = true;
489                                 
490                                 if (Contains (value)) {
491                                         owner.PerformLayout();
492                                         return;
493                                 }
494
495                                 if (value.tab_index == -1) {
496                                         int     end;
497                                         int     index;
498                                         int     use;
499
500                                         use = 0;
501                                         end = owner.child_controls.Count;
502                                         for (int i = 0; i < end; i++) {
503                                                 index = owner.child_controls[i].tab_index;
504                                                 if (index >= use) {
505                                                         use = index + 1;
506                                                 }
507                                         }
508                                         value.tab_index = use;
509                                 }
510
511                                 if (value.parent != null) {
512                                         value.parent.Controls.Remove(value);
513                                 }
514
515                                 all_controls = null;
516                                 list.Add (value);
517
518                                 value.ChangeParent(owner);
519
520                                 value.InitLayout();
521
522                                 if (owner.Visible)
523                                         owner.UpdateChildrenZOrder();
524                                 owner.PerformLayout(value, "Parent");
525                                 owner.OnControlAdded(new ControlEventArgs(value));
526                         }
527                         
528                         internal void AddToList (Control c)
529                         {
530                                 all_controls = null;
531                                 list.Add (c);
532                         }
533
534                         internal virtual void AddImplicit (Control control)
535                         {
536                                 if (impl_list == null)
537                                         impl_list = new ArrayList ();
538
539                                 if (AllContains (control)) {
540                                         owner.PerformLayout ();
541                                         return;
542                                 }
543
544                                 if (control.parent != null) {
545                                         control.parent.Controls.Remove(control);
546                                 }
547
548                                 all_controls = null;
549                                 impl_list.Add (control);
550
551                                 control.ChangeParent (owner);
552                                 control.InitLayout ();
553                                 if (owner.Visible)
554                                         owner.UpdateChildrenZOrder ();
555                                 
556                                 // If we are adding a new control that isn't
557                                 // visible, don't trigger a layout
558                                 if (control.VisibleInternal)
559                                         owner.PerformLayout (control, "Parent");
560                         }
561                         [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
562                         public virtual void AddRange (Control[] controls)
563                         {
564                                 if (controls == null)
565                                         throw new ArgumentNullException ("controls");
566
567                                 owner.SuspendLayout ();
568
569                                 try {
570                                         for (int i = 0; i < controls.Length; i++) 
571                                                 Add (controls[i]);
572                                 } finally {
573                                         owner.ResumeLayout ();
574                                 }
575                         }
576
577                         internal virtual void AddRangeImplicit (Control [] controls)
578                         {
579                                 if (controls == null)
580                                         throw new ArgumentNullException ("controls");
581
582                                 owner.SuspendLayout ();
583
584                                 try {
585                                         for (int i = 0; i < controls.Length; i++)
586                                                 AddImplicit (controls [i]);
587                                 } finally {
588                                         owner.ResumeLayout (false);
589                                 }
590                         }
591
592                         new 
593                         public virtual void Clear ()
594                         {
595                                 all_controls = null;
596
597                                 // MS sends remove events in reverse order
598                                 while (list.Count > 0) {
599                                         Remove((Control)list[list.Count - 1]);
600                                 }
601                         }
602
603                         internal virtual void ClearImplicit ()
604                         {
605                                 if (impl_list == null)
606                                         return;
607                                 all_controls = null;
608                                 impl_list.Clear ();
609                         }
610
611                         public bool Contains (Control control)
612                         {
613                                 return list.Contains (control);
614                         }
615
616                         internal bool ImplicitContains (Control value) {
617                                 if (impl_list == null)
618                                         return false;
619
620                                 return impl_list.Contains (value);
621                         }
622
623                         internal bool AllContains (Control value) {
624                                 return Contains (value) || ImplicitContains (value);
625                         }
626
627
628                         public virtual bool ContainsKey (string key)
629                         {
630                                 return IndexOfKey (key) >= 0;
631                         }
632
633
634                         // LAMESPEC: MSDN says AE, MS implementation throws ANE
635                         public Control[] Find (string key, bool searchAllChildren)
636                         {
637                                 if (string.IsNullOrEmpty (key))
638                                         throw new ArgumentNullException ("key");
639                                         
640                                 ArrayList al = new ArrayList ();
641                                 
642                                 foreach (Control c in list) {
643                                         if (c.Name.Equals (key, StringComparison.CurrentCultureIgnoreCase))
644                                                 al.Add (c);
645                                                 
646                                         if (searchAllChildren)
647                                                 al.AddRange (c.Controls.Find (key, true));
648                                 }
649                                 
650                                 return (Control[])al.ToArray (typeof (Control));
651                         }
652
653                         public int GetChildIndex(Control child) {
654                                 return GetChildIndex(child, false);
655                         }
656
657                         public virtual int GetChildIndex(Control child, bool throwException) {
658                                 int index;
659
660                                 index=list.IndexOf(child);
661
662                                 if (index==-1 && throwException) {
663                                         throw new ArgumentException("Not a child control", "child");
664                                 }
665                                 return index;
666                         }
667
668                         public override IEnumerator
669                         GetEnumerator () {
670                                 return new ControlCollectionEnumerator (list);
671                         }
672
673                         internal IEnumerator GetAllEnumerator () {
674                                 Control [] res = GetAllControls ();
675                                 return res.GetEnumerator ();
676                         }
677
678                         internal ArrayList ImplicitControls {
679                                 get { return impl_list; }
680                         }
681                         
682                         internal Control [] GetAllControls () {
683                                 if (all_controls != null)
684                                         return all_controls;
685
686                                 if (impl_list == null) {
687                                         all_controls = (Control []) list.ToArray (typeof (Control));
688                                         return all_controls;
689                                 }
690                                 
691                                 all_controls = new Control [list.Count + impl_list.Count];
692                                 impl_list.CopyTo (all_controls);
693                                 list.CopyTo (all_controls, impl_list.Count);
694
695                                 return all_controls;
696                         }
697
698                         public int IndexOf (Control control)
699                         {
700                                 return list.IndexOf (control);
701                         }
702
703                         public virtual int IndexOfKey (string key)
704                         {
705                                 if (string.IsNullOrEmpty (key))
706                                         return -1;
707                                         
708                                 for (int i = 0; i < list.Count; i++)
709                                         if (((Control)list[i]).Name.Equals (key, StringComparison.CurrentCultureIgnoreCase))
710                                                 return i;
711                                                 
712                                 return -1;
713                         }
714
715                         public virtual void Remove (Control value)
716                         {
717                                 if (value == null)
718                                         return;
719
720                                 all_controls = null;
721                                 list.Remove(value);
722
723                                 owner.PerformLayout(value, "Parent");
724                                 owner.OnControlRemoved(new ControlEventArgs(value));
725
726                                 ContainerControl container = owner.InternalGetContainerControl ();
727                                 if (container != null) { 
728                                         // Inform any container controls about the loss of a child control
729                                         // so that they can update their active control
730                                         container.ChildControlRemoved (value);
731                                 }
732
733                                 value.ChangeParent(null);
734
735                                 owner.UpdateChildrenZOrder();
736                         }
737
738                         internal virtual void RemoveImplicit (Control control)
739                         {
740                                 if (impl_list != null) {
741                                         all_controls = null;
742                                         impl_list.Remove (control);
743                                         owner.PerformLayout (control, "Parent");
744                                         owner.OnControlRemoved (new ControlEventArgs (control));
745                                 }
746                                 control.ChangeParent (null);
747                                 owner.UpdateChildrenZOrder ();
748                         }
749
750                         public void RemoveAt (int index)
751                         {
752                                 if (index < 0 || index >= list.Count)
753                                         throw new ArgumentOutOfRangeException("index", index, "ControlCollection does not have that many controls");
754
755                                 Remove ((Control) list [index]);
756                         }
757
758                         public virtual void RemoveByKey (string key)
759                         {
760                                 int index = IndexOfKey (key);
761                                 
762                                 if (index >= 0)
763                                         RemoveAt (index);
764                         }
765
766                         public virtual void SetChildIndex(Control child, int newIndex)
767                         {
768                                 if (child == null)
769                                         throw new ArgumentNullException ("child");
770
771                                 int     old_index;
772
773                                 old_index=list.IndexOf(child);
774                                 if (old_index==-1) {
775                                         throw new ArgumentException("Not a child control", "child");
776                                 }
777
778                                 if (old_index==newIndex) {
779                                         return;
780                                 }
781
782                                 all_controls = null;
783                                 list.RemoveAt(old_index);
784
785                                 if (newIndex>list.Count) {
786                                         list.Add(child);
787                                 } else {
788                                         list.Insert(newIndex, child);
789                                 }
790                                 child.UpdateZOrder();
791                                 owner.PerformLayout();
792                         }
793
794                         #endregion // ControlCollection Private Instance Methods
795
796                         #region ControlCollection Interface Properties
797
798                         #endregion // ControlCollection Interface Properties
799
800                         #region ControlCollection Interface Methods
801
802                         int IList.Add (object control)
803                         {
804                                 if (!(control is Control))
805                                         throw new ArgumentException ("Object of type Control required", "control");
806
807                                 if (control == null)
808                                         throw new ArgumentException ("control", "Cannot add null controls");
809
810                                 this.Add ((Control)control);
811                                 return this.IndexOf ((Control)control);
812                         }
813
814                         void IList.Remove (object control)
815                         {
816                                 if (!(control is Control))
817                                         throw new ArgumentException ("Object of type Control required", "control");
818
819                                 this.Remove ((Control)control);
820                         }
821
822                         Object ICloneable.Clone ()
823                         {
824                                 ControlCollection clone = new ControlCollection (this.owner);
825                                 clone.list = (ArrayList)list.Clone ();          // FIXME: Do we need this?
826                                 return clone;
827                         }
828
829                         #endregion // ControlCollection Interface Methods
830                 
831                         internal class ControlCollectionEnumerator : IEnumerator
832                         {
833                                 private ArrayList list;
834                                 int position = -1;
835                                 
836                                 public ControlCollectionEnumerator (ArrayList collection)
837                                 {
838                                         list = collection;
839                                 }
840                                 
841                                 #region IEnumerator Members
842                                 public object Current {
843                                         get {
844                                                 try {
845                                                         return list[position];
846                                                 } catch (IndexOutOfRangeException) {
847                                                         throw new InvalidOperationException ();
848                                                 }
849                                         }
850                                 }
851
852                                 public bool MoveNext ()
853                                 {
854                                         position++;
855                                         return (position < list.Count);
856                                 }
857
858                                 public void Reset ()
859                                 {
860                                         position = -1;
861                                 }
862
863                                 #endregion
864                         }
865                 }
866                 #endregion      // ControlCollection Class
867                 
868                 #region Public Constructors
869                 public Control ()
870                 {
871                         if (WindowsFormsSynchronizationContext.AutoInstall)
872                                 if (!(SynchronizationContext.Current is WindowsFormsSynchronizationContext))
873                                         SynchronizationContext.SetSynchronizationContext (new WindowsFormsSynchronizationContext ());
874
875                         layout_type = LayoutType.Anchor;
876                         anchor_style = AnchorStyles.Top | AnchorStyles.Left;
877
878                         is_created = false;
879                         is_visible = true;
880                         is_captured = false;
881                         is_disposed = false;
882                         is_enabled = true;
883                         is_entered = false;
884                         layout_pending = false;
885                         is_toplevel = false;
886                         causes_validation = true;
887                         has_focus = false;
888                         layout_suspended = 0;
889                         mouse_clicks = 1;
890                         tab_index = -1;
891                         cursor = null;
892                         right_to_left = RightToLeft.Inherit;
893                         border_style = BorderStyle.None;
894                         background_color = Color.Empty;
895                         dist_right = 0;
896                         dist_bottom = 0;
897                         tab_stop = true;
898                         ime_mode = ImeMode.Inherit;
899                         use_compatible_text_rendering = true;
900                         show_keyboard_cues = false;
901                         show_focus_cues = SystemInformation.MenuAccessKeysUnderlined;
902                         use_wait_cursor = false;
903
904                         backgroundimage_layout = ImageLayout.Tile;
905                         use_compatible_text_rendering = Application.use_compatible_text_rendering;
906                         padding = this.DefaultPadding;
907                         maximum_size = new Size();
908                         minimum_size = new Size();
909                         margin = this.DefaultMargin;
910                         auto_size_mode = AutoSizeMode.GrowOnly;
911
912                         control_style = ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | 
913                                         ControlStyles.Selectable | ControlStyles.StandardClick | 
914                                         ControlStyles.StandardDoubleClick;
915                         control_style |= ControlStyles.UseTextForAccessibility;
916
917                         parent = null;
918                         background_image = null;
919                         text = string.Empty;
920                         name = string.Empty;
921
922                         window_target = new ControlWindowTarget(this);
923                         window = new ControlNativeWindow(this);
924                         child_controls = CreateControlsInstance();
925                         
926                         bounds.Size = DefaultSize;
927                         client_size = ClientSizeFromSize (bounds.Size);
928                         client_rect = new Rectangle (Point.Empty, client_size);
929                         explicit_bounds = bounds;
930                 }
931
932                 public Control (Control parent, string text) : this()
933                 {
934                         Text=text;
935                         Parent=parent;
936                 }
937
938                 public Control (Control parent, string text, int left, int top, int width, int height) : this()
939                 {
940                         Parent=parent;
941                         SetBounds(left, top, width, height, BoundsSpecified.All);
942                         Text=text;
943                 }
944
945                 public Control (string text) : this()
946                 {
947                         Text=text;
948                 }
949
950                 public Control (string text, int left, int top, int width, int height) : this()
951                 {
952                         SetBounds(left, top, width, height, BoundsSpecified.All);
953                         Text=text;
954                 }
955
956                 private delegate void RemoveDelegate(object c);
957
958                 protected override void Dispose (bool disposing)
959                 {
960                         if (!is_disposed && disposing) {
961                                 is_disposing = true;
962                                 Capture = false;
963
964                                 DisposeBackBuffer ();
965
966                                 if (this.InvokeRequired) {
967                                         if (Application.MessageLoop && IsHandleCreated) {
968                                                 this.BeginInvokeInternal(new MethodInvoker(DestroyHandle), null);
969                                         }
970                                 } else {
971                                         DestroyHandle();
972                                 }
973
974                                 if (parent != null)
975                                         parent.Controls.Remove(this);
976
977                                 Control [] children = child_controls.GetAllControls ();
978                                 for (int i=0; i<children.Length; i++) {
979                                         children[i].parent = null;      // Need to set to null or our child will try and remove from ourselves and crash
980                                         children[i].Dispose();
981                                 }
982                         }
983                         is_disposed = true;
984                         base.Dispose(disposing);
985                 }
986                 #endregion      // Public Constructors
987
988                 #region Internal Properties
989
990                 internal Rectangle PaddingClientRectangle
991                 {
992                         get {
993                                 return new Rectangle (
994                                         ClientRectangle.Left   + padding.Left,
995                                         ClientRectangle.Top    + padding.Top, 
996                                         ClientRectangle.Width  - padding.Horizontal, 
997                                         ClientRectangle.Height - padding.Vertical);
998                         }
999                 }
1000
1001                 private MenuTracker active_tracker;
1002                 
1003                 internal MenuTracker ActiveTracker {
1004                         get { return active_tracker; }
1005                         set {
1006                                 if (value == active_tracker)
1007                                         return;
1008
1009                                 Capture = value != null;
1010                                 active_tracker = value;
1011                         }
1012                 }
1013
1014                 // Control is currently selected, like Focused, except maintains state
1015                 // when Form loses focus
1016                 internal bool InternalSelected {
1017                         get {
1018                                 IContainerControl container;
1019                         
1020                                 container = GetContainerControl();
1021                                 
1022                                 if (container != null && container.ActiveControl == this)
1023                                         return true;
1024                                         
1025                                 return false;
1026                         }
1027                 }
1028
1029                 // Looks for focus in child controls
1030                 // and also in the implicit ones
1031                 internal bool InternalContainsFocus {
1032                         get {
1033                                 IntPtr focused_window;
1034
1035                                 focused_window = XplatUI.GetFocus();
1036                                 if (IsHandleCreated) {
1037                                         if (focused_window == Handle)
1038                                                 return true;
1039
1040                                         foreach (Control child_control in child_controls.GetAllControls ())
1041                                                 if (child_control.InternalContainsFocus)
1042                                                         return true;
1043                                 }
1044
1045                                 return false;
1046                         }
1047                 }
1048                 
1049                 // Mouse is currently within the control's bounds
1050                 internal bool Entered {
1051                         get { return this.is_entered; }
1052                 }
1053
1054                 internal bool VisibleInternal {
1055                         get { return is_visible; }
1056                 }
1057
1058                 internal LayoutType ControlLayoutType {
1059                         get { return layout_type; }
1060                 }
1061
1062                 internal BorderStyle InternalBorderStyle {
1063                         get {
1064                                 return border_style;
1065                         }
1066
1067                         set {
1068                                 if (!Enum.IsDefined (typeof (BorderStyle), value))
1069                                         throw new InvalidEnumArgumentException (string.Format("Enum argument value '{0}' is not valid for BorderStyle", value));
1070
1071                                 if (border_style != value) {
1072                                         border_style = value;
1073
1074                                         if (IsHandleCreated) {
1075                                                 XplatUI.SetBorderStyle (window.Handle, (FormBorderStyle)border_style);
1076                                                 RecreateHandle ();
1077                                                 Refresh ();
1078                                         } else
1079                                                 client_size = ClientSizeFromSize (bounds.Size);
1080                                 }
1081                         }
1082                 }
1083                 
1084                 internal Size InternalClientSize { set { this.client_size = value; } }
1085                 internal virtual bool ActivateOnShow { get { return true; } }
1086                 internal Rectangle ExplicitBounds { get { return this.explicit_bounds; } set { this.explicit_bounds = value; } }
1087
1088                 internal bool ValidationFailed { 
1089                         get { 
1090                                 ContainerControl c = InternalGetContainerControl ();
1091                                 if (c != null)
1092                                         return c.validation_failed;
1093                                 return false;
1094                         }
1095                         set { 
1096                                 ContainerControl c = InternalGetContainerControl ();
1097                                 if (c != null)
1098                                         c.validation_failed = value; 
1099                         }
1100                 }
1101                 #endregion      // Internal Properties
1102
1103                 #region Private & Internal Methods
1104                 
1105                 void IDropTarget.OnDragDrop (DragEventArgs drgEvent)
1106                 {
1107                         OnDragDrop (drgEvent);
1108                 }
1109                 
1110                 void IDropTarget.OnDragEnter (DragEventArgs drgEvent)
1111                 {
1112                         OnDragEnter (drgEvent);
1113                 }
1114                 
1115                 void IDropTarget.OnDragLeave (EventArgs e)
1116                 {
1117                         OnDragLeave (e);
1118                 }
1119
1120                 void IDropTarget.OnDragOver (DragEventArgs drgEvent)
1121                 {
1122                         OnDragOver (drgEvent);
1123                 }
1124
1125                 internal IAsyncResult BeginInvokeInternal (Delegate method, object [] args) {
1126                         return BeginInvokeInternal (method, args, FindControlToInvokeOn ());
1127                 }
1128
1129                 internal IAsyncResult BeginInvokeInternal (Delegate method, object [] args, Control control) {
1130                         AsyncMethodResult       result;
1131                         AsyncMethodData         data;
1132
1133                         result = new AsyncMethodResult ();
1134                         data = new AsyncMethodData ();
1135
1136                         data.Handle = control.GetInvokableHandle ();
1137                         data.Method = method;
1138                         data.Args = args;
1139                         data.Result = result;
1140
1141                         if (!ExecutionContext.IsFlowSuppressed ()) {
1142                                 data.Context = ExecutionContext.Capture ();
1143                         }
1144
1145                         XplatUI.SendAsyncMethod (data);
1146                         return result;
1147                 }
1148
1149                 // The CheckForIllegalCrossThreadCalls in the #if 2.0 of
1150                 // Control.Handle throws an exception when we are trying
1151                 // to get the Handle to properly invoke on.  This avoids that.
1152                 private IntPtr GetInvokableHandle ()
1153                 {
1154                         if (!IsHandleCreated)
1155                                 CreateHandle ();
1156
1157                         return window.Handle;
1158                 }
1159
1160                 internal void PointToClient (ref int x, ref int y) {
1161                         XplatUI.ScreenToClient (Handle, ref x, ref y);
1162                 }
1163
1164                 internal void PointToScreen (ref int x, ref int y) {
1165                         XplatUI.ClientToScreen (Handle, ref x, ref y);
1166                 }
1167
1168                 internal bool IsRecreating {
1169                         get {
1170                                 return is_recreating;
1171                         }
1172                 }
1173
1174                 internal Graphics DeviceContext {
1175                         get { return Hwnd.GraphicsContext; }
1176                 }
1177
1178                 // An internal way to have a fixed height
1179                 // Basically for DataTimePicker 2.0
1180                 internal virtual int OverrideHeight (int height)
1181                 {
1182                         return height;
1183                 }
1184                 
1185                 private void ProcessActiveTracker (ref Message m)
1186                 {
1187                         bool is_up = ((Msg) m.Msg == Msg.WM_LBUTTONUP) ||
1188                                                  ((Msg) m.Msg == Msg.WM_RBUTTONUP);
1189                         
1190                         MouseButtons mb = FromParamToMouseButtons ((int) m.WParam.ToInt32 ());
1191                         
1192                         // We add in the button that was released (not sent in WParam)
1193                         if (is_up) {
1194                                 switch ((Msg)m.Msg) {
1195                                 case Msg.WM_LBUTTONUP:
1196                                         mb |= MouseButtons.Left;
1197                                         break;
1198                                 case Msg.WM_RBUTTONUP:
1199                                         mb |= MouseButtons.Right;
1200                                         break;
1201                                 }
1202                         }
1203                         
1204                         MouseEventArgs args = new MouseEventArgs (
1205                                 mb,
1206                                 mouse_clicks,
1207                                 Control.MousePosition.X,
1208                                 Control.MousePosition.Y,
1209                                 0);
1210
1211                         if (is_up) {
1212                                 active_tracker.OnMouseUp (args);
1213                                 mouse_clicks = 1;
1214                         } else {
1215                                 if (!active_tracker.OnMouseDown (args)) {
1216                                         Control control = GetRealChildAtPoint (Cursor.Position);
1217                                         if (control != null) {
1218                                                 Point pt = control.PointToClient (Cursor.Position);
1219                                                 XplatUI.SendMessage (control.Handle, 
1220                                                         (Msg)m.Msg, 
1221                                                         m.WParam, 
1222                                                         MakeParam (pt.X, pt.Y));
1223                                         }
1224                                 }
1225                         }
1226                 }
1227
1228                 private Control FindControlToInvokeOn ()
1229                 {
1230                         Control p = this;
1231                         do {
1232                                 if (p.IsHandleCreated)
1233                                         break;
1234                                 p = p.parent;
1235                         } while (p != null);
1236
1237                         if (p == null || !p.IsHandleCreated)
1238                                 throw new InvalidOperationException ("Cannot call Invoke or BeginInvoke on a control until the window handle is created");
1239                         
1240                         return p;
1241                 }
1242
1243                 private void InvalidateBackBuffer () {
1244                         if (backbuffer != null)
1245                                 backbuffer.Invalidate ();
1246                 }
1247
1248                 private DoubleBuffer GetBackBuffer () {
1249                         if (backbuffer == null)
1250                                 backbuffer = new DoubleBuffer (this);
1251                         return backbuffer;
1252                 }
1253
1254                 private void DisposeBackBuffer () {
1255                         if (backbuffer != null) {
1256                                 backbuffer.Dispose ();
1257                                 backbuffer = null;
1258                         }
1259                 }
1260
1261                 internal static void SetChildColor(Control parent) {
1262                         Control child;
1263
1264                         for (int i=0; i < parent.child_controls.Count; i++) {
1265                                 child=parent.child_controls[i];
1266                                 if (child.child_controls.Count>0) {
1267                                         SetChildColor(child);
1268                                 }
1269                         }
1270                 }
1271
1272                 internal bool Select(Control control) {
1273                         IContainerControl       container;
1274
1275                         if (control == null) {
1276                                 return false;
1277                         }
1278
1279                         container = GetContainerControl();
1280                         if (container != null && (Control)container != control) {
1281                                 container.ActiveControl = control;
1282                                 if (container.ActiveControl == control && !control.has_focus && control.IsHandleCreated)
1283                                         XplatUI.SetFocus(control.window.Handle);
1284                         }
1285                         else if (control.IsHandleCreated) {
1286                                 XplatUI.SetFocus(control.window.Handle);
1287                         }
1288                         return true;
1289                 }
1290
1291                 internal virtual void DoDefaultAction() {
1292                         // Only here to be overriden by our actual controls; this is needed by the accessibility class
1293                 }
1294
1295                 internal static IntPtr MakeParam (int low, int high){
1296                         return new IntPtr (high << 16 | low & 0xffff);
1297                 }
1298
1299                 internal static int LowOrder (int param) {
1300                         return ((int)(short)(param & 0xffff));
1301                 }
1302
1303                 internal static int HighOrder (long param) {
1304                         return ((int)(short)(param >> 16));
1305                 }
1306
1307                 // This method exists so controls overriding OnPaintBackground can have default background painting done
1308                 internal virtual void PaintControlBackground (PaintEventArgs pevent) {
1309
1310                         bool tbstyle_flat = ((CreateParams.Style & (int) ToolBarStyles.TBSTYLE_FLAT) != 0);
1311
1312                         // If we have transparent background
1313                         if (((BackColor.A != 0xff) && GetStyle(ControlStyles.SupportsTransparentBackColor)) || tbstyle_flat) {
1314                                 if (parent != null) {
1315                                         PaintEventArgs  parent_pe;
1316                                         GraphicsState   state;
1317
1318                                         parent_pe = new PaintEventArgs(pevent.Graphics, new Rectangle(pevent.ClipRectangle.X + Left, pevent.ClipRectangle.Y + Top, pevent.ClipRectangle.Width, pevent.ClipRectangle.Height));
1319
1320                                         state = parent_pe.Graphics.Save();
1321                                         parent_pe.Graphics.TranslateTransform(-Left, -Top);
1322                                         parent.OnPaintBackground(parent_pe);
1323                                         parent_pe.Graphics.Restore(state);
1324
1325                                         state = parent_pe.Graphics.Save();
1326                                         parent_pe.Graphics.TranslateTransform(-Left, -Top);
1327                                         parent.OnPaint(parent_pe);
1328                                         parent_pe.Graphics.Restore(state);
1329                                         parent_pe.SetGraphics(null);
1330                                 }
1331                         }
1332
1333                         if ((clip_region != null) && (XplatUI.UserClipWontExposeParent)) {
1334                                 if (parent != null) {
1335                                         PaintEventArgs  parent_pe;
1336                                         Region          region;
1337                                         GraphicsState   state;
1338                                         Hwnd            hwnd;
1339
1340                                         hwnd = Hwnd.ObjectFromHandle(Handle);
1341
1342                                         if (hwnd != null) {
1343                                                 parent_pe = new PaintEventArgs(pevent.Graphics, new Rectangle(pevent.ClipRectangle.X + Left, pevent.ClipRectangle.Y + Top, pevent.ClipRectangle.Width, pevent.ClipRectangle.Height));
1344
1345                                                 region = new Region ();
1346                                                 region.MakeEmpty();
1347                                                 region.Union(ClientRectangle);
1348
1349                                                 foreach (Rectangle r in hwnd.ClipRectangles) {
1350                                                         region.Union (r);
1351                                                 }
1352
1353                                                 state = parent_pe.Graphics.Save();
1354                                                 parent_pe.Graphics.Clip = region;
1355
1356                                                 parent_pe.Graphics.TranslateTransform(-Left, -Top);
1357                                                 parent.OnPaintBackground(parent_pe);
1358                                                 parent_pe.Graphics.Restore(state);
1359
1360                                                 state = parent_pe.Graphics.Save();
1361                                                 parent_pe.Graphics.Clip = region;
1362
1363                                                 parent_pe.Graphics.TranslateTransform(-Left, -Top);
1364                                                 parent.OnPaint(parent_pe);
1365                                                 parent_pe.Graphics.Restore(state);
1366                                                 parent_pe.SetGraphics(null);
1367
1368                                                 region.Intersect(clip_region);
1369                                                 pevent.Graphics.Clip = region;
1370                                         }
1371                                 }
1372                         }
1373
1374                         if (background_image == null) {
1375                                 if (!tbstyle_flat) {
1376                                         Rectangle paintRect = pevent.ClipRectangle;
1377                                         Brush pen = ThemeEngine.Current.ResPool.GetSolidBrush(BackColor);
1378                                         pevent.Graphics.FillRectangle(pen, paintRect);
1379                                 }
1380                                 return;
1381                         }
1382
1383                         DrawBackgroundImage (pevent.Graphics);
1384                 }
1385
1386                 void DrawBackgroundImage (Graphics g) {
1387                         Rectangle drawing_rectangle = new Rectangle ();
1388                         g.FillRectangle (ThemeEngine.Current.ResPool.GetSolidBrush (BackColor), ClientRectangle);
1389                                 
1390                         switch (backgroundimage_layout)
1391                         {
1392                         case ImageLayout.Tile:
1393                                 using (TextureBrush b = new TextureBrush (background_image, WrapMode.Tile)) {
1394                                         g.FillRectangle (b, ClientRectangle);
1395                                 }
1396                                 return;
1397                         case ImageLayout.Center:
1398                                 drawing_rectangle.Location = new Point (ClientSize.Width / 2 - background_image.Width / 2, ClientSize.Height / 2 - background_image.Height / 2);
1399                                 drawing_rectangle.Size = background_image.Size;
1400                                 break;
1401                         case ImageLayout.None:
1402                                 drawing_rectangle.Location = Point.Empty;
1403                                 drawing_rectangle.Size = background_image.Size;
1404                                 break;
1405                         case ImageLayout.Stretch:
1406                                 drawing_rectangle = ClientRectangle;
1407                                 break;
1408                         case ImageLayout.Zoom:
1409                                 drawing_rectangle = ClientRectangle;
1410                                 if ((float)background_image.Width / (float)background_image.Height < (float)drawing_rectangle.Width / (float) drawing_rectangle.Height) {
1411                                         drawing_rectangle.Width = (int) (background_image.Width * ((float)drawing_rectangle.Height / (float)background_image.Height));
1412                                         drawing_rectangle.X = (ClientRectangle.Width - drawing_rectangle.Width) / 2;
1413                                 } else {
1414                                         drawing_rectangle.Height = (int) (background_image.Height * ((float)drawing_rectangle.Width / (float)background_image.Width));
1415                                         drawing_rectangle.Y = (ClientRectangle.Height - drawing_rectangle.Height) / 2;
1416                                 }
1417                                 break;
1418                         default:
1419                                 return;
1420                         }
1421
1422                         g.DrawImage (background_image, drawing_rectangle);
1423
1424                 }
1425
1426                 internal virtual void DndEnter (DragEventArgs e) {
1427                         try {
1428                                 OnDragEnter (e);
1429                         } catch { }
1430                 }
1431
1432                 internal virtual void DndOver (DragEventArgs e) {
1433                         try {
1434                                 OnDragOver (e);
1435                         } catch { }
1436                 }
1437
1438                 internal virtual void DndDrop (DragEventArgs e) {
1439                         try {
1440                                 OnDragDrop (e);
1441                         } catch (Exception exc) {
1442                                 Console.Error.WriteLine ("MWF: Exception while dropping:");
1443                                 Console.Error.WriteLine (exc);
1444                         }
1445                 }
1446
1447                 internal virtual void DndLeave (EventArgs e) {
1448                         try {
1449                                 OnDragLeave (e);
1450                         } catch { }
1451                 }
1452
1453                 internal virtual void DndFeedback(GiveFeedbackEventArgs e) {
1454                         try {
1455                                 OnGiveFeedback(e);
1456                         } catch { }
1457                 }
1458
1459                 internal virtual void DndContinueDrag(QueryContinueDragEventArgs e) {
1460                         try {
1461                                 OnQueryContinueDrag(e);
1462                         } catch { }
1463                 }
1464                 
1465                 internal static MouseButtons FromParamToMouseButtons (long param) {             
1466                         MouseButtons buttons = MouseButtons.None;
1467                                         
1468                         if ((param & (long) MsgButtons.MK_LBUTTON) != 0)
1469                                 buttons |= MouseButtons.Left;
1470
1471                         if ((param & (long)MsgButtons.MK_MBUTTON) != 0)
1472                                 buttons |= MouseButtons.Middle;
1473
1474                         if ((param & (long)MsgButtons.MK_RBUTTON) != 0)
1475                                 buttons |= MouseButtons.Right;
1476                                 
1477                         return buttons;
1478                 }
1479
1480                 internal virtual void FireEnter () {
1481                         OnEnter (EventArgs.Empty);
1482                 }
1483
1484                 internal virtual void FireLeave () {
1485                         OnLeave (EventArgs.Empty);
1486                 }
1487
1488                 internal virtual void FireValidating (CancelEventArgs ce) {
1489                         OnValidating (ce);
1490                 }
1491
1492                 internal virtual void FireValidated () {
1493                         OnValidated (EventArgs.Empty);
1494                 }
1495
1496                 internal virtual bool ProcessControlMnemonic(char charCode) {
1497                         return ProcessMnemonic(charCode);
1498                 }
1499
1500                 private static Control FindFlatForward(Control container, Control start) {
1501                         Control found;
1502                         int     index;
1503                         int     end;
1504                         bool hit;
1505
1506                         found = null;
1507                         end = container.child_controls.Count;
1508                         hit = false;
1509
1510                         if (start != null) {
1511                                 index = start.tab_index;
1512                         } else {
1513                                 index = -1;
1514                         }
1515
1516                         for (int i = 0; i < end; i++) {
1517                                 if (start == container.child_controls[i]) {
1518                                         hit = true;
1519                                         continue;
1520                                 }
1521
1522                                 if (found == null || found.tab_index > container.child_controls[i].tab_index) {
1523                                         if (container.child_controls[i].tab_index > index || (hit && container.child_controls[i].tab_index == index)) {
1524                                                 found = container.child_controls[i];
1525                                         }
1526                                 }
1527                         }
1528                         return found;
1529                 }
1530
1531                 private static Control FindControlForward(Control container, Control start) {
1532                         Control found;
1533
1534                         found = null;
1535
1536                         if (start == null) {
1537                                 return FindFlatForward(container, start);
1538                         }
1539
1540                         if (start.child_controls != null && start.child_controls.Count > 0 && 
1541                                 (start == container || !((start is IContainerControl) &&  start.GetStyle(ControlStyles.ContainerControl)))) {
1542                                 return FindControlForward(start, null);
1543                         }
1544                         else {
1545                                 while (start != container) {
1546                                         found = FindFlatForward(start.parent, start);
1547                                         if (found != null) {
1548                                                 return found;
1549                                         }
1550                                         start = start.parent;
1551                                 }
1552                         }
1553                         return null;
1554                 }
1555
1556                 private static Control FindFlatBackward(Control container, Control start) {
1557                         Control found;
1558                         int     index;
1559                         int     end;
1560                         bool hit;
1561
1562                         found = null;
1563                         end = container.child_controls.Count;
1564                         hit = false;
1565
1566                         if (start != null) {
1567                                 index = start.tab_index;
1568                         } else {
1569                                 index = int.MaxValue;
1570                         }
1571
1572                         for (int i = end - 1; i >= 0; i--) {
1573                                 if (start == container.child_controls[i]) {
1574                                         hit = true;
1575                                         continue;
1576                                 }
1577
1578                                 if (found == null || found.tab_index < container.child_controls[i].tab_index) {
1579                                         if (container.child_controls[i].tab_index < index || (hit && container.child_controls[i].tab_index == index))
1580                                                 found = container.child_controls[i];
1581
1582                                 }
1583                         }
1584                         return found;
1585                 }
1586
1587                 private static Control FindControlBackward(Control container, Control start) {
1588
1589                         Control found = null;
1590
1591                         if (start == null) {
1592                                 found = FindFlatBackward(container, start);
1593                         }
1594                         else if (start != container) {
1595                                 if (start.parent != null) {
1596                                         found = FindFlatBackward(start.parent, start);
1597
1598                                         if (found == null) {
1599                                                 if (start.parent != container)
1600                                                         return start.parent;
1601                                                 return null;
1602                                         }
1603                                 }
1604                         }
1605                 
1606                         if (found == null || start.parent == null)
1607                                 found = start;
1608
1609                         while (found != null && (found == container || (!((found is IContainerControl) && found.GetStyle(ControlStyles.ContainerControl))) &&
1610                                 found.child_controls != null && found.child_controls.Count > 0)) {
1611 //                              while (ctl.child_controls != null && ctl.child_controls.Count > 0 && 
1612 //                                      (ctl == this || (!((ctl is IContainerControl) && ctl.GetStyle(ControlStyles.ContainerControl))))) {
1613                                 found = FindFlatBackward(found, null);
1614                         }
1615
1616                         return found;
1617
1618 /*
1619                         Control found;
1620
1621                         found = null;
1622
1623                         if (start != null) {
1624                                 found = FindFlatBackward(start.parent, start);
1625                                 if (found == null) {
1626                                         if (start.parent != container) {
1627                                                 return start.parent;
1628                                         }
1629                                 }
1630                         }
1631                         if (found == null) {
1632                                 found = FindFlatBackward(container, start);
1633                         }
1634
1635                         if (container != start) {
1636                                 while ((found != null) && (!found.Contains(start)) && found.child_controls != null && found.child_controls.Count > 0 && !(found is IContainerControl)) {// || found.GetStyle(ControlStyles.ContainerControl))) {
1637                                         found = FindControlBackward(found, null);
1638                                          if (found != null) {
1639                                                 return found;
1640                                         }
1641                                 }
1642                         }
1643                         return found;
1644 */                      
1645                 }
1646
1647                 internal virtual void HandleClick(int clicks, MouseEventArgs me) {
1648                         bool standardclick = GetStyle (ControlStyles.StandardClick);
1649                         bool standardclickclick = GetStyle (ControlStyles.StandardDoubleClick);
1650                         if ((clicks > 1) && standardclick && standardclickclick) {
1651                                 OnDoubleClick (me);
1652                                 OnMouseDoubleClick (me);
1653                         } else if (clicks == 1 && standardclick && !ValidationFailed) {
1654                                 OnClick (me);
1655                                 OnMouseClick (me);
1656                         }
1657                 }
1658                 
1659                 internal void CaptureWithConfine (Control ConfineWindow) {
1660                         if (this.IsHandleCreated && !is_captured) {
1661                                 is_captured = true;
1662                                 XplatUI.GrabWindow (this.window.Handle, ConfineWindow.Handle);
1663                         }
1664                 }
1665
1666                 private void CheckDataBindings () {
1667                         if (data_bindings == null)
1668                                 return;
1669
1670                         foreach (Binding binding in data_bindings) {
1671                                 binding.Check ();
1672                         }
1673                 }
1674
1675                 private void ChangeParent(Control new_parent) {
1676                         bool            pre_enabled;
1677                         bool            pre_visible;
1678                         Font            pre_font;
1679                         Color           pre_fore_color;
1680                         Color           pre_back_color;
1681                         RightToLeft     pre_rtl;
1682
1683                         // These properties are inherited from our parent
1684                         // Get them pre parent-change and then send events
1685                         // if they are changed after we have our new parent
1686                         pre_enabled = Enabled;
1687                         pre_visible = Visible;
1688                         pre_font = Font;
1689                         pre_fore_color = ForeColor;
1690                         pre_back_color = BackColor;
1691                         pre_rtl = RightToLeft;
1692                         // MS doesn't seem to send a CursorChangedEvent
1693
1694                         parent = new_parent;
1695
1696                         Form frm = this as Form;
1697                         if (frm != null) {
1698                                 frm.ChangingParent (new_parent);
1699                         } else if (IsHandleCreated) {
1700                                 IntPtr parent_handle = IntPtr.Zero;
1701                                 if (new_parent != null && new_parent.IsHandleCreated)
1702                                         parent_handle = new_parent.Handle;
1703                                 XplatUI.SetParent (Handle, parent_handle);
1704                         }
1705                         
1706                         OnParentChanged(EventArgs.Empty);
1707
1708                         if (pre_enabled != Enabled) {
1709                                 OnEnabledChanged(EventArgs.Empty);
1710                         }
1711
1712                         if (pre_visible != Visible) {
1713                                 OnVisibleChanged(EventArgs.Empty);
1714                         }
1715
1716                         if (pre_font != Font) {
1717                                 OnFontChanged(EventArgs.Empty);
1718                         }
1719
1720                         if (pre_fore_color != ForeColor) {
1721                                 OnForeColorChanged(EventArgs.Empty);
1722                         }
1723
1724                         if (pre_back_color != BackColor) {
1725                                 OnBackColorChanged(EventArgs.Empty);
1726                         }
1727
1728                         if (pre_rtl != RightToLeft) {
1729                                 // MS sneaks a OnCreateControl and OnHandleCreated in here, I guess
1730                                 // because when RTL changes they have to recreate the win32 control
1731                                 // We don't really need that (until someone runs into compatibility issues)
1732                                 OnRightToLeftChanged(EventArgs.Empty);
1733                         }
1734
1735                         if ((new_parent != null) && new_parent.Created && is_visible && !Created) {
1736                                 CreateControl();
1737                         }
1738
1739                         if ((binding_context == null) && Created) {
1740                                 OnBindingContextChanged(EventArgs.Empty);
1741                         }
1742                 }
1743
1744                 // Sometimes we need to do this calculation without it being virtual (constructor)
1745                 internal Size InternalSizeFromClientSize (Size clientSize)
1746                 {
1747                         Rectangle ClientRect;
1748                         Rectangle WindowRect;
1749                         CreateParams cp;
1750
1751                         ClientRect = new Rectangle (0, 0, clientSize.Width, clientSize.Height);
1752                         cp = this.CreateParams;
1753
1754                         if (XplatUI.CalculateWindowRect (ref ClientRect, cp, null, out WindowRect))
1755                                 return new Size (WindowRect.Width, WindowRect.Height);
1756
1757                         return Size.Empty;
1758                 }
1759                 
1760                 internal Size ClientSizeFromSize (Size size)
1761                 {
1762                         // Calling this gives us the difference in Size and ClientSize.
1763                         // We just have to apply that difference to our given size.
1764                         Size client_size = this.InternalSizeFromClientSize (size);
1765                         
1766                         if (client_size == Size.Empty)
1767                                 return Size.Empty;
1768                                 
1769                         return new Size (size.Width - (client_size.Width - size.Width), size.Height - (client_size.Height - size.Height));
1770                 }
1771                 
1772                 internal CreateParams GetCreateParams ()
1773                 {
1774                         return CreateParams;
1775                 }
1776
1777                 internal virtual Size GetPreferredSizeCore (Size proposedSize)
1778                 {
1779                         return this.explicit_bounds.Size;
1780                 }
1781
1782                 private void UpdateDistances() {
1783                         if (parent != null) {
1784                                 if (bounds.Width >= 0)
1785                                         dist_right = parent.ClientSize.Width - bounds.X - bounds.Width;
1786                                 if (bounds.Height >= 0)
1787                                         dist_bottom = parent.ClientSize.Height - bounds.Y - bounds.Height;
1788
1789                                 recalculate_distances = false;
1790                         }
1791                 }
1792                 
1793                 private Cursor GetAvailableCursor ()
1794                 {
1795                         if (Cursor != null && Enabled) {
1796                                 return Cursor;
1797                         }
1798
1799                         if (Parent != null) {
1800                                 return Parent.GetAvailableCursor ();
1801                         }
1802
1803                         return Cursors.Default;
1804                 }
1805                 
1806                 private void UpdateCursor ()
1807                 {
1808                         if (!IsHandleCreated)
1809                                 return;
1810                         
1811                         if (!Enabled) {
1812                                 XplatUI.SetCursor (window.Handle, GetAvailableCursor ().handle);
1813                                 return;
1814                         }
1815
1816                         Point pt = PointToClient (Cursor.Position);
1817
1818                         if (!bounds.Contains (pt) && !Capture)
1819                                 return;
1820
1821                         if (cursor != null || use_wait_cursor) {
1822                                 XplatUI.SetCursor (window.Handle, Cursor.handle);
1823                         } else {
1824                                 XplatUI.SetCursor (window.Handle, GetAvailableCursor ().handle);
1825                         }
1826                 }
1827                 
1828                 private bool UseDoubleBuffering {
1829                         get {
1830                                 if (!ThemeEngine.Current.DoubleBufferingSupported)
1831                                         return false;
1832
1833                                 // Since many of .Net's controls are unmanaged, they are doublebuffered
1834                                 // even though their bits may not be set in managed land.  This allows
1835                                 // us to doublebuffer as well without affecting public style bits.
1836                                 if (force_double_buffer)
1837                                         return true;
1838                                         
1839                                 if (DoubleBuffered)
1840                                         return true;
1841                                 return (control_style & ControlStyles.DoubleBuffer) != 0;
1842                         }
1843                 }
1844
1845                 internal void OnSizeInitializedOrChanged ()
1846                 {
1847                         Form form = this as Form;
1848                         if (form != null && form.WindowManager != null)
1849                                 ThemeEngine.Current.ManagedWindowOnSizeInitializedOrChanged (form);
1850                 }
1851                 #endregion      // Private & Internal Methods
1852
1853                 #region Public Static Properties
1854                 public static Color DefaultBackColor {
1855                         get {
1856                                 return ThemeEngine.Current.DefaultControlBackColor;
1857                         }
1858                 }
1859
1860                 public static Font DefaultFont {
1861                         get {
1862                                 return ThemeEngine.Current.DefaultFont;
1863                         }
1864                 }
1865
1866                 public static Color DefaultForeColor {
1867                         get {
1868                                 return ThemeEngine.Current.DefaultControlForeColor;
1869                         }
1870                 }
1871
1872                 public static Keys ModifierKeys {
1873                         get {
1874                                 return XplatUI.State.ModifierKeys;
1875                         }
1876                 }
1877
1878                 public static MouseButtons MouseButtons {
1879                         get {
1880                                 return XplatUI.State.MouseButtons;
1881                         }
1882                 }
1883
1884                 public static Point MousePosition {
1885                         get {
1886                                 return Cursor.Position;
1887                         }
1888                 }
1889                 
1890                 [EditorBrowsable (EditorBrowsableState.Advanced)]
1891                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
1892                 [Browsable (false)]
1893                 [MonoTODO ("Stub, value is not used")]
1894                 public static bool CheckForIllegalCrossThreadCalls 
1895                 {
1896                         get {
1897                                 return verify_thread_handle;
1898                         }
1899
1900                         set {
1901                                 verify_thread_handle = value;
1902                         }
1903                 }
1904                 #endregion      // Public Static Properties
1905
1906                 #region Public Instance Properties
1907                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1908                 [Browsable(false)]
1909                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1910                 public AccessibleObject AccessibilityObject {
1911                         get {
1912                                 if (accessibility_object==null) {
1913                                         accessibility_object=CreateAccessibilityInstance();
1914                                 }
1915                                 return accessibility_object;
1916                         }
1917                 }
1918
1919                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1920                 [Browsable(false)]
1921                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1922                 public string AccessibleDefaultActionDescription {
1923                         get {
1924                                 return accessible_default_action;
1925                         }
1926
1927                         set {
1928                                 accessible_default_action = value;
1929                         }
1930                 }
1931
1932                 [Localizable(true)]
1933                 [DefaultValue(null)]
1934                 [MWFCategory("Accessibility")]
1935                 public string AccessibleDescription {
1936                         get {
1937                                 return accessible_description;
1938                         }
1939
1940                         set {
1941                                 accessible_description = value;
1942                         }
1943                 }
1944
1945                 [Localizable(true)]
1946                 [DefaultValue(null)]
1947                 [MWFCategory("Accessibility")]
1948                 public string AccessibleName {
1949                         get {
1950                                 return accessible_name;
1951                         }
1952
1953                         set {
1954                                 accessible_name = value;
1955                         }
1956                 }
1957
1958                 [DefaultValue(AccessibleRole.Default)]
1959                 [MWFDescription("Role of the control"), MWFCategory("Accessibility")]
1960                 public AccessibleRole AccessibleRole {
1961                         get {
1962                                 return accessible_role;
1963                         }
1964
1965                         set {
1966                                 accessible_role = value;
1967                         }
1968                 }
1969
1970                 [DefaultValue(false)]
1971                 [MWFCategory("Behavior")]
1972                 public virtual bool AllowDrop {
1973                         get {
1974                                 return allow_drop;
1975                         }
1976
1977                         set {
1978                                 if (allow_drop == value)
1979                                         return;
1980                                 allow_drop = value;
1981                                 if (IsHandleCreated) {
1982                                         UpdateStyles();
1983                                         XplatUI.SetAllowDrop (Handle, value);
1984                                 }
1985                         }
1986                 }
1987
1988                 [Localizable(true)]
1989                 [RefreshProperties(RefreshProperties.Repaint)]
1990                 [DefaultValue(AnchorStyles.Top | AnchorStyles.Left)]
1991                 [MWFCategory("Layout")]
1992                 public virtual AnchorStyles Anchor {
1993                         get {
1994                                 return anchor_style;
1995                         }
1996
1997                         set {
1998                                 layout_type = LayoutType.Anchor;
1999
2000                                 if (anchor_style == value)
2001                                         return;
2002                                         
2003                                 anchor_style=value;
2004                                 dock_style = DockStyle.None;
2005                                 
2006                                 UpdateDistances ();
2007
2008                                 if (parent != null)
2009                                         parent.PerformLayout(this, "Anchor");
2010                         }
2011                 }
2012
2013                 [Browsable (false)]
2014                 [DefaultValue (typeof (Point), "0, 0")]
2015                 [EditorBrowsable (EditorBrowsableState.Advanced)]
2016                 public virtual Point AutoScrollOffset {
2017                         get {
2018                                 return auto_scroll_offset;
2019                         }
2020
2021                         set {
2022                                 this.auto_scroll_offset = value;
2023                         }
2024                 }
2025                         
2026                 // XXX: Implement me!
2027                 bool auto_size;
2028                 
2029                 [RefreshProperties (RefreshProperties.All)]
2030                 [Localizable (true)]
2031                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
2032                 [Browsable (false)]
2033                 [EditorBrowsable (EditorBrowsableState.Never)]
2034                 [DefaultValue (false)]
2035                 public virtual bool AutoSize {
2036                         get { return auto_size; }
2037                         set {
2038                                 if (this.auto_size != value) {
2039                                         auto_size = value;
2040                                         
2041                                         // If we're turning this off, reset our size
2042                                         if (!value) {
2043                                                 Size = explicit_bounds.Size;
2044                                         } else {
2045                                                 if (Parent != null)
2046                                                         Parent.PerformLayout (this, "AutoSize");
2047                                         }
2048
2049                                         OnAutoSizeChanged (EventArgs.Empty);
2050                                 }
2051                         }
2052                 }
2053                 
2054                 [AmbientValue ("{Width=0, Height=0}")]
2055                 [MWFCategory("Layout")]
2056                 public virtual Size MaximumSize {
2057                         get {
2058                                 return maximum_size;
2059                         }
2060                         set {
2061                                 if (maximum_size != value) {
2062                                         maximum_size = value;
2063                                         Size = PreferredSize;
2064                                 }
2065                         }
2066                 }
2067
2068                 internal bool ShouldSerializeMaximumSize ()
2069                 {
2070                         return this.MaximumSize != DefaultMaximumSize;
2071                 }
2072
2073                 [MWFCategory("Layout")]
2074                 public virtual Size MinimumSize {
2075                         get {
2076                                 return minimum_size;
2077                         }
2078                         set {
2079                                 if (minimum_size != value) {
2080                                         minimum_size = value;
2081                                         Size = PreferredSize;
2082                                 }
2083                         }
2084                 }
2085
2086                 internal bool ShouldSerializeMinimumSize ()
2087                 {
2088                         return this.MinimumSize != DefaultMinimumSize;
2089                 }
2090
2091                 [DispId(-501)]
2092                 [MWFCategory("Appearance")]
2093                 public virtual Color BackColor {
2094                         get {
2095                                 if (background_color.IsEmpty) {
2096                                         if (parent!=null) {
2097                                                 Color pcolor = parent.BackColor;
2098                                                 if (pcolor.A == 0xff || GetStyle(ControlStyles.SupportsTransparentBackColor))
2099                                                         return pcolor;
2100                                         }
2101                                         return DefaultBackColor;
2102                                 }
2103                                 return background_color;
2104                         }
2105
2106                         set {
2107                                 if (!value.IsEmpty && (value.A != 0xff) && !GetStyle(ControlStyles.SupportsTransparentBackColor)) {
2108                                         throw new ArgumentException("Transparent background colors are not supported on this control");
2109                                 }
2110
2111                                 if (background_color != value) {
2112                                         background_color=value;
2113                                         SetChildColor(this);
2114                                         OnBackColorChanged(EventArgs.Empty);
2115                                         Invalidate();
2116                                 }
2117                         }
2118                 }
2119
2120                 internal bool ShouldSerializeBackColor ()
2121                 {
2122                         return this.BackColor != DefaultBackColor;
2123                 }
2124
2125                 [Localizable(true)]
2126                 [DefaultValue(null)]
2127                 [MWFCategory("Appearance")]
2128                 public virtual Image BackgroundImage {
2129                         get {
2130                                 return background_image;
2131                         }
2132
2133                         set {
2134                                 if (background_image!=value) {
2135                                         background_image=value;
2136                                         OnBackgroundImageChanged(EventArgs.Empty);
2137                                         Invalidate ();
2138                                 }
2139                         }
2140                 }
2141
2142                 [DefaultValue (ImageLayout.Tile)]
2143                 [Localizable (true)]
2144                 [MWFCategory("Appearance")]
2145                 public virtual ImageLayout BackgroundImageLayout {
2146                         get {
2147                                 return backgroundimage_layout;
2148                         }
2149                         set {
2150                                 if (Array.IndexOf (Enum.GetValues (typeof (ImageLayout)), value) == -1)
2151                                         throw new InvalidEnumArgumentException ("value", (int) value, typeof(ImageLayout));
2152
2153                                 if (value != backgroundimage_layout) {
2154                                         backgroundimage_layout = value;
2155                                         Invalidate ();
2156                                         OnBackgroundImageLayoutChanged (EventArgs.Empty);
2157                                 }
2158                                 
2159                         }
2160                 } 
2161
2162                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2163                 [Browsable(false)]
2164                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2165                 public virtual BindingContext BindingContext {
2166                         get {
2167                                 if (binding_context != null)
2168                                         return binding_context;
2169                                 if (Parent == null)
2170                                         return null;
2171                                 binding_context = Parent.BindingContext;
2172                                 return binding_context;
2173                         }
2174                         set {
2175                                 if (binding_context != value) {
2176                                         binding_context = value;
2177                                         OnBindingContextChanged(EventArgs.Empty);
2178                                 }
2179                         }
2180                 }
2181
2182                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2183                 [Browsable(false)]
2184                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2185                 public int Bottom {
2186                         get {
2187                                 return this.bounds.Bottom;
2188                         }
2189                 }
2190
2191                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2192                 [Browsable(false)]
2193                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2194                 public Rectangle Bounds {
2195                         get {
2196                                 return this.bounds;
2197                         }
2198
2199                         set {
2200                                 SetBounds(value.Left, value.Top, value.Width, value.Height, BoundsSpecified.All);
2201                         }
2202                 }
2203
2204                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2205                 [Browsable(false)]
2206                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2207                 public bool CanFocus {
2208                         get {
2209                                 if (IsHandleCreated && Visible && Enabled) {
2210                                         return true;
2211                                 }
2212                                 return false;
2213                         }
2214                 }
2215
2216                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2217                 [Browsable(false)]
2218                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2219                 public bool CanSelect {
2220                         get {
2221                                 Control parent;
2222
2223                                 if (!GetStyle(ControlStyles.Selectable)) {
2224                                         return false;
2225                                 }
2226
2227                                 parent = this;
2228                                 while (parent != null) {
2229                                         if (!parent.is_visible || !parent.is_enabled) {
2230                                                 return false;
2231                                         }
2232
2233                                         parent = parent.parent;
2234                                 }
2235                                 return true;
2236                         }
2237                 }
2238
2239                 internal virtual bool InternalCapture {
2240                         get {
2241                                 return Capture;
2242                         }
2243
2244                         set {
2245                                 Capture = value;
2246                         }
2247                 }
2248
2249                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2250                 [Browsable(false)]
2251                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2252                 public bool Capture {
2253                         get {
2254                                 return this.is_captured;
2255                         }
2256
2257                         set {
2258                                 // Call OnMouseCaptureChanged when we get WM_CAPTURECHANGED.
2259                                 if (value != is_captured) {
2260                                         if (value) {
2261                                                 is_captured = true;
2262                                                 XplatUI.GrabWindow(Handle, IntPtr.Zero);
2263                                         } else {
2264                                                 if (IsHandleCreated)
2265                                                         XplatUI.UngrabWindow(Handle);
2266                                                 is_captured = false;
2267                                         }
2268                                 }
2269                         }
2270                 }
2271
2272                 [DefaultValue(true)]
2273                 [MWFCategory("Focus")]
2274                 public bool CausesValidation {
2275                         get {
2276                                 return this.causes_validation;
2277                         }
2278
2279                         set {
2280                                 if (this.causes_validation != value) {
2281                                         causes_validation = value;
2282                                         OnCausesValidationChanged(EventArgs.Empty);
2283                                 }
2284                         }
2285                 }
2286
2287                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2288                 [Browsable(false)]
2289                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2290                 public Rectangle ClientRectangle {
2291                         get {
2292                                 client_rect.Width = client_size.Width;
2293                                 client_rect.Height = client_size.Height;
2294                                 return client_rect;
2295                         }
2296                 }
2297
2298                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2299                 [Browsable(false)]
2300                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2301                 public Size ClientSize {
2302                         get {
2303 #if notneeded
2304                                 if ((this is Form) && (((Form)this).form_parent_window != null)) {
2305                                         return ((Form)this).form_parent_window.ClientSize;
2306                                 }
2307 #endif
2308
2309                                 return client_size;
2310                         }
2311
2312                         set {
2313                                 this.SetClientSizeCore(value.Width, value.Height);
2314                                 this.OnClientSizeChanged (EventArgs.Empty);
2315                         }
2316                 }
2317
2318                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2319                 [Browsable(false)]
2320                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2321                 [DescriptionAttribute("ControlCompanyNameDescr")]
2322                 public String CompanyName {
2323                         get {
2324                                 return "Mono Project, Novell, Inc.";
2325                         }
2326                 }
2327
2328                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2329                 [Browsable(false)]
2330                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2331                 public bool ContainsFocus {
2332                         get {
2333                                 IntPtr focused_window;
2334
2335                                 focused_window = XplatUI.GetFocus();
2336                                 if (IsHandleCreated) {
2337                                         if (focused_window == Handle) {
2338                                                 return true;
2339                                         }
2340
2341                                         for (int i=0; i < child_controls.Count; i++) {
2342                                                 if (child_controls[i].ContainsFocus) {
2343                                                         return true;
2344                                                 }
2345                                         }
2346                                 }
2347                                 return false;
2348                         }
2349                 }
2350                 [Browsable (false)]
2351                 [DefaultValue(null)]
2352                 [MWFCategory("Behavior")]
2353                 public virtual ContextMenu ContextMenu {
2354                         get {
2355                                 return ContextMenuInternal;
2356                         }
2357
2358                         set {
2359                                 ContextMenuInternal = value;
2360                         }
2361                 }
2362
2363                 internal virtual ContextMenu ContextMenuInternal {
2364                         get {
2365                                 return context_menu;
2366                         }
2367                         set {
2368                                 if (context_menu != value) {
2369                                         context_menu = value;
2370                                         OnContextMenuChanged (EventArgs.Empty);
2371                                 }
2372                         }
2373                 }
2374
2375                 [DefaultValue (null)]
2376                 [MWFCategory("Behavior")]
2377                 public virtual ContextMenuStrip ContextMenuStrip {
2378                         get { return this.context_menu_strip; }
2379                         set { 
2380                                 if (this.context_menu_strip != value) {
2381                                         this.context_menu_strip = value;
2382                                         if (value != null)
2383                                                 value.container = this;
2384                                         OnContextMenuStripChanged (EventArgs.Empty);
2385                                 }
2386                         }
2387                 }
2388
2389                 [Browsable(false)]
2390                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
2391                 public ControlCollection Controls {
2392                         get {
2393                                 return this.child_controls;
2394                         }
2395                 }
2396
2397                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2398                 [Browsable(false)]
2399                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2400                 public bool Created {
2401                         get {
2402                                 return (!is_disposed && is_created);
2403                         }
2404                 }
2405                 
2406                 [AmbientValue(null)]
2407                 [MWFCategory("Appearance")]
2408                 public virtual Cursor Cursor {
2409                         get {
2410                                 if (use_wait_cursor)
2411                                         return Cursors.WaitCursor;
2412
2413                                 if (cursor != null) {
2414                                         return cursor;
2415                                 }
2416
2417                                 if (parent != null) {
2418                                         return parent.Cursor;
2419                                 }
2420
2421                                 return Cursors.Default;
2422                         }
2423
2424                         set {
2425                                 if (cursor == value) {
2426                                         return;
2427                                 }
2428
2429                                 cursor = value;
2430                                 UpdateCursor ();
2431
2432                                 OnCursorChanged (EventArgs.Empty);
2433                         }
2434                 }
2435
2436                 internal bool ShouldSerializeCursor ()
2437                 {
2438                         return this.Cursor != Cursors.Default;
2439                 }
2440
2441                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
2442                 [ParenthesizePropertyName(true)]
2443                 [RefreshProperties(RefreshProperties.All)]
2444                 [MWFCategory("Data")]
2445                 public ControlBindingsCollection DataBindings {
2446                         get {
2447                                 if (data_bindings == null)
2448                                         data_bindings = new ControlBindingsCollection (this);
2449                                 return data_bindings;
2450                         }
2451                 }
2452
2453                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2454                 [Browsable(false)]
2455                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2456                 public virtual Rectangle DisplayRectangle {
2457                         get {
2458                                 return ClientRectangle;
2459                         }
2460                 }
2461
2462                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2463                 [Browsable(false)]
2464                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2465                 public bool Disposing {
2466                         get {
2467                                 return is_disposed;
2468                         }
2469                 }
2470
2471                 [Localizable(true)]
2472                 [RefreshProperties(RefreshProperties.Repaint)]
2473                 [DefaultValue(DockStyle.None)]
2474                 [MWFCategory("Layout")]
2475                 public virtual DockStyle Dock {
2476                         get {
2477                                 return dock_style;
2478                         }
2479
2480                         set {
2481                                 // If the user sets this to None, we need to still use Anchor layout
2482                                 if (value != DockStyle.None)
2483                                         layout_type = LayoutType.Dock;
2484
2485                                 if (dock_style == value) {
2486                                         return;
2487                                 }
2488
2489                                 if (!Enum.IsDefined (typeof (DockStyle), value)) {
2490                                         throw new InvalidEnumArgumentException ("value", (int) value,
2491                                                 typeof (DockStyle));
2492                                 }
2493
2494                                 dock_style = value;
2495                                 anchor_style = AnchorStyles.Top | AnchorStyles.Left;
2496
2497                                 if (dock_style == DockStyle.None) {
2498                                         bounds = explicit_bounds;
2499                                         layout_type = LayoutType.Anchor;
2500                                 }
2501
2502                                 if (parent != null)
2503                                         parent.PerformLayout(this, "Dock");
2504                                 else if (Controls.Count > 0)
2505                                         PerformLayout ();
2506
2507                                 OnDockChanged(EventArgs.Empty);
2508                         }
2509                 }
2510
2511                 protected virtual bool DoubleBuffered {
2512                         get {
2513                                 return (control_style & ControlStyles.OptimizedDoubleBuffer) != 0;
2514                         }
2515
2516                         set {
2517                                 if (value == DoubleBuffered)
2518                                         return;
2519                                 if (value) {
2520                                         SetStyle (ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);
2521                                 } else {
2522                                         SetStyle (ControlStyles.OptimizedDoubleBuffer, false);
2523                                 }
2524                                 
2525                         }
2526                 }
2527                 
2528                 public void DrawToBitmap (Bitmap bitmap, Rectangle targetBounds)
2529                 {
2530                         Graphics g = Graphics.FromImage (bitmap);
2531                         
2532                         // Only draw within the target bouds, and up to the size of the control
2533                         g.IntersectClip (targetBounds);
2534                         g.IntersectClip (Bounds);
2535                         
2536                         // Logic copied from WmPaint
2537                         PaintEventArgs pea = new PaintEventArgs (g, targetBounds);
2538                         
2539                         if (!GetStyle (ControlStyles.Opaque))
2540                                 OnPaintBackground (pea);
2541
2542                         OnPaintBackgroundInternal (pea);
2543
2544                         OnPaintInternal (pea);
2545
2546                         if (!pea.Handled)
2547                                 OnPaint (pea);
2548                         
2549                         g.Dispose ();
2550                 }
2551                 
2552                 [DispId(-514)]
2553                 [Localizable(true)]
2554                 [MWFCategory("Behavior")]
2555                 public bool Enabled {
2556                         get {
2557                                 if (!is_enabled) {
2558                                         return false;
2559                                 }
2560
2561                                 if (parent != null) {
2562                                         return parent.Enabled;
2563                                 }
2564
2565                                 return true;
2566                         }
2567
2568                         set {
2569                                 if (this.is_enabled == value)
2570                                         return;
2571
2572                                 bool old_value = is_enabled;
2573
2574                                 is_enabled = value;
2575
2576                                 if (!value)
2577                                         UpdateCursor ();
2578
2579                                 if (old_value != value && !value && this.has_focus)
2580                                         SelectNextControl(this, true, true, true, true);
2581
2582                                 OnEnabledChanged (EventArgs.Empty);
2583                         }
2584                 }
2585
2586                 internal bool ShouldSerializeEnabled ()
2587                 {
2588                         return this.Enabled != true;
2589                 }
2590
2591                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2592                 [Browsable(false)]
2593                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2594                 public virtual bool Focused {
2595                         get {
2596                                 return this.has_focus;
2597                         }
2598                 }
2599
2600                 [DispId(-512)]
2601                 [AmbientValue(null)]
2602                 [Localizable(true)]
2603                 [MWFCategory("Appearance")]
2604                 public virtual Font Font {
2605                         [return: MarshalAs (UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof (Font))]
2606                         get {
2607                                 if (font != null)
2608                                         return font;
2609
2610                                 if (parent != null) {
2611                                         Font f = parent.Font;
2612                                         
2613                                         if (f != null)
2614                                                 return f;
2615                                 }
2616
2617                                 return DefaultFont;
2618                         }
2619
2620                         [param:MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(Font))]
2621                         set {
2622                                 if (font != null && font == value) {
2623                                         return;
2624                                 }
2625
2626                                 font = value;
2627                                 Invalidate();
2628                                 OnFontChanged (EventArgs.Empty);
2629                                 PerformLayout ();
2630                         }
2631                 }
2632
2633                 internal bool ShouldSerializeFont ()
2634                 {
2635                         return !this.Font.Equals (DefaultFont);
2636                 }
2637
2638                 [DispId(-513)]
2639                 [MWFCategory("Appearance")]
2640                 public virtual Color ForeColor {
2641                         get {
2642                                 if (foreground_color.IsEmpty) {
2643                                         if (parent!=null) {
2644                                                 return parent.ForeColor;
2645                                         }
2646                                         return DefaultForeColor;
2647                                 }
2648                                 return foreground_color;
2649                         }
2650
2651                         set {
2652                                 if (foreground_color != value) {
2653                                         foreground_color=value;
2654                                         Invalidate();
2655                                         OnForeColorChanged(EventArgs.Empty);
2656                                 }
2657                         }
2658                 }
2659
2660                 internal bool ShouldSerializeForeColor ()
2661                 {
2662                         return this.ForeColor != DefaultForeColor;
2663                 }
2664
2665                 [DispId(-515)]
2666                 [Browsable(false)]
2667                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2668                 public IntPtr Handle {                                                  // IWin32Window
2669                         get {
2670                                 if (verify_thread_handle) {
2671                                         if (this.InvokeRequired) {
2672                                                 throw new InvalidOperationException("Cross-thread access of handle detected. Handle access only valid on thread that created the control");
2673                                         }
2674                                 }
2675                                 if (!IsHandleCreated) {
2676                                         CreateHandle();
2677                                 }
2678                                 return window.Handle;
2679                         }
2680                 }
2681
2682                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2683                 [Browsable(false)]
2684                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2685                 public bool HasChildren {
2686                         get {
2687                                 if (this.child_controls.Count>0) {
2688                                         return true;
2689                                 }
2690                                 return false;
2691                         }
2692                 }
2693
2694                 [EditorBrowsable(EditorBrowsableState.Always)]
2695                 [Browsable(false)]
2696                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2697                 public int Height {
2698                         get { return this.bounds.Height; }
2699                         set { SetBounds(bounds.X, bounds.Y, bounds.Width, value, BoundsSpecified.Height); }
2700                 }
2701                 
2702                 [AmbientValue(ImeMode.Inherit)]
2703                 [Localizable(true)]
2704                 [MWFCategory("Behavior")]
2705                 public ImeMode ImeMode {
2706                         get {
2707                                 if (ime_mode == ImeMode.Inherit) {
2708                                         if (parent != null)
2709                                                 return parent.ImeMode;
2710                                         else
2711                                                 return ImeMode.NoControl; // default value
2712                                 }
2713                                 return ime_mode;
2714                         }
2715
2716                         set {
2717                                 if (ime_mode != value) {
2718                                         ime_mode = value;
2719
2720                                         OnImeModeChanged(EventArgs.Empty);
2721                                 }
2722                         }
2723                 }
2724
2725                 internal bool ShouldSerializeImeMode ()
2726                 {
2727                         return this.ImeMode != ImeMode.NoControl;
2728                 }
2729
2730                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2731                 [Browsable(false)]
2732                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2733                 public bool InvokeRequired {                                            // ISynchronizeInvoke
2734                         get {
2735                                 if (creator_thread != null && creator_thread!=Thread.CurrentThread) {
2736                                         return true;
2737                                 }
2738                                 return false;
2739                         }
2740                 }
2741
2742                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2743                 [Browsable(false)]
2744                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2745                 public bool IsAccessible {
2746                         get {
2747                                 return is_accessible;
2748                         }
2749
2750                         set {
2751                                 is_accessible = value;
2752                         }
2753                 }
2754
2755                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2756                 [Browsable(false)]
2757                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2758                 public bool IsDisposed {
2759                         get {
2760                                 return this.is_disposed;
2761                         }
2762                 }
2763
2764                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2765                 [Browsable(false)]
2766                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2767                 public bool IsHandleCreated {
2768                         get {
2769                                 if (window == null || window.Handle == IntPtr.Zero)
2770                                         return false;
2771
2772                                 Hwnd hwnd = Hwnd.ObjectFromHandle (window.Handle);
2773                                 if (hwnd != null && hwnd.zombie)
2774                                         return false;
2775
2776                                 return true;
2777                         }
2778                 }
2779
2780                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2781                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2782                 [Browsable(false)]
2783                 [MonoNotSupported ("RTL is not supported")]
2784                 public bool IsMirrored {
2785                         get { return false; }
2786                 }
2787
2788                 [Browsable (false)]
2789                 [EditorBrowsable (EditorBrowsableState.Advanced)]
2790                 public virtual Layout.LayoutEngine LayoutEngine {
2791                         get {
2792                                 if (layout_engine == null)
2793                                         layout_engine = new Layout.DefaultLayout ();
2794                                 return layout_engine;
2795                         }
2796                 }
2797
2798                 [EditorBrowsable(EditorBrowsableState.Always)]
2799                 [Browsable(false)]
2800                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2801                 public int Left {
2802                         get {
2803                                 return this.bounds.Left;
2804                         }
2805
2806                         set {
2807                                 SetBounds(value, bounds.Y, bounds.Width, bounds.Height, BoundsSpecified.X);
2808                         }
2809                 }
2810
2811                 [Localizable(true)]
2812                 [MWFCategory("Layout")]
2813                 public Point Location {
2814                         get {
2815                                 return this.bounds.Location;
2816                         }
2817
2818                         set {
2819                                 SetBounds(value.X, value.Y, bounds.Width, bounds.Height, BoundsSpecified.Location);
2820                         }
2821                 }
2822
2823                 internal bool ShouldSerializeLocation ()
2824                 {
2825                         return this.Location != new Point (0, 0);
2826                 }
2827
2828                 [Localizable (true)]
2829                 [MWFCategory("Layout")]
2830                 public Padding Margin {
2831                         get { return this.margin; }
2832                         set { 
2833                                 if (this.margin != value) {
2834                                         this.margin = value; 
2835                                         if (Parent != null)
2836                                                 Parent.PerformLayout (this, "Margin");
2837                                         OnMarginChanged (EventArgs.Empty);
2838                                 }
2839                         }
2840                 }
2841
2842                 internal bool ShouldSerializeMargin ()
2843                 {
2844                         return this.Margin != DefaultMargin;
2845                 }
2846
2847                 [Browsable(false)]
2848                 public string Name {
2849                         get {
2850                                 return name;
2851                         }
2852
2853                         set {
2854                                 name = value;
2855                         }
2856                 }
2857
2858                 [Localizable(true)]
2859                 [MWFCategory("Layout")]
2860                 public Padding Padding {
2861                         get {
2862                                 return padding;
2863                         }
2864
2865                         set {
2866                                 if (padding != value) {
2867                                         padding = value;
2868                                         OnPaddingChanged (EventArgs.Empty);
2869                                         
2870                                         // Changing padding generally requires a new size
2871                                         if (this.AutoSize && this.Parent != null)
2872                                                 parent.PerformLayout (this, "Padding");
2873                                         else
2874                                                 PerformLayout (this, "Padding");
2875                                 }
2876                         }
2877                 }
2878
2879                 internal bool ShouldSerializePadding ()
2880                 {
2881                         return this.Padding != DefaultPadding;
2882                 }
2883
2884                 [Browsable(false)]
2885                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2886                 public Control Parent {
2887                         get {
2888                                 return this.parent;
2889                         }
2890
2891                         set {
2892                                 if (value == this) {
2893                                         throw new ArgumentException("A circular control reference has been made. A control cannot be owned or parented to itself.");
2894                                 }
2895
2896                                 if (parent!=value) {
2897                                         if (value==null) {
2898                                                 parent.Controls.Remove(this);
2899                                                 parent = null;
2900                                                 return;
2901                                         }
2902
2903                                         value.Controls.Add(this);
2904                                 }
2905                         }
2906                 }
2907
2908                 [Browsable (false)]
2909                 public Size PreferredSize {
2910                         get { return this.GetPreferredSize (Size.Empty); }
2911                 }
2912
2913                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2914                 [Browsable(false)]
2915                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2916                 public string ProductName {
2917                         get {
2918                                 Type t = typeof (AssemblyProductAttribute);
2919                                 Assembly assembly = GetType().Module.Assembly;
2920                                 object [] attrs = assembly.GetCustomAttributes (t, false);
2921                                 AssemblyProductAttribute a = null;
2922                                 // On MS we get a NullRefException if product attribute is not
2923                                 // set. 
2924                                 if (attrs != null && attrs.Length > 0)
2925                                         a = (AssemblyProductAttribute) attrs [0];
2926                                 if (a == null) {
2927                                         return GetType ().Namespace;
2928                                 }
2929                                 return a.Product;
2930                         }
2931                 }
2932
2933                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2934                 [Browsable(false)]
2935                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2936                 public string ProductVersion {
2937                         get {
2938                                 Type t = typeof (AssemblyVersionAttribute);
2939                                 Assembly assembly = GetType().Module.Assembly;
2940                                 object [] attrs = assembly.GetCustomAttributes (t, false);
2941                                 if (attrs == null || attrs.Length < 1)
2942                                         return "1.0.0.0";
2943                                 return ((AssemblyVersionAttribute)attrs [0]).Version;
2944                         }
2945                 }
2946
2947                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2948                 [Browsable(false)]
2949                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2950                 public bool RecreatingHandle {
2951                         get {
2952                                 return is_recreating;
2953                         }
2954                 }
2955
2956                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2957                 [Browsable(false)]
2958                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2959                 public Region Region {
2960                         get {
2961                                 return clip_region;
2962                         }
2963
2964                         set {
2965                                 if (clip_region != value) {
2966                                         if (IsHandleCreated)
2967                                                 XplatUI.SetClipRegion(Handle, value);
2968
2969                                         clip_region = value;
2970                                         
2971                                         OnRegionChanged (EventArgs.Empty);
2972                                 }
2973                         }
2974                 }
2975
2976                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2977                 [Browsable(false)]
2978                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2979                 public int Right {
2980                         get {
2981                                 return this.bounds.Right;
2982                         }
2983                 }
2984
2985                 [AmbientValue(RightToLeft.Inherit)]
2986                 [Localizable(true)]
2987                 [MWFCategory("Appearance")]
2988                 public virtual RightToLeft RightToLeft {
2989                         get {
2990                                 if (right_to_left == RightToLeft.Inherit) {
2991                                         if (parent != null)
2992                                                 return parent.RightToLeft;
2993                                         else
2994                                                 return RightToLeft.No; // default value
2995                                 }
2996                                 return right_to_left;
2997                         }
2998
2999                         set {
3000                                 if (value != right_to_left) {
3001                                         right_to_left = value;
3002                                         OnRightToLeftChanged(EventArgs.Empty);
3003                                         PerformLayout ();
3004                                 }
3005                         }
3006                 }
3007
3008                 internal bool ShouldSerializeRightToLeft ()
3009                 {
3010                         return this.RightToLeft != RightToLeft.No;
3011                 }
3012
3013                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3014                 public override ISite Site {
3015                         get {
3016                                 return base.Site;
3017                         }
3018
3019                         set {
3020                                 base.Site = value;
3021
3022                                 if (value != null) {
3023                                         AmbientProperties ap = (AmbientProperties) value.GetService (typeof (AmbientProperties));
3024                                         if (ap != null) {
3025                                                 BackColor = ap.BackColor;
3026                                                 ForeColor = ap.ForeColor;
3027                                                 Cursor = ap.Cursor;
3028                                                 Font = ap.Font;
3029                                         }
3030                                 }
3031                         }
3032                 }
3033
3034                 internal bool ShouldSerializeSite ()
3035                 {
3036                         return false;
3037                 }
3038
3039                 [Localizable(true)]
3040                 [MWFCategory("Layout")]
3041                 public Size Size {
3042                         get {
3043                                 return new Size(Width, Height);
3044                         }
3045
3046                         set {
3047                                 SetBounds(bounds.X, bounds.Y, value.Width, value.Height, BoundsSpecified.Size);
3048                         }
3049                 }
3050
3051                 internal virtual bool ShouldSerializeSize ()
3052                 {
3053                         return this.Size != DefaultSize;
3054                 }
3055
3056                 [Localizable(true)]
3057                 [MergableProperty(false)]
3058                 [MWFCategory("Behavior")]
3059                 public int TabIndex {
3060                         get {
3061                                 if (tab_index != -1) {
3062                                         return tab_index;
3063                                 }
3064                                 return 0;
3065                         }
3066
3067                         set {
3068                                 if (tab_index != value) {
3069                                         tab_index = value;
3070                                         OnTabIndexChanged(EventArgs.Empty);
3071                                 }
3072                         }
3073                 }
3074
3075                 [DispId(-516)]
3076                 [DefaultValue(true)]
3077                 [MWFCategory("Behavior")]
3078                 public bool TabStop {
3079                         get {
3080                                 return tab_stop;
3081                         }
3082
3083                         set {
3084                                 if (tab_stop != value) {
3085                                         tab_stop = value;
3086                                         OnTabStopChanged(EventArgs.Empty);
3087                                 }
3088                         }
3089                 }
3090
3091                 [Localizable(false)]
3092                 [Bindable(true)]
3093                 [TypeConverter(typeof(StringConverter))]
3094                 [DefaultValue(null)]
3095                 [MWFCategory("Data")]
3096                 public object Tag {
3097                         get {
3098                                 return control_tag;
3099                         }
3100
3101                         set {
3102                                 control_tag = value;
3103                         }
3104                 }
3105
3106                 [DispId(-517)]
3107                 [Localizable(true)]
3108                 [BindableAttribute(true)]
3109                 [MWFCategory("Appearance")]
3110                 public virtual string Text {
3111                         get {
3112                                 // Our implementation ignores ControlStyles.CacheText - we always cache
3113                                 return this.text;
3114                         }
3115
3116                         set {
3117                                 if (value == null) {
3118                                         value = String.Empty;
3119                                 }
3120
3121                                 if (text!=value) {
3122                                         text=value;
3123                                         UpdateWindowText ();
3124                                         OnTextChanged (EventArgs.Empty);
3125
3126                                         // Label has its own AutoSize implementation
3127                                         if (AutoSize && Parent != null && (!(this is Label)))
3128                                                 Parent.PerformLayout (this, "Text");
3129                                 }
3130                         }
3131                 }
3132
3133                 internal virtual void UpdateWindowText ()
3134                 {
3135                         if (!IsHandleCreated) {
3136                                 return;
3137                         }
3138                         XplatUI.Text (Handle, text);
3139                 }
3140
3141                 [EditorBrowsable(EditorBrowsableState.Always)]
3142                 [Browsable(false)]
3143                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
3144                 public int Top {
3145                         get {
3146                                 return this.bounds.Top;
3147                         }
3148
3149                         set {
3150                                 SetBounds(bounds.X, value, bounds.Width, bounds.Height, BoundsSpecified.Y);
3151                         }
3152                 }
3153
3154                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3155                 [Browsable(false)]
3156                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
3157                 public Control TopLevelControl {
3158                         get {
3159                                 Control p = this;
3160
3161                                 while (p.parent != null) {
3162                                         p = p.parent;
3163                                 }
3164
3165                                 return p is Form ? p : null;
3166                         }
3167                 }
3168
3169                 [EditorBrowsable(EditorBrowsableState.Always)]
3170                 [Browsable(true)]
3171                 [DefaultValue (false)]
3172                 [MWFCategory("Appearance")]
3173                 public bool UseWaitCursor {
3174                         get { return use_wait_cursor; }
3175                         set {
3176                                 if (use_wait_cursor != value) {
3177                                         use_wait_cursor = value;
3178                                         UpdateCursor ();
3179                                         OnCursorChanged (EventArgs.Empty);
3180                                 }
3181                         }
3182                 }
3183
3184                 [Localizable(true)]
3185                 [MWFCategory("Behavior")]
3186                 public bool Visible {
3187                         get {
3188                                 if (!is_visible) {
3189                                         return false;
3190                                 } else if (parent != null) {
3191                                         return parent.Visible;
3192                                 }
3193
3194                                 return true;
3195                         }
3196
3197                         set {
3198                                 if (this.is_visible != value) {
3199                                         SetVisibleCore(value);
3200
3201                                         if (parent != null)
3202                                                 parent.PerformLayout (this, "Visible");
3203                                 }
3204                         }
3205                 }
3206
3207                 internal bool ShouldSerializeVisible ()
3208                 {
3209                         return this.Visible != true;
3210                 }
3211
3212                 [EditorBrowsable(EditorBrowsableState.Always)]
3213                 [Browsable(false)]
3214                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
3215                 public int Width {
3216                         get {
3217                                 return this.bounds.Width;
3218                         }
3219
3220                         set {
3221                                 SetBounds(bounds.X, bounds.Y, value, bounds.Height, BoundsSpecified.Width);
3222                         }
3223                 }
3224
3225                 [EditorBrowsable(EditorBrowsableState.Never)]
3226                 [Browsable(false)]
3227                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
3228                 public IWindowTarget WindowTarget {
3229                         get { return window_target; }
3230                         set { window_target = value; }
3231                 }
3232                 #endregion      // Public Instance Properties
3233
3234                 #region Protected Instance Properties
3235                 protected virtual bool CanEnableIme {
3236                         get { return false; }
3237                 }
3238                 
3239                 // Is only false in some ActiveX contexts
3240                 protected override bool CanRaiseEvents {
3241                         get { return true; }
3242                 }
3243
3244                 protected virtual CreateParams CreateParams {
3245                         get {
3246                                 CreateParams create_params = new CreateParams();
3247
3248                                 try {
3249                                         create_params.Caption = Text;
3250                                 }
3251                                 catch {
3252                                         create_params.Caption = text;
3253                                 }
3254
3255                                 try {
3256                                         create_params.X = Left;
3257                                 }
3258                                 catch {
3259                                         create_params.X = this.bounds.X;
3260                                 }
3261
3262                                 try {
3263                                         create_params.Y = Top;
3264                                 }
3265                                 catch {
3266                                         create_params.Y = this.bounds.Y;
3267                                 }
3268
3269                                 try {
3270                                         create_params.Width = Width;
3271                                 }
3272                                 catch {
3273                                         create_params.Width = this.bounds.Width;
3274                                 }
3275
3276                                 try {
3277                                         create_params.Height = Height;
3278                                 }
3279                                 catch {
3280                                         create_params.Height = this.bounds.Height;
3281                                 }
3282
3283
3284                                 create_params.ClassName = XplatUI.GetDefaultClassName (GetType ());
3285                                 create_params.ClassStyle = (int)(XplatUIWin32.ClassStyle.CS_OWNDC | XplatUIWin32.ClassStyle.CS_DBLCLKS);
3286                                 create_params.ExStyle = 0;
3287                                 create_params.Param = 0;
3288
3289                                 if (allow_drop) {
3290                                         create_params.ExStyle |= (int)WindowExStyles.WS_EX_ACCEPTFILES;
3291                                 }
3292
3293                                 if ((parent!=null) && (parent.IsHandleCreated)) {
3294                                         create_params.Parent = parent.Handle;
3295                                 }
3296
3297                                 create_params.Style = (int)WindowStyles.WS_CHILD | (int)WindowStyles.WS_CLIPCHILDREN | (int)WindowStyles.WS_CLIPSIBLINGS;
3298
3299                                 if (is_visible) {
3300                                         create_params.Style |= (int)WindowStyles.WS_VISIBLE;
3301                                 }
3302
3303                                 if (!is_enabled) {
3304                                         create_params.Style |= (int)WindowStyles.WS_DISABLED;
3305                                 }
3306
3307                                 switch (border_style) {
3308                                         case BorderStyle.FixedSingle:
3309                                                 create_params.Style |= (int) WindowStyles.WS_BORDER;
3310                                                 break;
3311                                         case BorderStyle.Fixed3D:
3312                                                 create_params.ExStyle |= (int) WindowExStyles.WS_EX_CLIENTEDGE;
3313                                                 break;
3314                                 }
3315                                 
3316                                 create_params.control = this;
3317
3318                                 return create_params;
3319                         }
3320                 }
3321
3322                 protected virtual Cursor DefaultCursor { get { return Cursors.Default; } }
3323
3324                 protected virtual ImeMode DefaultImeMode {
3325                         get {
3326                                 return ImeMode.Inherit;
3327                         }
3328                 }
3329
3330                 protected virtual Padding DefaultMargin {
3331                         get { return new Padding (3); }
3332                 }
3333                 
3334                 protected virtual Size DefaultMaximumSize { get { return new Size (); } }
3335                 protected virtual Size DefaultMinimumSize { get { return new Size (); } }
3336                 protected virtual Padding DefaultPadding { get { return new Padding (); } }
3337
3338                 protected virtual Size DefaultSize {
3339                         get {
3340                                 return new Size(0, 0);
3341                         }
3342                 }
3343
3344                 protected int FontHeight {
3345                         get {
3346                                 return Font.Height;
3347                         }
3348
3349                         set {
3350                                 ;; // Nothing to do
3351                         }
3352                 }
3353                 [Obsolete ()]
3354                 protected bool RenderRightToLeft {
3355                         get {
3356                                 return (this.right_to_left == RightToLeft.Yes);
3357                         }
3358                 }
3359
3360                 protected bool ResizeRedraw {
3361                         get {
3362                                 return GetStyle(ControlStyles.ResizeRedraw);
3363                         }
3364
3365                         set {
3366                                 SetStyle(ControlStyles.ResizeRedraw, value);
3367                         }
3368                 }
3369
3370                 [EditorBrowsable (EditorBrowsableState.Advanced)]
3371                 protected virtual bool ScaleChildren {
3372                         get { return ScaleChildrenInternal; }
3373                 }
3374
3375                 internal virtual bool ScaleChildrenInternal {
3376                         get { return true; }
3377                 }
3378
3379                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3380                 [Browsable(false)]
3381                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
3382                 protected internal virtual bool ShowFocusCues {
3383                         get {
3384                                 if (this is Form)
3385                                         return show_focus_cues;
3386                                         
3387                                 if (this.parent == null)
3388                                         return false;
3389                                         
3390                                 Form f = this.FindForm ();
3391                                 
3392                                 if (f != null)
3393                                         return f.show_focus_cues;
3394                                         
3395                                 return false;
3396                         }
3397                 }
3398
3399                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3400                 [Browsable(false)]
3401                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
3402                 internal virtual protected bool ShowKeyboardCues {
3403                         get {
3404                                 return ShowKeyboardCuesInternal;
3405                         }
3406                 }
3407
3408                 internal bool ShowKeyboardCuesInternal {
3409                         get {
3410                                 if (SystemInformation.MenuAccessKeysUnderlined || DesignMode)
3411                                         return true; 
3412
3413                                 return show_keyboard_cues;
3414                         }
3415                 }
3416
3417                 #endregion      // Protected Instance Properties
3418
3419                 #region Public Static Methods
3420                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3421                 public static Control FromChildHandle(IntPtr handle) {
3422                         return Control.ControlNativeWindow.ControlFromChildHandle (handle);
3423                 }
3424
3425                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3426                 public static Control FromHandle(IntPtr handle) {
3427                         return Control.ControlNativeWindow.ControlFromHandle(handle);
3428                 }
3429
3430                 [MonoTODO ("Only implemented for Win32, others always return false")]
3431                 public static bool IsKeyLocked (Keys keyVal)
3432                 {
3433                         switch (keyVal) {
3434                                 case Keys.CapsLock:
3435                                 case Keys.NumLock:
3436                                 case Keys.Scroll:
3437                                         return XplatUI.IsKeyLocked ((VirtualKeys)keyVal);
3438                                 default:
3439                                         throw new NotSupportedException ("keyVal must be CapsLock, NumLock, or ScrollLock");
3440                         }
3441                 }
3442
3443                 public static bool IsMnemonic(char charCode, string text) {
3444                         int amp;
3445
3446                         amp = text.IndexOf('&');
3447
3448                         if (amp != -1) {
3449                                 if (amp + 1 < text.Length) {
3450                                         if (text[amp + 1] != '&') {
3451                                                 if (Char.ToUpper(charCode) == Char.ToUpper(text.ToCharArray(amp + 1, 1)[0])) {
3452                                                         return true;
3453                                                 }       
3454                                         }
3455                                 }
3456                         }
3457                         return false;
3458                 }
3459                 #endregion
3460
3461                 #region Protected Static Methods
3462                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3463                 protected static bool ReflectMessage(IntPtr hWnd, ref Message m) {
3464                         Control c;
3465
3466                         c = Control.FromHandle(hWnd);
3467
3468                         if (c != null) {
3469                                 c.WndProc(ref m);
3470                                 return true;
3471                         }
3472                         return false;
3473                 }
3474                 #endregion
3475
3476                 #region Public Instance Methods
3477                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3478                 public IAsyncResult BeginInvoke(Delegate method) {
3479                         object [] prms = null;
3480                         if (method is EventHandler)
3481                                 prms = new object [] { this, EventArgs.Empty };
3482                         return BeginInvokeInternal(method, prms);
3483                 }
3484
3485                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3486                 public IAsyncResult BeginInvoke (Delegate method, params object[] args)
3487                 {
3488                         return BeginInvokeInternal (method, args);
3489                 }
3490
3491                 public void BringToFront() {
3492                         if (parent != null) {
3493                                 parent.child_controls.SetChildIndex(this, 0);
3494                         }
3495                         else if (IsHandleCreated) {
3496                                 XplatUI.SetZOrder(Handle, IntPtr.Zero, false, false);
3497                         }
3498                 }
3499
3500                 public bool Contains(Control ctl) {
3501                         while (ctl != null) {
3502                                 ctl = ctl.parent;
3503                                 if (ctl == this) {
3504                                         return true;
3505                                 }
3506                         }
3507                         return false;
3508                 }
3509
3510                 public void CreateControl () {
3511                         if (is_created) {
3512                                 return;
3513                         }
3514
3515                         if (is_disposing) {
3516                                 return;
3517                         }
3518
3519                         if (!is_visible) {
3520                                 return;
3521                         }
3522                         
3523                         if (parent != null && !parent.Created) {
3524                                 return;
3525                         }
3526
3527                         if (!IsHandleCreated) {
3528                                 CreateHandle();
3529                         }
3530
3531                         if (!is_created) {
3532                                 is_created = true;
3533
3534                                 // Create all of our children (implicit ones as well) when we are created.
3535                                 // The child should fire it's OnLoad before the parents, however
3536                                 // if the child checks Parent.Created in it's OnCreateControl, the
3537                                 // parent is already created.
3538                                 foreach (Control c in Controls.GetAllControls ())
3539                                         if (!c.Created && !c.IsDisposed)
3540                                                 c.CreateControl ();
3541                                                 
3542                                 OnCreateControl();
3543                         }
3544                 }
3545
3546                 public Graphics CreateGraphics() {
3547                         if (!IsHandleCreated) {
3548                                 this.CreateHandle();
3549                         }
3550                         return Graphics.FromHwnd(this.window.Handle);
3551                 }
3552
3553                 public DragDropEffects DoDragDrop(object data, DragDropEffects allowedEffects) {
3554                         DragDropEffects result = DragDropEffects.None;
3555                         if (IsHandleCreated)
3556                                 result = XplatUI.StartDrag(Handle, data, allowedEffects);
3557                         OnDragDropEnd (result);
3558                         return result;
3559                 }
3560
3561                 internal virtual void OnDragDropEnd (DragDropEffects effects)
3562                 {
3563                 }
3564
3565                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3566                 public object EndInvoke (IAsyncResult asyncResult) {
3567                         AsyncMethodResult result = (AsyncMethodResult) asyncResult;
3568                         return result.EndInvoke ();
3569                 }
3570
3571                 internal Control FindRootParent ()
3572                 {
3573                         Control c = this;
3574                         
3575                         while (c.Parent != null)
3576                                 c = c.Parent;
3577
3578                         return c;
3579                 }
3580
3581                 public Form FindForm() {
3582                         Control c;
3583
3584                         c = this;
3585                         while (c != null) {
3586                                 if (c is Form) {
3587                                         return (Form)c;
3588                                 }
3589                                 c = c.Parent;
3590                         }
3591                         return null;
3592                 }
3593                 [EditorBrowsable (EditorBrowsableState.Advanced)]
3594                 public bool Focus() {
3595                         return FocusInternal (false);
3596                 }
3597
3598                 internal virtual bool FocusInternal (bool skip_check) {
3599                         if (skip_check || (CanFocus && IsHandleCreated && !has_focus && !is_focusing)) {
3600                                 is_focusing = true;
3601                                 Select(this);
3602                                 is_focusing = false;
3603                         }
3604                         return has_focus;
3605                 }
3606
3607                 internal Control GetRealChildAtPoint (Point pt) {
3608                         if (!IsHandleCreated)
3609                                 CreateHandle ();
3610
3611                         foreach (Control control in child_controls.GetAllControls ()) {
3612                                 if (control.Bounds.Contains (PointToClient (pt))) {
3613                                         Control child = control.GetRealChildAtPoint (pt);
3614                                         if (child == null)
3615                                                 return control;
3616                                         else
3617                                                 return child;
3618                                 }
3619                         }
3620
3621                         return null;
3622                 }
3623
3624                 public Control GetChildAtPoint(Point pt)
3625                 {
3626                         return GetChildAtPoint (pt, GetChildAtPointSkip.None);
3627                 }
3628
3629                 public Control GetChildAtPoint (Point pt, GetChildAtPointSkip skipValue)
3630                 {
3631                         // MS's version causes the handle to be created.  The stack trace shows that get_Handle is called here, but
3632                         // we'll just call CreateHandle instead.
3633                         if (!IsHandleCreated)
3634                                 CreateHandle ();
3635
3636                         // Microsoft's version of this function doesn't seem to work, so I can't check
3637                         // if we only consider children or also grandchildren, etc.
3638                         // I'm gonna say 'children only'
3639                         foreach (Control child in Controls) {
3640                                 if ((skipValue & GetChildAtPointSkip.Disabled) == GetChildAtPointSkip.Disabled && !child.Enabled)
3641                                         continue;
3642                                 else if ((skipValue & GetChildAtPointSkip.Invisible) == GetChildAtPointSkip.Invisible && !child.Visible)
3643                                         continue;
3644                                 else if ((skipValue & GetChildAtPointSkip.Transparent) == GetChildAtPointSkip.Transparent && child.BackColor.A == 0x0)
3645                                         continue;
3646                                 else if (child.Bounds.Contains (pt))
3647                                         return child;
3648                         }
3649
3650                         return null;
3651                 }
3652
3653                 public IContainerControl GetContainerControl() {
3654                         Control current = this;
3655
3656                         while (current!=null) {
3657                                 if ((current is IContainerControl) && ((current.control_style & ControlStyles.ContainerControl)!=0)) {
3658                                         return (IContainerControl)current;
3659                                 }
3660                                 current = current.parent;
3661                         }
3662                         return null;
3663                 }
3664
3665                 internal ContainerControl InternalGetContainerControl() {
3666                         Control current = this;
3667
3668                         while (current!=null) {
3669                                 if ((current is ContainerControl) && ((current.control_style & ControlStyles.ContainerControl)!=0)) {
3670                                         return current as ContainerControl;
3671                                 }
3672                                 current = current.parent;
3673                         }
3674                         return null;
3675                 }
3676
3677                 public Control GetNextControl(Control ctl, bool forward) {
3678
3679                         if (!this.Contains(ctl)) {
3680                                 ctl = this;
3681                         }
3682
3683                         if (forward) {
3684                                 ctl = FindControlForward(this, ctl);
3685                         }
3686                         else {
3687                                 ctl = FindControlBackward(this, ctl);
3688                         }
3689
3690                         if (ctl != this) {
3691                                 return ctl;
3692                         }
3693                         return null;
3694                 }
3695
3696                 [EditorBrowsable (EditorBrowsableState.Advanced)]
3697                 public virtual Size GetPreferredSize (Size proposedSize) {
3698                         Size retsize = GetPreferredSizeCore (proposedSize);
3699                         
3700                         // If we're bigger than the MaximumSize, fix that
3701                         if (this.maximum_size.Width != 0 && retsize.Width > this.maximum_size.Width)
3702                                 retsize.Width = this.maximum_size.Width;
3703                         if (this.maximum_size.Height != 0 && retsize.Height > this.maximum_size.Height)
3704                                 retsize.Height = this.maximum_size.Height;
3705                                 
3706                         // If we're smaller than the MinimumSize, fix that
3707                         if (this.minimum_size.Width != 0 && retsize.Width < this.minimum_size.Width)
3708                                 retsize.Width = this.minimum_size.Width;
3709                         if (this.minimum_size.Height != 0 && retsize.Height < this.minimum_size.Height)
3710                                 retsize.Height = this.minimum_size.Height;
3711                                 
3712                         return retsize;
3713                 }
3714
3715                 public void Hide() {
3716                         this.Visible = false;
3717                 }
3718
3719                 public void Invalidate ()
3720                 {
3721                         Invalidate (ClientRectangle, false);
3722                 }
3723
3724                 public void Invalidate (bool invalidateChildren)
3725                 {
3726                         Invalidate (ClientRectangle, invalidateChildren);
3727                 }
3728
3729                 public void Invalidate (Rectangle rc)
3730                 {
3731                         Invalidate (rc, false);
3732                 }
3733
3734                 public void Invalidate (Rectangle rc, bool invalidateChildren)
3735                 {
3736                         // Win32 invalidates control including when Width and Height is equal 0
3737                         // or is not visible, only Paint event must be care about this.
3738                         if (!IsHandleCreated)
3739                                 return;
3740
3741                         if (rc.IsEmpty)
3742                                 rc = ClientRectangle;
3743                                 
3744                         if  (rc.Width > 0 && rc.Height > 0) {
3745
3746                                 NotifyInvalidate(rc);
3747
3748                                 XplatUI.Invalidate(Handle, rc, false);
3749
3750                                 if (invalidateChildren) {
3751                                         Control [] controls = child_controls.GetAllControls ();
3752                                         for (int i=0; i<controls.Length; i++)
3753                                                 controls [i].Invalidate ();
3754                                 } else {
3755                                         // If any of our children are transparent, we
3756                                         // have to invalidate them anyways
3757                                         foreach (Control c in Controls)
3758                                                 if (c.BackColor.A != 255)
3759                                                         c.Invalidate ();
3760                                 }
3761                         }
3762                         OnInvalidated(new InvalidateEventArgs(rc));
3763                 }
3764
3765                 public void Invalidate (Region region)
3766                 {
3767                         Invalidate (region, false);
3768                 }
3769
3770                 public void Invalidate (Region region, bool invalidateChildren)
3771                 {
3772                         using (Graphics g = CreateGraphics ()){
3773                                 RectangleF bounds = region.GetBounds (g);
3774                                 Invalidate (new Rectangle ((int) bounds.X, (int) bounds.Y, (int) bounds.Width, (int) bounds.Height), invalidateChildren);
3775                         }
3776                 }
3777
3778                 public object Invoke (Delegate method) {
3779                         object [] prms = null;
3780                         if (method is EventHandler)
3781                                 prms = new object [] { this, EventArgs.Empty };
3782
3783                         return Invoke(method, prms);
3784                 }
3785                 public object Invoke (Delegate method, params object [] args) {
3786                         Control control = FindControlToInvokeOn ();
3787                         
3788                         if (!this.InvokeRequired) {
3789                                 return method.DynamicInvoke(args);
3790                         }
3791
3792                         IAsyncResult result = BeginInvokeInternal (method, args, control);
3793                         return EndInvoke(result);
3794                 }
3795
3796                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3797                 public void PerformLayout() {
3798                         PerformLayout(null, null);
3799                 }
3800
3801                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3802                 public void PerformLayout(Control affectedControl, string affectedProperty) {
3803                         LayoutEventArgs levent = new LayoutEventArgs(affectedControl, affectedProperty);
3804
3805                         foreach (Control c in Controls.GetAllControls ())
3806                                 if (c.recalculate_distances)
3807                                         c.UpdateDistances ();
3808
3809                         if (layout_suspended > 0) {
3810                                 layout_pending = true;
3811                                 return;
3812                         }
3813                                         
3814                         layout_pending = false;
3815
3816                         // Prevent us from getting messed up
3817                         layout_suspended++;
3818
3819                         // Perform all Dock and Anchor calculations
3820                         try {
3821                                 OnLayout(levent);
3822                         }
3823
3824                                 // Need to make sure we decremend layout_suspended
3825                         finally {
3826                                 layout_suspended--;
3827                         }
3828                 }
3829
3830                 public Point PointToClient (Point p) {
3831                         int x = p.X;
3832                         int y = p.Y;
3833
3834                         XplatUI.ScreenToClient (Handle, ref x, ref y);
3835
3836                         return new Point (x, y);
3837                 }
3838
3839                 public Point PointToScreen(Point p) {
3840                         int x = p.X;
3841                         int y = p.Y;
3842
3843                         XplatUI.ClientToScreen(Handle, ref x, ref y);
3844
3845                         return new Point(x, y);
3846                 }
3847
3848                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3849                 public PreProcessControlState PreProcessControlMessage (ref Message msg)
3850                 {
3851                         return PreProcessControlMessageInternal (ref msg);
3852                 }
3853
3854                 internal PreProcessControlState PreProcessControlMessageInternal (ref Message msg)
3855                 {
3856                         switch ((Msg)msg.Msg) {
3857                                 case Msg.WM_KEYDOWN:
3858                                 case Msg.WM_SYSKEYDOWN:
3859                                         PreviewKeyDownEventArgs e = new PreviewKeyDownEventArgs ((Keys)msg.WParam.ToInt32 () | XplatUI.State.ModifierKeys);
3860                                         OnPreviewKeyDown (e);
3861                                 
3862                                         if (e.IsInputKey)
3863                                                 return PreProcessControlState.MessageNeeded;
3864                                 
3865                                         if (PreProcessMessage (ref msg))
3866                                                 return PreProcessControlState.MessageProcessed;
3867
3868                                         if (IsInputKey ((Keys)msg.WParam.ToInt32 () | XplatUI.State.ModifierKeys))
3869                                                 return PreProcessControlState.MessageNeeded;    
3870                                         
3871                                         break;
3872                                 case Msg.WM_CHAR:
3873                                 case Msg.WM_SYSCHAR:
3874                                         if (PreProcessMessage (ref msg))
3875                                                 return PreProcessControlState.MessageProcessed;
3876                                                 
3877                                         if (IsInputChar ((char)msg.WParam))
3878                                                 return PreProcessControlState.MessageNeeded;
3879                                                 
3880                                         break;
3881                                 default:
3882                                         break;
3883                         }
3884                                 
3885                         return PreProcessControlState.MessageNotNeeded;
3886                 }
3887                 
3888                 public virtual bool PreProcessMessage (ref Message msg)
3889                 {
3890                         return InternalPreProcessMessage (ref msg);
3891                 }
3892
3893                 internal virtual bool InternalPreProcessMessage (ref Message msg) {
3894                         Keys key_data;
3895
3896                         if ((msg.Msg == (int)Msg.WM_KEYDOWN) || (msg.Msg == (int)Msg.WM_SYSKEYDOWN)) {
3897                                 key_data = (Keys)msg.WParam.ToInt32() | XplatUI.State.ModifierKeys;
3898
3899                                 if (!ProcessCmdKey(ref msg, key_data)) {
3900                                         if (IsInputKey(key_data)) {
3901                                                 return false;
3902                                         }
3903
3904                                         return ProcessDialogKey(key_data);
3905                                 }
3906
3907                                 return true;
3908                         } else if (msg.Msg == (int)Msg.WM_CHAR) {
3909                                 if (IsInputChar((char)msg.WParam)) {
3910                                         return false;
3911                                 }
3912                                 return ProcessDialogChar((char)msg.WParam);
3913                         } else if (msg.Msg == (int)Msg.WM_SYSCHAR) {
3914                                 if (ProcessDialogChar((char)msg.WParam))
3915                                         return true;
3916                                 else
3917                                         return ToolStripManager.ProcessMenuKey (ref msg);
3918                         }
3919                         return false;
3920                 }
3921
3922                 public Rectangle RectangleToClient(Rectangle r) {
3923                         return new Rectangle(PointToClient(r.Location), r.Size);
3924                 }
3925
3926                 public Rectangle RectangleToScreen(Rectangle r) {
3927                         return new Rectangle(PointToScreen(r.Location), r.Size);
3928                 }
3929
3930                 public virtual void Refresh() {
3931                         if (IsHandleCreated && Visible) {
3932                                 Invalidate(true);
3933                                 Update ();
3934                         }
3935                 }
3936
3937                 [EditorBrowsable(EditorBrowsableState.Never)]
3938                 public virtual void ResetBackColor() {
3939                         BackColor = Color.Empty;
3940                 }
3941
3942                 [EditorBrowsable(EditorBrowsableState.Never)]
3943                 public void ResetBindings() {
3944                         if (data_bindings != null)
3945                                 data_bindings.Clear();
3946                 }
3947
3948                 [EditorBrowsable(EditorBrowsableState.Never)]
3949                 public virtual void ResetCursor() {
3950                         Cursor = null;
3951                 }
3952
3953                 [EditorBrowsable(EditorBrowsableState.Never)]
3954                 public virtual void ResetFont() {
3955                         font = null;
3956                 }
3957
3958                 [EditorBrowsable(EditorBrowsableState.Never)]
3959                 public virtual void ResetForeColor() {
3960                         foreground_color = Color.Empty;
3961                 }
3962
3963                 [EditorBrowsable(EditorBrowsableState.Never)]
3964                 public void ResetImeMode() {
3965                         ime_mode = DefaultImeMode;
3966                 }
3967
3968                 [EditorBrowsable(EditorBrowsableState.Never)]
3969                 public virtual void ResetRightToLeft() {
3970                         right_to_left = RightToLeft.Inherit;
3971                 }
3972
3973                 public virtual void ResetText() {
3974                         Text = String.Empty;
3975                 }
3976
3977                 public void ResumeLayout() {
3978                         ResumeLayout (true);
3979                 }
3980
3981                 public void ResumeLayout(bool performLayout) {
3982                         if (layout_suspended > 0) {
3983                                 layout_suspended--;
3984                         }
3985
3986                         if (layout_suspended == 0) {
3987                                 if (this is ContainerControl)
3988                                         (this as ContainerControl).PerformDelayedAutoScale();
3989
3990                                 if (!performLayout)
3991                                         foreach (Control c in Controls.GetAllControls ())
3992                                                 c.UpdateDistances ();
3993
3994                                 if (performLayout && layout_pending) {
3995                                         PerformLayout();
3996                                 }
3997                         }
3998                 }
3999                 [EditorBrowsable (EditorBrowsableState.Never)]
4000                 [Obsolete ()]
4001                 public void Scale(float ratio) {
4002                         ScaleCore(ratio, ratio);
4003                 }
4004                 
4005                 [EditorBrowsable (EditorBrowsableState.Never)]
4006                 [Obsolete ()]
4007                 public void Scale(float dx, float dy) {
4008                         ScaleCore(dx, dy);
4009                 }
4010
4011                 [EditorBrowsable (EditorBrowsableState.Advanced)]
4012                 public void Scale (SizeF factor)
4013                 {
4014                         BoundsSpecified bounds_spec = BoundsSpecified.All;
4015
4016                         SuspendLayout ();
4017
4018                         if (this is ContainerControl) {
4019                                 if ((this as ContainerControl).IsAutoScaling)
4020                                         bounds_spec = BoundsSpecified.Size;
4021                                 else if (IsContainerAutoScaling (this.Parent))
4022                                         bounds_spec = BoundsSpecified.Location;
4023                         }
4024
4025                         ScaleControl (factor, bounds_spec);
4026
4027                         // Scale children
4028                         if ((bounds_spec != BoundsSpecified.Location) && ScaleChildren) {
4029                                 foreach (Control c in Controls.GetAllControls ()) {
4030                                         c.Scale (factor);
4031                                         if (c is ContainerControl) {
4032                                                 ContainerControl cc = c as ContainerControl;
4033                                                 if ((cc.AutoScaleMode == AutoScaleMode.Inherit) && IsContainerAutoScaling (this))
4034                                                         cc.PerformAutoScale (true);
4035                                         }
4036                                 }
4037                         }
4038
4039                         ResumeLayout ();
4040                 }
4041
4042                 internal ContainerControl FindContainer (Control c)
4043                 {
4044                         while ((c != null) && !(c is ContainerControl))
4045                                 c = c.Parent;
4046                         return c as ContainerControl;
4047                 }
4048
4049                 private bool IsContainerAutoScaling (Control c)
4050                 {
4051                         ContainerControl cc = FindContainer (c);
4052                         return (cc != null) && cc.IsAutoScaling;
4053                 }
4054
4055                 public void Select() {
4056                         Select(false, false);   
4057                 }
4058
4059 #if DebugFocus
4060                 private void printTree(Control c, string t) {
4061                         foreach(Control i in c.child_controls) {
4062                                 Console.WriteLine ("{2}{0}.TabIndex={1}", i, i.tab_index, t);
4063                                 printTree (i, t+"\t");
4064                         }
4065                 }
4066 #endif
4067                 public bool SelectNextControl(Control ctl, bool forward, bool tabStopOnly, bool nested, bool wrap) {
4068                         Control c;
4069
4070 #if DebugFocus
4071                         Console.WriteLine("{0}", this.FindForm());
4072                         printTree(this, "\t");
4073 #endif
4074
4075                         if (!this.Contains(ctl) || (!nested && (ctl.parent != this))) {
4076                                 ctl = null;
4077                         }
4078                         c = ctl;
4079                         do {
4080                                 c = GetNextControl(c, forward);
4081                                 if (c == null) {
4082                                         if (wrap) {
4083                                                 wrap = false;
4084                                                 continue;
4085                                         }
4086                                         break;
4087                                 }
4088
4089 #if DebugFocus
4090                                 Console.WriteLine("{0} {1}", c, c.CanSelect);
4091 #endif
4092                                 if (c.CanSelect && ((c.parent == this) || nested) && (c.tab_stop || !tabStopOnly)) {
4093                                         c.Select (true, true);
4094                                         return true;
4095                                 }
4096                         } while (c != ctl); // If we wrap back to ourselves we stop
4097
4098                         return false;
4099                 }
4100
4101                 public void SendToBack() {
4102                         if (parent != null) {
4103                                 parent.child_controls.SetChildIndex(this, parent.child_controls.Count);
4104                         }
4105                 }
4106
4107                 public void SetBounds(int x, int y, int width, int height) {
4108                         SetBounds(x, y, width, height, BoundsSpecified.All);
4109                 }
4110
4111                 public void SetBounds(int x, int y, int width, int height, BoundsSpecified specified) {
4112                         // Fill in the values that were not specified
4113                         if ((specified & BoundsSpecified.X) == 0)
4114                                 x = Left;
4115                         if ((specified & BoundsSpecified.Y) == 0)
4116                                 y = Top;
4117                         if ((specified & BoundsSpecified.Width) == 0)
4118                                 width = Width;
4119                         if ((specified & BoundsSpecified.Height) == 0)
4120                                 height = Height;
4121                 
4122                         SetBoundsInternal (x, y, width, height, specified);
4123                 }
4124
4125                 internal void SetBoundsInternal (int x, int y, int width, int height, BoundsSpecified specified)
4126                 {
4127                         // SetBoundsCore is really expensive to call, so we want to avoid it if we can.
4128                         // We can avoid it if:
4129                         // - The requested dimensions are the same as our current dimensions
4130                         // AND
4131                         // - Any BoundsSpecified is the same as our current explicit_size
4132                         if (bounds.X != x || (explicit_bounds.X != x && (specified & BoundsSpecified.X) == BoundsSpecified.X))
4133                                 SetBoundsCore (x, y, width, height, specified);
4134                         else if (bounds.Y != y || (explicit_bounds.Y != y && (specified & BoundsSpecified.Y) == BoundsSpecified.Y))
4135                                 SetBoundsCore (x, y, width, height, specified);
4136                         else if (bounds.Width != width || (explicit_bounds.Width != width && (specified & BoundsSpecified.Width) == BoundsSpecified.Width))
4137                                 SetBoundsCore (x, y, width, height, specified);
4138                         else if (bounds.Height != height || (explicit_bounds.Height != height && (specified & BoundsSpecified.Height) == BoundsSpecified.Height))
4139                                 SetBoundsCore (x, y, width, height, specified);
4140                         else
4141                                 return;
4142                         
4143                         // If the user explicitly moved or resized us, recalculate our anchor distances
4144                         if (specified != BoundsSpecified.None)
4145                                 UpdateDistances ();
4146                         
4147                         if (parent != null)
4148                                 parent.PerformLayout(this, "Bounds");
4149                 }
4150
4151                 public void Show () {
4152                         this.Visible = true;
4153                 }
4154
4155                 public void SuspendLayout() {
4156                         layout_suspended++;
4157                 }
4158
4159                 public void Update() {
4160                         if (IsHandleCreated) {
4161                                 XplatUI.UpdateWindow(window.Handle);
4162                         }
4163                 }
4164                 #endregion      // Public Instance Methods
4165
4166                 #region Protected Instance Methods
4167                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4168                 protected void AccessibilityNotifyClients(AccessibleEvents accEvent, int childID) {
4169                         // turns out this method causes handle
4170                         // creation in 1.1.  at first I thought this
4171                         // would be accomplished just by using
4172                         // get_AccessibilityObject, which would route
4173                         // through CreateAccessibilityInstance, which
4174                         // calls CreateControl.  This isn't the case,
4175                         // though (as overriding
4176                         // CreateAccessibilityInstance and adding a
4177                         // CWL shows nothing.  So we fudge it and put
4178                         // a CreateHandle here.
4179
4180
4181                         if (accessibility_object != null && accessibility_object is ControlAccessibleObject)
4182                                 ((ControlAccessibleObject)accessibility_object).NotifyClients (accEvent, childID);
4183                 }
4184
4185                 [EditorBrowsable (EditorBrowsableState.Advanced)]
4186                 protected void AccessibilityNotifyClients (AccessibleEvents accEvent, int objectID, int childID)
4187                 {
4188                         if (accessibility_object != null && accessibility_object is ControlAccessibleObject)
4189                                 ((ControlAccessibleObject)accessibility_object).NotifyClients (accEvent, objectID, childID);
4190                 }
4191
4192                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4193                 protected virtual AccessibleObject CreateAccessibilityInstance() {
4194                         CreateControl ();
4195                         return new Control.ControlAccessibleObject(this);
4196                 }
4197
4198                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4199                 protected virtual ControlCollection CreateControlsInstance() {
4200                         return new ControlCollection(this);
4201                 }
4202
4203                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4204                 protected virtual void CreateHandle() {
4205                         if (IsDisposed) {
4206                                 throw new ObjectDisposedException(GetType().FullName);
4207                         }
4208
4209                         if (IsHandleCreated && !is_recreating) {
4210                                 return;
4211                         }
4212
4213                         CreateParams create_params = CreateParams;
4214                         window.CreateHandle(create_params);
4215
4216                         if (window.Handle != IntPtr.Zero) {
4217                                 creator_thread = Thread.CurrentThread;
4218
4219                                 XplatUI.EnableWindow(window.Handle, is_enabled);
4220
4221                                 if (clip_region != null) {
4222                                         XplatUI.SetClipRegion(window.Handle, clip_region);
4223                                 }
4224
4225                                 // Set our handle with our parent
4226                                 if ((parent != null) && (parent.IsHandleCreated)) {
4227                                         XplatUI.SetParent(window.Handle, parent.Handle);
4228                                 }
4229
4230                                 UpdateStyles();
4231                                 XplatUI.SetAllowDrop (window.Handle, allow_drop);
4232
4233                                 // Find out where the window manager placed us
4234                                 if ((CreateParams.Style & (int)WindowStyles.WS_CHILD) != 0) {
4235                                         XplatUI.SetBorderStyle(window.Handle, (FormBorderStyle)border_style);
4236                                 }
4237
4238                                 Rectangle save_bounds = explicit_bounds;
4239                                 UpdateBounds ();
4240                                 explicit_bounds = save_bounds;
4241                         }
4242                 }
4243
4244                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4245                 protected virtual void DefWndProc(ref Message m) {
4246                         window.DefWndProc(ref m);
4247                 }
4248
4249                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4250                 protected virtual void DestroyHandle() {
4251                         if (IsHandleCreated) {
4252                                 if (window != null) {
4253                                         window.DestroyHandle();
4254                                 }
4255                         }
4256                 }
4257
4258                 protected virtual AccessibleObject GetAccessibilityObjectById (int objectId)
4259                 {
4260                         // XXX need to implement this.
4261                         return null;
4262                 }
4263                 
4264                 protected internal AutoSizeMode GetAutoSizeMode () 
4265                 {
4266                         return auto_size_mode;
4267                 }
4268
4269                 [EditorBrowsable (EditorBrowsableState.Advanced)]
4270                 protected virtual Rectangle GetScaledBounds (Rectangle bounds, SizeF factor, BoundsSpecified specified)
4271                 {
4272                         // Top level controls do not scale location
4273                         if (!is_toplevel) {
4274                                 if ((specified & BoundsSpecified.X) == BoundsSpecified.X)
4275                                         bounds.X = (int)Math.Round (bounds.X * factor.Width);
4276                                 if ((specified & BoundsSpecified.Y) == BoundsSpecified.Y)
4277                                         bounds.Y = (int)Math.Round (bounds.Y * factor.Height);
4278                         }
4279
4280                         if ((specified & BoundsSpecified.Width) == BoundsSpecified.Width && !GetStyle (ControlStyles.FixedWidth)) {
4281                                 int border = (this is ComboBox) ? (ThemeEngine.Current.Border3DSize.Width * 2) :
4282                                         (this.bounds.Width - this.client_size.Width);
4283                                 bounds.Width = (int)Math.Round ((bounds.Width - border) * factor.Width + border);
4284                         }
4285                         if ((specified & BoundsSpecified.Height) == BoundsSpecified.Height && !GetStyle (ControlStyles.FixedHeight)) {
4286                                 int border = (this is ComboBox) ? (ThemeEngine.Current.Border3DSize.Height * 2) :
4287                                         (this.bounds.Height - this.client_size.Height);
4288                                 bounds.Height = (int)Math.Round ((bounds.Height - border) * factor.Height + border);
4289                         }
4290
4291                         return bounds;
4292                 }
4293
4294                 private Rectangle GetScaledBoundsOld (Rectangle bounds, SizeF factor, BoundsSpecified specified)
4295                 {
4296                         RectangleF new_bounds = new RectangleF(bounds.Location, bounds.Size);
4297
4298                         // Top level controls do not scale location
4299                         if (!is_toplevel) {
4300                                 if ((specified & BoundsSpecified.X) == BoundsSpecified.X)
4301                                         new_bounds.X *= factor.Width;
4302                                 if ((specified & BoundsSpecified.Y) == BoundsSpecified.Y)
4303                                         new_bounds.Y *= factor.Height;
4304                         }
4305
4306                         if ((specified & BoundsSpecified.Width) == BoundsSpecified.Width && !GetStyle (ControlStyles.FixedWidth)) {
4307                                 int border = (this is Form) ? (this.bounds.Width - this.client_size.Width) : 0;
4308                                 new_bounds.Width = ((new_bounds.Width - border) * factor.Width + border);
4309                         }
4310                         if ((specified & BoundsSpecified.Height) == BoundsSpecified.Height && !GetStyle (ControlStyles.FixedHeight)) {
4311                                 int border = (this is Form) ? (this.bounds.Height - this.client_size.Height) : 0;
4312                                 new_bounds.Height = ((new_bounds.Height - border) * factor.Height + border);
4313                         }
4314
4315                         bounds.X = (int)Math.Round (new_bounds.X);
4316                         bounds.Y = (int)Math.Round (new_bounds.Y);
4317                         bounds.Width = (int)Math.Round (new_bounds.Right) - bounds.X;
4318                         bounds.Height = (int)Math.Round (new_bounds.Bottom) - bounds.Y;
4319
4320                         return bounds;
4321                 }
4322
4323                 protected internal bool GetStyle(ControlStyles flag) {
4324                         return (control_style & flag) != 0;
4325                 }
4326
4327                 protected bool GetTopLevel() {
4328                         return is_toplevel;
4329                 }
4330
4331                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4332                 protected virtual void InitLayout() {
4333                 }
4334
4335                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4336                 protected void InvokeGotFocus(Control toInvoke, EventArgs e) {
4337                         toInvoke.OnGotFocus(e);
4338                 }
4339
4340                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4341                 protected void InvokeLostFocus(Control toInvoke, EventArgs e) {
4342                         toInvoke.OnLostFocus(e);
4343                 }
4344
4345                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4346                 protected void InvokeOnClick(Control toInvoke, EventArgs e) {
4347                         toInvoke.OnClick(e);
4348                 }
4349
4350                 protected void InvokePaint(Control c, PaintEventArgs e) {
4351                         c.OnPaint (e);
4352                 }
4353
4354                 protected void InvokePaintBackground(Control c, PaintEventArgs e) {
4355                         c.OnPaintBackground (e);
4356                 }
4357
4358                 protected virtual bool IsInputChar (char charCode) {
4359                         // XXX on MS.NET this method causes the handle to be created..
4360                         if (!IsHandleCreated)
4361                                 CreateHandle ();
4362
4363                         return IsInputCharInternal (charCode);
4364                 }
4365
4366                 internal virtual bool IsInputCharInternal (char charCode) {
4367                         return false;
4368                 }
4369                 
4370                 protected virtual bool IsInputKey (Keys keyData) {
4371                         // Doc says this one calls IsInputChar; not sure what to do with that
4372                         return false;
4373                 }
4374
4375                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4376                 protected virtual void NotifyInvalidate(Rectangle invalidatedArea) {
4377                         // override me?
4378                 }
4379
4380                 protected virtual bool ProcessCmdKey(ref Message msg, Keys keyData) {
4381                         if ((context_menu != null) && context_menu.ProcessCmdKey(ref msg, keyData)) {
4382                                 return true;
4383                         }
4384
4385                         if (parent != null) {
4386                                 return parent.ProcessCmdKey(ref msg, keyData);
4387                         }
4388
4389                         return false;
4390                 }
4391
4392                 protected virtual bool ProcessDialogChar(char charCode) {
4393                         if (parent != null) {
4394                                 return parent.ProcessDialogChar (charCode);
4395                         }
4396
4397                         return false;
4398                 }
4399
4400                 protected virtual bool ProcessDialogKey (Keys keyData) {
4401                         if (parent != null) {
4402                                 return parent.ProcessDialogKey (keyData);
4403                         }
4404
4405                         return false;
4406                 }
4407
4408                 protected virtual bool ProcessKeyEventArgs (ref Message m)
4409                 {
4410                         KeyEventArgs key_event;
4411
4412                         switch (m.Msg) {
4413                                 case (int)Msg.WM_SYSKEYDOWN:
4414                                 case (int)Msg.WM_KEYDOWN: {
4415                                         key_event = new KeyEventArgs ((Keys) m.WParam.ToInt32 ());
4416                                         OnKeyDown (key_event);
4417                                         suppressing_key_press = key_event.SuppressKeyPress;
4418                                         return key_event.Handled;
4419                                 }
4420
4421                                 case (int)Msg.WM_SYSKEYUP:
4422                                 case (int)Msg.WM_KEYUP: {
4423                                         key_event = new KeyEventArgs ((Keys) m.WParam.ToInt32 ());
4424                                         OnKeyUp (key_event);
4425                                         return key_event.Handled;
4426                                 }
4427
4428                                 case (int)Msg.WM_SYSCHAR:
4429                                 case (int)Msg.WM_CHAR: {
4430                                         if (suppressing_key_press)
4431                                                 return true;
4432                                         KeyPressEventArgs key_press_event;
4433
4434                                         key_press_event = new KeyPressEventArgs ((char) m.WParam);
4435                                         OnKeyPress(key_press_event);
4436                                         m.WParam = (IntPtr) key_press_event.KeyChar;
4437                                         return key_press_event.Handled;
4438                                 }
4439
4440                                 default: {
4441                                         break;
4442                                 }
4443                         }
4444
4445                         return false;
4446                 }
4447
4448                 protected internal virtual bool ProcessKeyMessage (ref Message m)
4449                 {
4450                         if (parent != null) {
4451                                 if (parent.ProcessKeyPreview (ref m))
4452                                         return true;
4453                         }
4454
4455                         return ProcessKeyEventArgs (ref m);
4456                 }
4457
4458                 protected virtual bool ProcessKeyPreview (ref Message m) {
4459                         if (parent != null)
4460                                 return parent.ProcessKeyPreview(ref m);
4461
4462                         return false;
4463                 }
4464
4465                 protected virtual bool ProcessMnemonic(char charCode) {
4466                         // override me
4467                         return false;
4468                 }
4469
4470                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4471                 protected void RaiseDragEvent(object key, DragEventArgs e) {
4472                         // MS Internal
4473                 }
4474
4475                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4476                 protected void RaiseKeyEvent(object key, KeyEventArgs e) {
4477                         // MS Internal
4478                 }
4479
4480                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4481                 protected void RaiseMouseEvent(object key, MouseEventArgs e) {
4482                         // MS Internal
4483                 }
4484
4485                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4486                 protected void RaisePaintEvent(object key, PaintEventArgs e) {
4487                         // MS Internal
4488                 }
4489
4490                 private void SetIsRecreating () {
4491                         is_recreating=true;
4492
4493                         foreach (Control c in Controls.GetAllControls()) {
4494                                 c.SetIsRecreating ();
4495                         }
4496                 }
4497
4498                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4499                 protected void RecreateHandle() {
4500                         if (!IsHandleCreated)
4501                                 return;
4502
4503 #if DebugRecreate
4504                         Console.WriteLine("Recreating control {0}", XplatUI.Window(window.Handle));
4505 #endif
4506
4507                         SetIsRecreating ();
4508
4509                         if (IsHandleCreated) {
4510 #if DebugRecreate
4511                                 Console.WriteLine(" + handle is created, destroying it.");
4512 #endif
4513                                 DestroyHandle();
4514                                 // WM_DESTROY will CreateHandle for us
4515                         } else {
4516 #if DebugRecreate
4517                                 Console.WriteLine(" + handle is not created, creating it.");
4518 #endif
4519                                 if (!is_created) {
4520                                         CreateControl();
4521                                 } else {
4522                                         CreateHandle();
4523                                 }
4524
4525                                 is_recreating = false;
4526 #if DebugRecreate
4527                                 Console.WriteLine (" + new handle = {0:X}", Handle.ToInt32());
4528 #endif
4529                         }
4530
4531                 }
4532
4533                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4534                 protected void ResetMouseEventArgs() {
4535                         // MS Internal
4536                 }
4537
4538                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4539                 protected ContentAlignment RtlTranslateAlignment(ContentAlignment align) {
4540                         if (right_to_left == RightToLeft.No) {
4541                                 return align;
4542                         }
4543
4544                         switch (align) {
4545                                 case ContentAlignment.TopLeft: {
4546                                         return ContentAlignment.TopRight;
4547                                 }
4548
4549                                 case ContentAlignment.TopRight: {
4550                                         return ContentAlignment.TopLeft;
4551                                 }
4552
4553                                 case ContentAlignment.MiddleLeft: {
4554                                         return ContentAlignment.MiddleRight;
4555                                 }
4556
4557                                 case ContentAlignment.MiddleRight: {
4558                                         return ContentAlignment.MiddleLeft;
4559                                 }
4560
4561                                 case ContentAlignment.BottomLeft: {
4562                                         return ContentAlignment.BottomRight;
4563                                 }
4564
4565                                 case ContentAlignment.BottomRight: {
4566                                         return ContentAlignment.BottomLeft;
4567                                 }
4568
4569                                 default: {
4570                                         // if it's center it doesn't change
4571                                         return align;
4572                                 }
4573                         }
4574                 }
4575
4576                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4577                 protected HorizontalAlignment RtlTranslateAlignment(HorizontalAlignment align) {
4578                         if ((right_to_left == RightToLeft.No) || (align == HorizontalAlignment.Center)) {
4579                                 return align;
4580                         }
4581
4582                         if (align == HorizontalAlignment.Left) {
4583                                 return HorizontalAlignment.Right;
4584                         }
4585
4586                         // align must be HorizontalAlignment.Right
4587                         return HorizontalAlignment.Left;
4588                 }
4589
4590                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4591                 protected LeftRightAlignment RtlTranslateAlignment(LeftRightAlignment align) {
4592                         if (right_to_left == RightToLeft.No) {
4593                                 return align;
4594                         }
4595
4596                         if (align == LeftRightAlignment.Left) {
4597                                 return LeftRightAlignment.Right;
4598                         }
4599
4600                         // align must be LeftRightAlignment.Right;
4601                         return LeftRightAlignment.Left;
4602                 }
4603
4604                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4605                 protected ContentAlignment RtlTranslateContent(ContentAlignment align) {
4606                         return RtlTranslateAlignment(align);
4607                 }
4608
4609                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4610                 protected HorizontalAlignment RtlTranslateHorizontal(HorizontalAlignment align) {
4611                         return RtlTranslateAlignment(align);
4612                 }
4613
4614                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4615                 protected LeftRightAlignment RtlTranslateLeftRight(LeftRightAlignment align) {
4616                         return RtlTranslateAlignment(align);
4617                 }
4618
4619                 [EditorBrowsable (EditorBrowsableState.Advanced)]
4620                 protected virtual void ScaleControl (SizeF factor, BoundsSpecified specified)
4621                 {
4622                         Rectangle new_bounds = GetScaledBounds (bounds, factor, specified);
4623
4624                         SetBounds (new_bounds.X, new_bounds.Y, new_bounds.Width, new_bounds.Height, specified);
4625                 }
4626
4627                 [EditorBrowsable (EditorBrowsableState.Never)]
4628                 protected virtual void ScaleCore (float dx, float dy)
4629                 {
4630                         Rectangle new_bounds = GetScaledBoundsOld (bounds, new SizeF (dx, dy), BoundsSpecified.All);
4631
4632                         SuspendLayout ();
4633
4634                         SetBounds (new_bounds.X, new_bounds.Y, new_bounds.Width, new_bounds.Height, BoundsSpecified.All);
4635
4636                         if (ScaleChildrenInternal)
4637                                 foreach (Control c in Controls.GetAllControls ())
4638                                         c.Scale (dx, dy);
4639
4640                         ResumeLayout ();
4641                 }
4642
4643                 protected virtual void Select(bool directed, bool forward) {
4644                         IContainerControl       container;
4645                         
4646                         container = GetContainerControl();
4647                         if (container != null && (Control)container != this)
4648                                 container.ActiveControl = this;
4649                 }
4650
4651                 protected void SetAutoSizeMode (AutoSizeMode mode)
4652                 {
4653                         if (auto_size_mode != mode) {
4654                                 auto_size_mode = mode;
4655                                 PerformLayout (this, "AutoSizeMode");
4656                         }
4657                 }
4658                 
4659                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4660                 protected virtual void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) {
4661                         SetBoundsCoreInternal (x, y, width, height, specified);
4662                 }
4663                 
4664                 internal virtual void SetBoundsCoreInternal(int x, int y, int width, int height, BoundsSpecified specified) {
4665                         // Nasty hack for 2.0 DateTimePicker
4666                         height = OverrideHeight (height);
4667                         
4668                         Rectangle old_explicit = explicit_bounds;
4669                         Rectangle new_bounds = new Rectangle (x, y, width, height);
4670
4671                         // SetBoundsCore updates the Win32 control itself. UpdateBounds updates the controls variables and fires events, I'm guessing - pdb
4672                         if (IsHandleCreated) {
4673                                 XplatUI.SetWindowPos(Handle, x, y, width, height);
4674
4675                                 // Win32 automatically changes negative width/height to 0.
4676                                 // The control has already been sent a WM_WINDOWPOSCHANGED message and it has the correct
4677                                 // data, but it'll be overwritten when we call UpdateBounds unless we get the updated
4678                                 // size.
4679                                 int cw, ch, ix, iy;
4680                                 XplatUI.GetWindowPos(Handle, this is Form, out ix, out iy, out width, out height, out cw, out ch);
4681                         }
4682
4683                         // BoundsSpecified tells us which variables were programatic (user-set).
4684                         // We need to store those in the explicit bounds
4685                         if ((specified & BoundsSpecified.X) == BoundsSpecified.X)
4686                                 explicit_bounds.X = new_bounds.X;
4687                         else
4688                                 explicit_bounds.X = old_explicit.X;
4689
4690                         if ((specified & BoundsSpecified.Y) == BoundsSpecified.Y)
4691                                 explicit_bounds.Y = new_bounds.Y;
4692                         else
4693                                 explicit_bounds.Y = old_explicit.Y;
4694
4695                         if ((specified & BoundsSpecified.Width) == BoundsSpecified.Width)
4696                                 explicit_bounds.Width = new_bounds.Width;
4697                         else
4698                                 explicit_bounds.Width = old_explicit.Width;
4699
4700                         if ((specified & BoundsSpecified.Height) == BoundsSpecified.Height)
4701                                 explicit_bounds.Height = new_bounds.Height;
4702                         else
4703                                 explicit_bounds.Height = old_explicit.Height;
4704
4705                         // We need to store the explicit bounds because UpdateBounds is always going
4706                         // to change it, and we have to fix it.  However, UpdateBounds also calls
4707                         // OnLocationChanged, OnSizeChanged, and OnClientSizeChanged.  The user can
4708                         // override those or use those events to change the size explicitly, and we 
4709                         // can't undo those changes.  So if the bounds after calling UpdateBounds are
4710                         // the same as the ones we sent it, we need to fix the explicit bounds.  If
4711                         // it's not the same as we sent UpdateBounds, then someone else changed it, and
4712                         // we better not mess it up.  Fun stuff.
4713                         Rectangle stored_explicit_bounds = explicit_bounds;
4714                         
4715                         UpdateBounds(x, y, width, height);
4716
4717                         if (explicit_bounds.X == x)
4718                                 explicit_bounds.X = stored_explicit_bounds.X;
4719
4720                         if (explicit_bounds.Y == y)
4721                                 explicit_bounds.Y = stored_explicit_bounds.Y;
4722
4723                         if (explicit_bounds.Width == width)
4724                                 explicit_bounds.Width = stored_explicit_bounds.Width;
4725
4726                         if (explicit_bounds.Height == height)
4727                                 explicit_bounds.Height = stored_explicit_bounds.Height;
4728                 }
4729
4730                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4731                 protected virtual void SetClientSizeCore(int x, int y) {
4732                         Size NewSize = InternalSizeFromClientSize (new Size (x, y));
4733                         
4734                         if (NewSize != Size.Empty)
4735                                 SetBounds (bounds.X, bounds.Y, NewSize.Width, NewSize.Height, BoundsSpecified.Size);
4736                 }
4737
4738                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4739                 protected internal void SetStyle(ControlStyles flag, bool value) {
4740                         if (value) {
4741                                 control_style |= flag;
4742                         } else {
4743                                 control_style &= ~flag;
4744                         }
4745                 }
4746
4747                 protected void SetTopLevel(bool value) {
4748                         if ((GetTopLevel() != value) && (parent != null)) {
4749                                 throw new ArgumentException ("Cannot change toplevel style of a parented control.");
4750                         }
4751
4752                         if (this is Form) {
4753                                 if (IsHandleCreated && value != Visible) {
4754                                         Visible = value;
4755                                 }
4756                         } else {
4757                                 // XXX MS.NET causes handle to be created here
4758                                 if (!IsHandleCreated)
4759                                         CreateHandle ();
4760                         }
4761                         is_toplevel = value;
4762                 }
4763
4764                 protected virtual void SetVisibleCore(bool value) {
4765                         if (value != is_visible) {
4766                                 is_visible = value;
4767                                 
4768                                 if (is_visible && ((window.Handle == IntPtr.Zero) || !is_created)) {
4769                                         CreateControl();
4770                                         if (!(this is Form))
4771                                                 UpdateZOrder ();
4772                                 }
4773
4774                                 if (IsHandleCreated) {
4775                                         XplatUI.SetVisible (Handle, is_visible, true);
4776                                         if (!is_visible) {
4777                                                 if (parent != null && parent.IsHandleCreated) {
4778                                                         parent.Invalidate (bounds);
4779                                                         parent.Update ();
4780                                                 } else {
4781                                                         Refresh ();
4782                                                 }
4783                                         } else if (is_visible && this is Form) {
4784                                                 // If we are Min or Max, we won't get a WM_SHOWWINDOW from SetWindowState,
4785                                                 // so we need to manually create our children, and set them visible
4786                                                 // (This normally happens in WmShowWindow.)
4787                                                 if ((this as Form).WindowState != FormWindowState.Normal)
4788                                                         OnVisibleChanged (EventArgs.Empty);
4789                                                 else
4790                                                         // Explicitly move Toplevel windows to where we want them;
4791                                                         // apparently moving unmapped toplevel windows doesn't work
4792                                                         XplatUI.SetWindowPos(window.Handle, bounds.X, bounds.Y, bounds.Width, bounds.Height);   
4793                                         } else {
4794                                                 // If we are becoming visible, z-order may have changed while
4795                                                 // we were invisible, so update our z-order position
4796                                                 if (parent != null)
4797                                                         parent.UpdateZOrderOfChild (this);
4798                                         }
4799                                         
4800                                         if (!(this is Form))
4801                                                 OnVisibleChanged (EventArgs.Empty);
4802                                 }
4803                                 else {
4804                                         OnVisibleChanged(EventArgs.Empty);
4805                                 }
4806                         }
4807                 }
4808
4809                 [EditorBrowsable (EditorBrowsableState.Advanced)]
4810                 protected virtual Size SizeFromClientSize (Size clientSize) {
4811                         return InternalSizeFromClientSize (clientSize);
4812                 }
4813
4814                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4815                 protected void UpdateBounds() {
4816                         if (!IsHandleCreated)
4817                                 return;
4818
4819                         int     x;
4820                         int     y;
4821                         int     width;
4822                         int     height;
4823                         int     client_width;
4824                         int     client_height;
4825
4826                         XplatUI.GetWindowPos(this.Handle, this is Form, out x, out y, out width, out height, out client_width, out client_height);
4827
4828                         UpdateBounds(x, y, width, height, client_width, client_height);
4829                 }
4830
4831                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4832                 protected void UpdateBounds(int x, int y, int width, int height) {
4833                         CreateParams    cp;
4834                         Rectangle       rect;
4835
4836                         // Calculate client rectangle
4837                         rect = new Rectangle(0, 0, 0, 0);
4838                         cp = CreateParams;
4839
4840                         XplatUI.CalculateWindowRect(ref rect, cp, cp.menu, out rect);
4841                         UpdateBounds(x, y, width, height, width - (rect.Right - rect.Left), height - (rect.Bottom - rect.Top));
4842                 }
4843
4844                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4845                 protected void UpdateBounds(int x, int y, int width, int height, int clientWidth, int clientHeight) {
4846                         // UpdateBounds only seems to set our sizes and fire events but not update the GUI window to match
4847                         bool    moved   = false;
4848                         bool    resized = false;
4849
4850                         // Needed to generate required notifications
4851                         if ((this.bounds.X!=x) || (this.bounds.Y!=y)) {
4852                                 moved=true;
4853                         }
4854
4855                         if ((this.Bounds.Width!=width) || (this.Bounds.Height!=height)) {
4856                                 resized=true;
4857                         }
4858
4859                         bounds.X=x;
4860                         bounds.Y=y;
4861                         bounds.Width=width;
4862                         bounds.Height=height;
4863
4864                         // Assume explicit bounds set. SetBoundsCore will restore old bounds
4865                         // if needed.
4866                         explicit_bounds = bounds;
4867
4868                         client_size.Width=clientWidth;
4869                         client_size.Height=clientHeight;
4870
4871                         if (moved) {
4872                                 OnLocationChanged(EventArgs.Empty);
4873
4874                                 if (!background_color.IsEmpty && background_color.A < byte.MaxValue)
4875                                         Invalidate ();
4876                         }
4877
4878                         if (resized) {
4879                                 OnSizeInitializedOrChanged ();
4880                                 OnSizeChanged(EventArgs.Empty);
4881                                 OnClientSizeChanged (EventArgs.Empty);
4882                         }
4883                 }
4884
4885                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4886                 protected void UpdateStyles() {
4887                         if (!IsHandleCreated) {
4888                                 return;
4889                         }
4890
4891                         XplatUI.SetWindowStyle(window.Handle, CreateParams);
4892                         OnStyleChanged(EventArgs.Empty);
4893                 }
4894
4895                 private void UpdateZOrderOfChild(Control child) {
4896                         if (IsHandleCreated && child.IsHandleCreated && (child.parent == this) && Hwnd.ObjectFromHandle(child.Handle).Mapped) {
4897                                 // Need to take into account all controls
4898                                 Control [] all_controls = child_controls.GetAllControls ();
4899
4900                                 int index = Array.IndexOf (all_controls, child);
4901                                 
4902                                 for (; index > 0; index--) {
4903                                         if (!all_controls [index - 1].IsHandleCreated || !all_controls [index - 1].VisibleInternal || !Hwnd.ObjectFromHandle(all_controls [index - 1].Handle).Mapped)
4904                                                 continue;
4905                                         break;
4906                                 }
4907                                 
4908                                 if (index > 0)  {
4909                                         XplatUI.SetZOrder(child.Handle, all_controls [index - 1].Handle, false, false);
4910                                 } else {
4911                                         IntPtr after = AfterTopMostControl ();
4912                                         if (after != IntPtr.Zero && after != child.Handle)
4913                                                 XplatUI.SetZOrder (child.Handle, after, false, false);
4914                                         else
4915                                                 XplatUI.SetZOrder (child.Handle, IntPtr.Zero, true, false);
4916                                 }
4917                         }
4918                 }
4919                 
4920                 // Override this if there is a control that shall always remain on
4921                 // top of other controls (such as scrollbars). If there are several
4922                 // of these controls, the bottom-most should be returned.
4923                 internal virtual IntPtr AfterTopMostControl () {
4924                         return IntPtr.Zero;
4925                 }
4926
4927                 // internal because we need to call it from ScrollableControl.OnVisibleChanged
4928                 internal void UpdateChildrenZOrder() {
4929                         Control [] controls;
4930
4931                         if (!IsHandleCreated) {
4932                                 return;
4933                         }
4934
4935                         // XXX This code is severely broken.  It leaks
4936                         // the "zero_sized" abstraction out of the X11
4937                         // backend and into Control.cs.  It'll work on
4938                         // windows simply by virtue of windows never
4939                         // setting that field to true.
4940                         //
4941                         // basically what we need to guard against is
4942                         // calling XplatUI.SetZOrder on an hwnd that
4943                         // corresponds to an unmapped X window.
4944                         //
4945                         // Also, explicitly send implicit controls to the back.
4946                         if (child_controls.ImplicitControls == null) {
4947                                 controls = new Control [child_controls.Count];
4948                                 child_controls.CopyTo (controls, 0);
4949                         } else {
4950                                 controls = new Control [child_controls.Count + child_controls.ImplicitControls.Count];
4951                                 child_controls.CopyTo (controls, 0);
4952                                 child_controls.ImplicitControls.CopyTo (controls, child_controls.Count);
4953                         }
4954
4955                         ArrayList children_to_order = new ArrayList ();
4956
4957                         for (int i = 0; i < controls.Length; i ++) {
4958                                 if (!controls[i].IsHandleCreated || !controls[i].VisibleInternal)
4959                                         continue;
4960
4961                                 Hwnd hwnd = Hwnd.ObjectFromHandle (controls[i].Handle);
4962                                 if (hwnd == null || hwnd.zero_sized)
4963                                         continue;
4964
4965                                 children_to_order.Add (controls[i]);
4966                         }
4967
4968                         for (int i = 1; i < children_to_order.Count; i ++) {
4969                                 Control upper = (Control)children_to_order[i-1];
4970                                 Control lower = (Control)children_to_order[i];
4971
4972                                 XplatUI.SetZOrder(lower.Handle, upper.Handle, false, false);
4973                         }
4974                 }
4975
4976                 [EditorBrowsable(EditorBrowsableState.Advanced)]
4977                 protected void UpdateZOrder() {
4978                         if (parent != null) {
4979                                 parent.UpdateZOrderOfChild(this);
4980                         }
4981                 }
4982
4983                 protected virtual void WndProc(ref Message m) {
4984 #if DebugMessages
4985                         Console.WriteLine("Control {0} received message {1}", window.Handle == IntPtr.Zero ? this.Text : XplatUI.Window(window.Handle), m.ToString ());
4986 #endif
4987                         if ((this.control_style & ControlStyles.EnableNotifyMessage) != 0) {
4988                                 OnNotifyMessage(m);
4989                         }
4990
4991                         switch((Msg)m.Msg) {
4992                                 case Msg.WM_DESTROY: {
4993                                         WmDestroy(ref m);
4994                                         return;
4995                                 }
4996
4997                                 case Msg.WM_WINDOWPOSCHANGED: {
4998                                         WmWindowPosChanged(ref m);
4999                                         return;
5000                                 }
5001
5002                                         // Nice description of what should happen when handling WM_PAINT
5003                                         // can be found here: http://pluralsight.com/wiki/default.aspx/Craig/FlickerFreeControlDrawing.html
5004                                         // and here http://msdn.microsoft.com/msdnmag/issues/06/03/WindowsFormsPerformance/
5005                                 case Msg.WM_PAINT: {
5006                                         WmPaint (ref m);
5007                                         return;
5008                                 }
5009                                         
5010                                 // The DefWndProc will never have to handle this, we always paint the background in managed code
5011                                 // In theory this code would look at ControlStyles.AllPaintingInWmPaint and and call OnPaintBackground
5012                                 // here but it just makes things more complicated...
5013                                 case Msg.WM_ERASEBKGND: {
5014                                         WmEraseBackground (ref m);
5015                                         return;
5016                                 }
5017
5018                                 case Msg.WM_LBUTTONUP: {
5019                                         WmLButtonUp (ref m);
5020                                         return;
5021                                 }
5022                                         
5023                                 case Msg.WM_LBUTTONDOWN: {
5024                                         WmLButtonDown (ref m);
5025                                         return;
5026                                 }
5027
5028                                 case Msg.WM_LBUTTONDBLCLK: {
5029                                         WmLButtonDblClick (ref m);
5030                                         return;
5031                                 }
5032
5033                                 case Msg.WM_MBUTTONUP: {
5034                                         WmMButtonUp (ref m);
5035                                         return;
5036                                 }
5037                                         
5038                                 case Msg.WM_MBUTTONDOWN: {                                      
5039                                         WmMButtonDown (ref m);
5040                                         return;
5041                                 }
5042
5043                                 case Msg.WM_MBUTTONDBLCLK: {
5044                                         WmMButtonDblClick (ref m);
5045                                         return;
5046                                 }
5047
5048                                 case Msg.WM_RBUTTONUP: {
5049                                         WmRButtonUp (ref m);
5050                                         return;
5051                                 }
5052                                         
5053                                 case Msg.WM_RBUTTONDOWN: {                                      
5054                                         WmRButtonDown (ref m);
5055                                         return;
5056                                 }
5057
5058                                 case Msg.WM_RBUTTONDBLCLK: {
5059                                         WmRButtonDblClick (ref m);
5060                                         return;
5061                                 }
5062
5063                                 case Msg.WM_CONTEXTMENU: {
5064                                         WmContextMenu (ref m);
5065                                         return;
5066                                 }
5067
5068                                 case Msg.WM_MOUSEWHEEL: {
5069                                         WmMouseWheel (ref m);
5070                                         return;
5071                                 }
5072
5073                                 case Msg.WM_MOUSEMOVE: {
5074                                         WmMouseMove (ref m);
5075                                         return;
5076                                 }
5077
5078                                 case Msg.WM_SHOWWINDOW: {
5079                                         WmShowWindow (ref m);
5080                                         return;
5081                                 }
5082
5083                                 case Msg.WM_CREATE: {
5084                                         WmCreate (ref m);
5085                                         return;
5086                                 }
5087
5088                                 case Msg.WM_MOUSE_ENTER: {
5089                                         WmMouseEnter (ref m);
5090                                         return;
5091                                 }
5092
5093                                 case Msg.WM_MOUSELEAVE: {
5094                                         WmMouseLeave (ref m);
5095                                         return;
5096                                 }
5097
5098                                 case Msg.WM_MOUSEHOVER: {
5099                                         WmMouseHover (ref m);
5100                                         return;
5101                                 }
5102
5103                                 case Msg.WM_SYSKEYUP: {
5104                                         WmSysKeyUp (ref m);
5105                                         return;
5106                                 }
5107
5108                                 case Msg.WM_SYSKEYDOWN:
5109                                 case Msg.WM_KEYDOWN:
5110                                 case Msg.WM_KEYUP:
5111                                 case Msg.WM_SYSCHAR:
5112                                 case Msg.WM_CHAR: {
5113                                         WmKeys (ref m);
5114                                         return;
5115                                 }
5116
5117                                 case Msg.WM_HELP: {
5118                                         WmHelp (ref m);
5119                                         return;
5120                                 }
5121
5122                                 case Msg.WM_KILLFOCUS: {
5123                                         WmKillFocus (ref m);
5124                                         return;
5125                                 }
5126
5127                                 case Msg.WM_SETFOCUS: {
5128                                         WmSetFocus (ref m);
5129                                         return;
5130                                 }
5131                                         
5132                                 case Msg.WM_SYSCOLORCHANGE: {
5133                                         WmSysColorChange (ref m);
5134                                         return;
5135                                 }
5136
5137                                 case Msg.WM_SETCURSOR: {
5138                                         WmSetCursor (ref m);
5139                                         return;
5140                                 }
5141
5142                                 case Msg.WM_CAPTURECHANGED: {
5143                                         WmCaptureChanged (ref m);
5144                                         return;
5145                                 }
5146
5147                                 case Msg.WM_CHANGEUISTATE: {
5148                                         WmChangeUIState (ref m);
5149                                         return;
5150                                 }
5151                         
5152                                 case Msg.WM_UPDATEUISTATE: {
5153                                         WmUpdateUIState (ref m);
5154                                         return;
5155                                 }
5156
5157                                 default:
5158                                         DefWndProc(ref m);
5159                                         return;
5160                         }
5161                 }
5162
5163                 #endregion      // Public Instance Methods
5164
5165                 #region WM methods
5166                 
5167                 private void WmDestroy (ref Message m) {
5168                         OnHandleDestroyed(EventArgs.Empty);
5169 #if DebugRecreate
5170                         IntPtr handle = window.Handle;
5171 #endif
5172                         window.InvalidateHandle();
5173
5174                         is_created = false;
5175                         if (is_recreating) {
5176 #if DebugRecreate
5177                                 Console.WriteLine ("Creating handle for {0:X}", handle.ToInt32());
5178 #endif
5179                                 CreateHandle();
5180 #if DebugRecreate
5181                                 Console.WriteLine (" + new handle = {0:X}", Handle.ToInt32());
5182 #endif
5183                                 is_recreating = false;
5184                         }
5185
5186                         if (is_disposing) {
5187                                 is_disposing = false;
5188                                 is_visible = false;
5189                         }
5190                 }
5191
5192                 private void WmWindowPosChanged (ref Message m) {
5193                         if (Visible) {
5194                                 Rectangle save_bounds = explicit_bounds;
5195                                 UpdateBounds();
5196                                 explicit_bounds = save_bounds;
5197                                 if (GetStyle(ControlStyles.ResizeRedraw)) {
5198                                         Invalidate();
5199                                 }
5200                         }
5201                 }
5202
5203
5204                 // Nice description of what should happen when handling WM_PAINT
5205                 // can be found here: http://pluralsight.com/wiki/default.aspx/Craig/FlickerFreeControlDrawing.html
5206                 // and here http://msdn.microsoft.com/msdnmag/issues/06/03/WindowsFormsPerformance/
5207                 private void WmPaint (ref Message m) {
5208                         IntPtr handle = Handle;
5209
5210                         PaintEventArgs paint_event = XplatUI.PaintEventStart (ref m, handle, true);
5211
5212                         if (paint_event == null)
5213                                 return;
5214
5215                         DoubleBuffer current_buffer = null;
5216                         if (UseDoubleBuffering) {
5217                                 current_buffer = GetBackBuffer ();
5218                                 // This optimization doesn't work when the area is invalidated
5219                                 // during a paint operation because finishing the paint operation
5220                                 // clears the invalidated region and then this thing keeps the new
5221                                 // invalidate from working.  To re-enable this, we would need a
5222                                 // mechanism to allow for nested invalidates (see bug #328681)
5223                                 //if (!current_buffer.InvalidRegion.IsVisible (paint_event.ClipRectangle)) {
5224                                 //        // Just blit the previous image
5225                                 //        current_buffer.Blit (paint_event);
5226                                 //        XplatUI.PaintEventEnd (ref m, handle, true);
5227                                 //        return;
5228                                 //}
5229                                 current_buffer.Start (paint_event);
5230                         }
5231                         // If using OptimizedDoubleBuffer, ensure the clip region gets set
5232                         if (GetStyle (ControlStyles.OptimizedDoubleBuffer))
5233                                 paint_event.Graphics.SetClip (Rectangle.Intersect (paint_event.ClipRectangle, this.ClientRectangle));
5234
5235                         if (!GetStyle(ControlStyles.Opaque)) {
5236                                 OnPaintBackground (paint_event);
5237                         }
5238
5239                         // Button-derived controls choose to ignore their Opaque style, give them a chance to draw their background anyways
5240                         OnPaintBackgroundInternal (paint_event);
5241
5242                         OnPaintInternal(paint_event);
5243                         if (!paint_event.Handled) {
5244                                 OnPaint (paint_event);
5245                         }
5246
5247                         if (current_buffer != null) {
5248                                 current_buffer.End (paint_event);
5249                         }
5250
5251
5252                         XplatUI.PaintEventEnd (ref m, handle, true);
5253                 }
5254
5255                 private void WmEraseBackground (ref Message m) {
5256                         // The DefWndProc will never have to handle this, we always paint the background in managed code
5257                         // In theory this code would look at ControlStyles.AllPaintingInWmPaint and and call OnPaintBackground
5258                         // here but it just makes things more complicated...
5259                         m.Result = (IntPtr)1;
5260                 }
5261
5262                 private void WmLButtonUp (ref Message m)
5263                 {
5264                         // Menu handle.
5265                         if (XplatUI.IsEnabled (Handle) && active_tracker != null) {
5266                                 ProcessActiveTracker (ref m);
5267                                 return;
5268                         }
5269
5270                         MouseEventArgs me;
5271
5272                         me = new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()) | MouseButtons.Left, 
5273                                 mouse_clicks, 
5274                                 LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
5275                                 0);
5276
5277                         HandleClick(mouse_clicks, me);
5278                         OnMouseUp (me);
5279
5280                         if (InternalCapture) {
5281                                 InternalCapture = false;
5282                         }
5283
5284                         if (mouse_clicks > 1) {
5285                                 mouse_clicks = 1;
5286                         }
5287                 }
5288
5289                 private void WmLButtonDown (ref Message m)
5290                 {
5291                         // Menu handle.
5292                         if (XplatUI.IsEnabled (Handle) && active_tracker != null) {
5293                                 ProcessActiveTracker (ref m);
5294                                 return;
5295                         }
5296                 
5297                         ValidationFailed = false;
5298                         if (CanSelect) {
5299                                 Select (true, true);
5300                         }
5301                         if (!ValidationFailed) {
5302                                 InternalCapture = true;
5303                                 OnMouseDown (new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()), 
5304                                         mouse_clicks, LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
5305                                         0));
5306                         }
5307                 }
5308
5309                 private void WmLButtonDblClick (ref Message m) {
5310                         InternalCapture = true;
5311                         mouse_clicks++;
5312                         OnMouseDown (new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()), 
5313                                 mouse_clicks, LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
5314                                 0));
5315                 }
5316
5317                 private void WmMButtonUp (ref Message m) {
5318                         MouseEventArgs me;
5319
5320                         me = new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()) | MouseButtons.Middle, 
5321                                 mouse_clicks, 
5322                                 LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
5323                                 0);
5324
5325                         HandleClick(mouse_clicks, me);
5326                         OnMouseUp (me);
5327                         if (InternalCapture) {
5328                                 InternalCapture = false;
5329                         }
5330                         if (mouse_clicks > 1) {
5331                                 mouse_clicks = 1;
5332                         }
5333                 }
5334
5335                 private void WmMButtonDown (ref Message m) {
5336                         InternalCapture = true;
5337                         OnMouseDown (new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()), 
5338                                 mouse_clicks, LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
5339                                 0));
5340                 }
5341
5342                 private void WmMButtonDblClick (ref Message m) {
5343                         InternalCapture = true;
5344                         mouse_clicks++;
5345                         OnMouseDown (new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()), 
5346                                 mouse_clicks, LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
5347                                 0));
5348                 }
5349
5350                 private void WmRButtonUp (ref Message m)
5351                 {
5352                         // Menu handle.
5353                         if (XplatUI.IsEnabled (Handle) && active_tracker != null) {
5354                                 ProcessActiveTracker (ref m);
5355                                 return;
5356                         }
5357
5358                         MouseEventArgs  me;
5359                         Point           pt;
5360
5361                         pt = new Point(LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()));
5362                         pt = PointToScreen(pt);
5363
5364                         me = new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()) | MouseButtons.Right, 
5365                                 mouse_clicks, 
5366                                 LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
5367                                 0);
5368
5369                         HandleClick(mouse_clicks, me);
5370
5371                         XplatUI.SendMessage(m.HWnd, Msg.WM_CONTEXTMENU, m.HWnd, (IntPtr)(pt.X + (pt.Y << 16)));
5372                         OnMouseUp (me);
5373
5374                         if (InternalCapture) {
5375                                 InternalCapture = false;
5376                         }
5377
5378                         if (mouse_clicks > 1) {
5379                                 mouse_clicks = 1;
5380                         }
5381                 }
5382
5383                 private void WmRButtonDown (ref Message m)
5384                 {
5385                         // Menu handle.
5386                         if (XplatUI.IsEnabled (Handle) && active_tracker != null) {
5387                                 ProcessActiveTracker (ref m);
5388                                 return;
5389                         }
5390
5391                         InternalCapture = true;
5392                         OnMouseDown (new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()), 
5393                                 mouse_clicks, LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
5394                                 0));
5395                 }
5396
5397                 private void WmRButtonDblClick (ref Message m) {
5398                         InternalCapture = true;
5399                         mouse_clicks++;
5400                         OnMouseDown (new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()), 
5401                                 mouse_clicks, LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
5402                                 0));
5403                 }
5404
5405                 private void WmContextMenu (ref Message m) {
5406                         if (context_menu != null) {
5407                                 Point   pt;
5408
5409                                 pt = new Point(LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()));
5410
5411                                 if (pt.X == -1 || pt.Y == -1) {
5412                                         pt.X = (this.Width / 2) + this.Left;
5413                                         pt.Y = (this.Height / 2) + this.Top;
5414                                         pt = this.PointToScreen (pt);
5415                                 }
5416                                         
5417                                 context_menu.Show (this, PointToClient (pt));
5418                                 return;
5419                         }
5420
5421                                 // If there isn't a regular context menu, show the Strip version
5422                                 if (context_menu == null && context_menu_strip != null) {
5423                                         Point pt;
5424
5425                                         pt = new Point (LowOrder ((int)m.LParam.ToInt32 ()), HighOrder ((int)m.LParam.ToInt32 ()));
5426                                         
5427                                         if (pt.X == -1 || pt.Y == -1) { 
5428                                                 pt.X = (this.Width / 2) + this.Left; 
5429                                                 pt.Y = (this.Height /2) + this.Top; 
5430                                                 pt = this.PointToScreen (pt);
5431                                         }
5432                                         
5433                                         context_menu_strip.SetSourceControl (this);
5434                                         context_menu_strip.Show (this, PointToClient (pt));
5435                                         return;
5436                                 }
5437                         DefWndProc(ref m);
5438                 }
5439
5440                 private void WmCreate (ref Message m) {
5441                         OnHandleCreated(EventArgs.Empty);
5442                 }
5443
5444                 private void WmMouseWheel (ref Message m) {
5445                         DefWndProc(ref m);
5446                         OnMouseWheel (new MouseEventArgs (FromParamToMouseButtons ((long) m.WParam), 
5447                                 mouse_clicks, LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
5448                                 HighOrder((long)m.WParam)));
5449                 }
5450
5451
5452                 private void WmMouseMove (ref Message m) {
5453                         if (XplatUI.IsEnabled (Handle) && active_tracker != null) {
5454                                 MouseEventArgs args = new MouseEventArgs (
5455                                         FromParamToMouseButtons ((int)m.WParam.ToInt32 ()),
5456                                         mouse_clicks,
5457                                         Control.MousePosition.X,
5458                                         Control.MousePosition.Y,
5459                                         0);
5460
5461                                 active_tracker.OnMotion (args);
5462                                 return;
5463                         }
5464                         
5465                         OnMouseMove  (new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()), 
5466                                 mouse_clicks, 
5467                                 LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
5468                                 0));
5469                 }
5470
5471                 private void WmMouseEnter (ref Message m) {
5472                         if (is_entered) {
5473                                 return;
5474                         }
5475                         is_entered = true;
5476                         OnMouseEnter(EventArgs.Empty);
5477                 }
5478
5479                 private void WmMouseLeave (ref Message m) {
5480                         is_entered=false;
5481                         OnMouseLeave(EventArgs.Empty);
5482                 }
5483
5484                 private void WmMouseHover (ref Message m) {
5485                         OnMouseHover(EventArgs.Empty);
5486                 }
5487
5488                 private void WmShowWindow (ref Message m) {
5489                         if (IsDisposed)
5490                                 return;
5491
5492                         Form frm = this as Form;
5493                         if (m.WParam.ToInt32() != 0) {
5494                                 if (m.LParam.ToInt32 () == 0) {
5495                                         CreateControl ();
5496                                 
5497                                         // Make sure all our children are properly parented to us
5498                                         Control [] controls = child_controls.GetAllControls ();
5499 //                                      bool parented = false;
5500                                         for (int i=0; i<controls.Length; i++) {
5501                                                 if (controls [i].is_visible && controls[i].IsHandleCreated)
5502                                                         if (XplatUI.GetParent (controls[i].Handle) != window.Handle) {
5503                                                                 XplatUI.SetParent(controls[i].Handle, window.Handle);
5504 //                                                              parented = true;
5505                                                         }
5506
5507                                         }
5508                                         
5509                                         //if (parented)
5510                                                 UpdateChildrenZOrder ();
5511                                 }
5512                         } else {
5513                                 if (parent != null && Focused) {
5514                                         Control container;
5515                                         // Need to start at parent, GetContainerControl might return ourselves if we're a container
5516                                         container = (Control)parent.GetContainerControl();
5517                                         if (container != null && (frm == null || !frm.IsMdiChild)) {
5518                                                 container.SelectNextControl(this, true, true, true, true);
5519                                         }
5520                                 }
5521                         }
5522
5523                         if (frm != null)
5524                                 frm.waiting_showwindow = false;
5525
5526                         // If the form is Max/Min, it got its OnVisibleChanged in SetVisibleCore
5527                         if (frm != null) {
5528                                 if (!IsRecreating && (frm.IsMdiChild || frm.WindowState == FormWindowState.Normal)) /* XXX make sure this works for mdi forms */
5529                                         OnVisibleChanged(EventArgs.Empty);
5530                         } else if (is_toplevel)
5531                                 OnVisibleChanged(EventArgs.Empty);
5532                 }
5533
5534                 private void WmSysKeyUp (ref Message m) {
5535                         if (ProcessKeyMessage(ref m)) {
5536                                 m.Result = IntPtr.Zero;
5537                                 return;
5538                         }
5539
5540                         if ((m.WParam.ToInt32() & (int)Keys.KeyCode) == (int)Keys.Menu) {
5541                                 Form    form;
5542
5543                                 form = FindForm();
5544                                 if (form != null && form.ActiveMenu != null) {
5545                                         form.ActiveMenu.ProcessCmdKey(ref m, (Keys)m.WParam.ToInt32());
5546                                 }
5547                                 else
5548                                         if (ToolStripManager.ProcessMenuKey (ref m))
5549                                                 return;
5550                         }
5551
5552                         DefWndProc (ref m);
5553                 }
5554
5555                 private void WmKeys (ref Message m)
5556                 {
5557                         if (ProcessKeyMessage(ref m)) {
5558                                 m.Result = IntPtr.Zero;
5559                                 return;
5560                         }
5561                         DefWndProc (ref m);
5562                 }
5563
5564                 private void WmHelp (ref Message m) {
5565                         Point   mouse_pos;
5566                         if (m.LParam != IntPtr.Zero) {
5567                                 HELPINFO        hi;
5568
5569                                 hi = new HELPINFO();
5570
5571                                 hi = (HELPINFO) Marshal.PtrToStructure (m.LParam, typeof (HELPINFO));
5572                                 mouse_pos = new Point(hi.MousePos.x, hi.MousePos.y);
5573                         } else {
5574                                 mouse_pos = Control.MousePosition;
5575                         }
5576                         OnHelpRequested(new HelpEventArgs(mouse_pos));
5577                         m.Result = (IntPtr)1;
5578                 }
5579
5580                 private void WmKillFocus (ref Message m) {
5581                         this.has_focus = false;
5582                         OnLostFocus (EventArgs.Empty);
5583                 }
5584
5585                 private void WmSetFocus (ref Message m) {
5586                         if (!has_focus) {
5587                                 this.has_focus = true;
5588                                 OnGotFocus (EventArgs.Empty);
5589                         }
5590                 }
5591                                         
5592                 private void WmSysColorChange (ref Message m) {
5593                         ThemeEngine.Current.ResetDefaults();
5594                         OnSystemColorsChanged(EventArgs.Empty);
5595                 }
5596
5597                 private void WmSetCursor (ref Message m) {
5598                         if ((cursor == null && use_wait_cursor == false) || ((HitTest)(m.LParam.ToInt32() & 0xffff) != HitTest.HTCLIENT)) {
5599                                 DefWndProc(ref m);
5600                                 return;
5601                         }
5602
5603                         XplatUI.SetCursor(window.Handle, Cursor.handle);
5604                         m.Result = (IntPtr)1;
5605                 }
5606
5607                 private void WmCaptureChanged (ref Message m) {
5608                         is_captured = false;
5609                         OnMouseCaptureChanged (EventArgs.Empty);
5610                         m.Result = (IntPtr) 0;
5611                 }
5612
5613                 private void WmChangeUIState (ref Message m) {
5614                         foreach (Control control in Controls) {
5615                                 XplatUI.SendMessage (control.Handle, Msg.WM_UPDATEUISTATE, m.WParam, m.LParam);
5616                         }
5617                 }
5618
5619                 private void WmUpdateUIState (ref Message m) {
5620                         int action = LowOrder (m.WParam.ToInt32 ());
5621                         int element = HighOrder (m.WParam.ToInt32 ());
5622
5623                         if (action == (int) MsgUIState.UIS_INITIALIZE)
5624                                 return;
5625
5626                         UICues cues = UICues.None;
5627
5628                         if ((element & (int) MsgUIState.UISF_HIDEACCEL) != 0) {
5629                                 if ((action == (int) MsgUIState.UIS_CLEAR) != show_keyboard_cues) {
5630                                         cues |= UICues.ChangeKeyboard;
5631                                         show_keyboard_cues = (action == (int) MsgUIState.UIS_CLEAR);
5632                                 }
5633                         }
5634
5635                         if ((element & (int) MsgUIState.UISF_HIDEFOCUS) != 0) {
5636                                 if ((action == (int) MsgUIState.UIS_CLEAR) != show_focus_cues) {
5637                                         cues |= UICues.ChangeFocus;
5638                                         show_focus_cues = (action == (int) MsgUIState.UIS_CLEAR);
5639                                 }
5640                         }
5641
5642                         if ((cues & UICues.Changed) != UICues.None) {
5643                                 OnChangeUICues (new UICuesEventArgs (cues));
5644                                 Invalidate ();
5645                         }
5646                 }
5647
5648                 #endregion
5649
5650                 #region OnXXX methods
5651                 protected virtual void OnAutoSizeChanged (EventArgs e)
5652                 {
5653                         EventHandler eh = (EventHandler)(Events[AutoSizeChangedEvent]);
5654                         if (eh != null)
5655                                 eh (this, e);
5656                 }
5657
5658                 [EditorBrowsable (EditorBrowsableState.Advanced)]
5659                 protected virtual void OnBackColorChanged(EventArgs e) {
5660                         EventHandler eh = (EventHandler)(Events [BackColorChangedEvent]);
5661                         if (eh != null)
5662                                 eh (this, e);
5663                         for (int i=0; i<child_controls.Count; i++) child_controls[i].OnParentBackColorChanged(e);
5664                 }
5665
5666                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5667                 protected virtual void OnBackgroundImageChanged(EventArgs e) {
5668                         EventHandler eh = (EventHandler)(Events [BackgroundImageChangedEvent]);
5669                         if (eh != null)
5670                                 eh (this, e);
5671                         for (int i=0; i<child_controls.Count; i++) child_controls[i].OnParentBackgroundImageChanged(e);
5672                 }
5673
5674                 [EditorBrowsable (EditorBrowsableState.Advanced)]
5675                 protected virtual void OnBackgroundImageLayoutChanged (EventArgs e)
5676                 {
5677                         EventHandler eh = (EventHandler)(Events[BackgroundImageLayoutChangedEvent]);
5678                         if (eh != null)
5679                                 eh (this, e);
5680                 }
5681
5682                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5683                 protected virtual void OnBindingContextChanged(EventArgs e) {
5684                         CheckDataBindings ();
5685                         EventHandler eh = (EventHandler)(Events [BindingContextChangedEvent]);
5686                         if (eh != null)
5687                                 eh (this, e);
5688                         for (int i=0; i<child_controls.Count; i++) child_controls[i].OnParentBindingContextChanged(e);
5689                 }
5690
5691                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5692                 protected virtual void OnCausesValidationChanged(EventArgs e) {
5693                         EventHandler eh = (EventHandler)(Events [CausesValidationChangedEvent]);
5694                         if (eh != null)
5695                                 eh (this, e);
5696                 }
5697
5698                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5699                 protected virtual void OnChangeUICues(UICuesEventArgs e) {
5700                         UICuesEventHandler eh = (UICuesEventHandler)(Events [ChangeUICuesEvent]);
5701                         if (eh != null)
5702                                 eh (this, e);
5703                 }
5704
5705                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5706                 protected virtual void OnClick(EventArgs e) {
5707                         EventHandler eh = (EventHandler)(Events [ClickEvent]);
5708                         if (eh != null)
5709                                 eh (this, e);
5710                 }
5711
5712                 [EditorBrowsable (EditorBrowsableState.Advanced)]
5713                 protected virtual void OnClientSizeChanged (EventArgs e)
5714                 {
5715                         EventHandler eh = (EventHandler)(Events[ClientSizeChangedEvent]);
5716                         if (eh != null)
5717                                 eh (this, e);
5718                 }
5719
5720                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5721                 protected virtual void OnContextMenuChanged(EventArgs e) {
5722                         EventHandler eh = (EventHandler)(Events [ContextMenuChangedEvent]);
5723                         if (eh != null)
5724                                 eh (this, e);
5725                 }
5726
5727                 [EditorBrowsable (EditorBrowsableState.Advanced)]
5728                 protected virtual void OnContextMenuStripChanged (EventArgs e) {
5729                         EventHandler eh = (EventHandler)(Events [ContextMenuStripChangedEvent]);
5730                         if (eh != null)
5731                                 eh (this, e);
5732                 }
5733
5734                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5735                 protected virtual void OnControlAdded(ControlEventArgs e) {
5736                         ControlEventHandler eh = (ControlEventHandler)(Events [ControlAddedEvent]);
5737                         if (eh != null)
5738                                 eh (this, e);
5739                 }
5740
5741                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5742                 protected virtual void OnControlRemoved(ControlEventArgs e) {
5743                         ControlEventHandler eh = (ControlEventHandler)(Events [ControlRemovedEvent]);
5744                         if (eh != null)
5745                                 eh (this, e);
5746                 }
5747
5748                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5749                 protected virtual void OnCreateControl() {
5750                         // Override me!
5751                 }
5752
5753                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5754                 protected virtual void OnCursorChanged(EventArgs e) {
5755                         EventHandler eh = (EventHandler)(Events [CursorChangedEvent]);
5756                         if (eh != null)
5757                                 eh (this, e);
5758                                 
5759                         for (int i = 0; i < child_controls.Count; i++) child_controls[i].OnParentCursorChanged (e);
5760                 }
5761
5762                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5763                 protected virtual void OnDockChanged(EventArgs e) {
5764                         EventHandler eh = (EventHandler)(Events [DockChangedEvent]);
5765                         if (eh != null)
5766                                 eh (this, e);
5767                 }
5768
5769                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5770                 protected virtual void OnDoubleClick(EventArgs e) {
5771                         EventHandler eh = (EventHandler)(Events [DoubleClickEvent]);
5772                         if (eh != null)
5773                                 eh (this, e);
5774                 }
5775
5776                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5777                 protected virtual void OnDragDrop(DragEventArgs drgevent) {
5778                         DragEventHandler eh = (DragEventHandler)(Events [DragDropEvent]);
5779                         if (eh != null)
5780                                 eh (this, drgevent);
5781                 }
5782
5783                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5784                 protected virtual void OnDragEnter(DragEventArgs drgevent) {
5785                         DragEventHandler eh = (DragEventHandler)(Events [DragEnterEvent]);
5786                         if (eh != null)
5787                                 eh (this, drgevent);
5788                 }
5789
5790                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5791                 protected virtual void OnDragLeave(EventArgs e) {
5792                         EventHandler eh = (EventHandler)(Events [DragLeaveEvent]);
5793                         if (eh != null)
5794                                 eh (this, e);
5795                 }
5796
5797                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5798                 protected virtual void OnDragOver(DragEventArgs drgevent) {
5799                         DragEventHandler eh = (DragEventHandler)(Events [DragOverEvent]);
5800                         if (eh != null)
5801                                 eh (this, drgevent);
5802                 }
5803
5804                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5805                 protected virtual void OnEnabledChanged(EventArgs e) {
5806                         if (IsHandleCreated) {
5807                                 if (this is Form) {
5808                                         if (((Form)this).context == null) {
5809                                                 XplatUI.EnableWindow(window.Handle, Enabled);
5810                                         }
5811                                 } else {
5812                                         XplatUI.EnableWindow(window.Handle, Enabled);
5813                                 }
5814                                 Refresh();
5815                         }
5816
5817                         EventHandler eh = (EventHandler)(Events [EnabledChangedEvent]);
5818                         if (eh != null)
5819                                 eh (this, e);
5820
5821                         foreach (Control c in Controls.GetAllControls ())
5822                                 c.OnParentEnabledChanged (e);
5823                 }
5824
5825                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5826                 protected virtual void OnEnter(EventArgs e) {
5827                         EventHandler eh = (EventHandler)(Events [EnterEvent]);
5828                         if (eh != null)
5829                                 eh (this, e);
5830                 }
5831
5832                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5833                 protected virtual void OnFontChanged(EventArgs e) {
5834                         EventHandler eh = (EventHandler)(Events [FontChangedEvent]);
5835                         if (eh != null)
5836                                 eh (this, e);
5837                         for (int i=0; i<child_controls.Count; i++) child_controls[i].OnParentFontChanged(e);
5838                 }
5839
5840                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5841                 protected virtual void OnForeColorChanged(EventArgs e) {
5842                         EventHandler eh = (EventHandler)(Events [ForeColorChangedEvent]);
5843                         if (eh != null)
5844                                 eh (this, e);
5845                         for (int i=0; i<child_controls.Count; i++) child_controls[i].OnParentForeColorChanged(e);
5846                 }
5847
5848                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5849                 protected virtual void OnGiveFeedback(GiveFeedbackEventArgs gfbevent) {
5850                         GiveFeedbackEventHandler eh = (GiveFeedbackEventHandler)(Events [GiveFeedbackEvent]);
5851                         if (eh != null)
5852                                 eh (this, gfbevent);
5853                 }
5854                 
5855                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5856                 protected virtual void OnGotFocus(EventArgs e) {
5857                         EventHandler eh = (EventHandler)(Events [GotFocusEvent]);
5858                         if (eh != null)
5859                                 eh (this, e);
5860                 }
5861
5862                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5863                 protected virtual void OnHandleCreated(EventArgs e) {
5864                         EventHandler eh = (EventHandler)(Events [HandleCreatedEvent]);
5865                         if (eh != null)
5866                                 eh (this, e);
5867                 }
5868
5869                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5870                 protected virtual void OnHandleDestroyed(EventArgs e) {
5871                         EventHandler eh = (EventHandler)(Events [HandleDestroyedEvent]);
5872                         if (eh != null)
5873                                 eh (this, e);
5874                 }
5875
5876                 internal void RaiseHelpRequested (HelpEventArgs hevent) {
5877                         OnHelpRequested (hevent);
5878                 }
5879                 
5880                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5881                 protected virtual void OnHelpRequested(HelpEventArgs hevent) {
5882                         HelpEventHandler eh = (HelpEventHandler)(Events [HelpRequestedEvent]);
5883                         if (eh != null)
5884                                 eh (this, hevent);
5885                 }
5886
5887                 protected virtual void OnImeModeChanged(EventArgs e) {
5888                         EventHandler eh = (EventHandler)(Events [ImeModeChangedEvent]);
5889                         if (eh != null)
5890                                 eh (this, e);
5891                 }
5892
5893                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5894                 protected virtual void OnInvalidated(InvalidateEventArgs e) {
5895                         if (UseDoubleBuffering) {
5896                                 // should this block be here?  seems like it
5897                                 // would be more at home in
5898                                 // NotifyInvalidated..
5899                                 if (e.InvalidRect == ClientRectangle) {
5900                                         InvalidateBackBuffer ();
5901                                 } else if (backbuffer != null){
5902                                         // we need this Inflate call here so
5903                                         // that the border of the rectangle is
5904                                         // considered Visible (the
5905                                         // invalid_region.IsVisible call) in
5906                                         // the WM_PAINT handling below.
5907                                         Rectangle r = Rectangle.Inflate(e.InvalidRect, 1,1);
5908                                         backbuffer.InvalidRegion.Union (r);
5909                                 }
5910                         }
5911
5912                         InvalidateEventHandler eh = (InvalidateEventHandler)(Events [InvalidatedEvent]);
5913                         if (eh != null)
5914                                 eh (this, e);
5915                 }
5916
5917                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5918                 protected virtual void OnKeyDown(KeyEventArgs e) {
5919                         KeyEventHandler eh = (KeyEventHandler)(Events [KeyDownEvent]);
5920                         if (eh != null)
5921                                 eh (this, e);
5922                 }
5923
5924                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5925                 protected virtual void OnKeyPress(KeyPressEventArgs e) {
5926                         KeyPressEventHandler eh = (KeyPressEventHandler)(Events [KeyPressEvent]);
5927                         if (eh != null)
5928                                 eh (this, e);
5929                 }
5930
5931                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5932                 protected virtual void OnKeyUp(KeyEventArgs e) {
5933                         KeyEventHandler eh = (KeyEventHandler)(Events [KeyUpEvent]);
5934                         if (eh != null)
5935                                 eh (this, e);
5936                 }
5937
5938                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5939                 protected virtual void OnLayout(LayoutEventArgs levent) {
5940                         LayoutEventHandler eh = (LayoutEventHandler)(Events [LayoutEvent]);
5941                         if (eh != null)
5942                                 eh (this, levent);
5943
5944                         Size s = Size;
5945                         
5946                         // If our layout changed our PreferredSize, our parent
5947                         // needs to re-lay us out.  However, it's not always possible to
5948                         // be our preferred size, so only try once so we don't loop forever.
5949                         if (Parent != null && AutoSize && !nested_layout && PreferredSize != s) {
5950                                 nested_layout = true;
5951                                 Parent.PerformLayout ();
5952                                 nested_layout = false;
5953                         }
5954                         
5955                         LayoutEngine.Layout (this, levent);
5956                 }
5957
5958                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5959                 protected virtual void OnLeave(EventArgs e) {
5960                         EventHandler eh = (EventHandler)(Events [LeaveEvent]);
5961                         if (eh != null)
5962                                 eh (this, e);
5963                 }
5964
5965                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5966                 protected virtual void OnLocationChanged(EventArgs e) {
5967                         OnMove(e);
5968                         EventHandler eh = (EventHandler)(Events [LocationChangedEvent]);
5969                         if (eh != null)
5970                                 eh (this, e);
5971                 }
5972
5973                 [EditorBrowsable(EditorBrowsableState.Advanced)]
5974                 protected virtual void OnLostFocus(EventArgs e) {
5975                         EventHandler eh = (EventHandler)(Events [LostFocusEvent]);
5976                         if (eh != null)
5977                                 eh (this, e);
5978                 }
5979
5980                 protected virtual void OnMarginChanged (EventArgs e)
5981                 {
5982                         EventHandler eh = (EventHandler)(Events[MarginChangedEvent]);
5983                         if (eh != null)
5984                                 eh (this, e);
5985                 }
5986                 [EditorBrowsable (EditorBrowsableState.Advanced)]
5987                 protected virtual void OnMouseCaptureChanged (EventArgs e)
5988                 {
5989                         EventHandler eh = (EventHandler)(Events [MouseCaptureChangedEvent]);
5990                         if (eh != null)
5991                                 eh (this, e);
5992                 }
5993
5994                 [EditorBrowsable (EditorBrowsableState.Advanced)]
5995                 protected virtual void OnMouseClick (MouseEventArgs e)
5996                 {
5997                         MouseEventHandler eh = (MouseEventHandler)(Events [MouseClickEvent]);
5998                         if (eh != null)
5999                                 eh (this, e);
6000                 }
6001
6002                 [EditorBrowsable (EditorBrowsableState.Advanced)]
6003                 protected virtual void OnMouseDoubleClick (MouseEventArgs e)
6004                 {
6005                         MouseEventHandler eh = (MouseEventHandler)(Events [MouseDoubleClickEvent]);
6006                         if (eh != null)
6007                                 eh (this, e);
6008                 }
6009
6010                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6011                 protected virtual void OnMouseDown(MouseEventArgs e) {
6012                         MouseEventHandler eh = (MouseEventHandler)(Events [MouseDownEvent]);
6013                         if (eh != null)
6014                                 eh (this, e);
6015                 }
6016
6017                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6018                 protected virtual void OnMouseEnter(EventArgs e) {
6019                         EventHandler eh = (EventHandler)(Events [MouseEnterEvent]);
6020                         if (eh != null)
6021                                 eh (this, e);
6022                 }
6023
6024                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6025                 protected virtual void OnMouseHover(EventArgs e) {
6026                         EventHandler eh = (EventHandler)(Events [MouseHoverEvent]);
6027                         if (eh != null)
6028                                 eh (this, e);
6029                 }
6030
6031                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6032                 protected virtual void OnMouseLeave(EventArgs e) {
6033                         EventHandler eh = (EventHandler)(Events [MouseLeaveEvent]);
6034                         if (eh != null)
6035                                 eh (this, e);
6036                 }
6037
6038                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6039                 protected virtual void OnMouseMove(MouseEventArgs e) {
6040                         MouseEventHandler eh = (MouseEventHandler)(Events [MouseMoveEvent]);
6041                         if (eh != null)
6042                                 eh (this, e);
6043                 }
6044
6045                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6046                 protected virtual void OnMouseUp(MouseEventArgs e) {
6047                         MouseEventHandler eh = (MouseEventHandler)(Events [MouseUpEvent]);
6048                         if (eh != null)
6049                                 eh (this, e);
6050                 }
6051
6052                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6053                 protected virtual void OnMouseWheel(MouseEventArgs e) {
6054                         MouseEventHandler eh = (MouseEventHandler)(Events [MouseWheelEvent]);
6055                         if (eh != null)
6056                                 eh (this, e);
6057                 }
6058
6059                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6060                 protected virtual void OnMove(EventArgs e) {
6061                         EventHandler eh = (EventHandler)(Events [MoveEvent]);
6062                         if (eh != null)
6063                                 eh (this, e);
6064                 }
6065
6066                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6067                 protected virtual void OnNotifyMessage(Message m) {
6068                         // Override me!
6069                 }
6070
6071                 protected virtual void OnPaddingChanged (EventArgs e) {
6072                         EventHandler eh = (EventHandler) (Events [PaddingChangedEvent]);
6073                         if (eh != null)
6074                                 eh (this, e);
6075                 }
6076
6077                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6078                 protected virtual void OnPaint(PaintEventArgs e) {
6079                         PaintEventHandler eh = (PaintEventHandler)(Events [PaintEvent]);
6080                         if (eh != null)
6081                                 eh (this, e);
6082                 }
6083
6084                 internal virtual void OnPaintBackgroundInternal(PaintEventArgs e) {
6085                         // Override me
6086                 }
6087
6088                 internal virtual void OnPaintInternal(PaintEventArgs e) {
6089                         // Override me
6090                 }
6091
6092                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6093                 protected virtual void OnPaintBackground(PaintEventArgs pevent) {
6094                         PaintControlBackground (pevent);
6095                 }
6096
6097                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6098                 protected virtual void OnParentBackColorChanged(EventArgs e) {
6099                         if (background_color.IsEmpty && background_image==null) {
6100                                 Invalidate();
6101                                 OnBackColorChanged(e);
6102                         }
6103                 }
6104
6105                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6106                 protected virtual void OnParentBackgroundImageChanged(EventArgs e) {
6107                         Invalidate();
6108                         OnBackgroundImageChanged(e);
6109                 }
6110
6111                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6112                 protected virtual void OnParentBindingContextChanged(EventArgs e) {
6113                         if (binding_context==null && Parent != null) {
6114                                 binding_context=Parent.binding_context;
6115                                 OnBindingContextChanged(e);
6116                         }
6117                 }
6118
6119                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6120                 protected virtual void OnParentChanged(EventArgs e) {
6121                         EventHandler eh = (EventHandler)(Events [ParentChangedEvent]);
6122                         if (eh != null)
6123                                 eh (this, e);
6124                 }
6125
6126                 [EditorBrowsable (EditorBrowsableState.Advanced)]
6127                 protected virtual void OnParentCursorChanged (EventArgs e)
6128                 {
6129                 }
6130
6131                 [EditorBrowsable (EditorBrowsableState.Advanced)]
6132                 protected virtual void OnParentEnabledChanged(EventArgs e) {
6133                         if (is_enabled) {
6134                                 OnEnabledChanged(e);
6135                         }
6136                 }
6137
6138                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6139                 protected virtual void OnParentFontChanged(EventArgs e) {
6140                         if (font==null) {
6141                                 Invalidate();
6142                                 OnFontChanged(e);
6143                         }
6144                 }
6145
6146                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6147                 protected virtual void OnParentForeColorChanged(EventArgs e) {
6148                         if (foreground_color.IsEmpty) {
6149                                 Invalidate();
6150                                 OnForeColorChanged(e);
6151                         }
6152                 }
6153
6154                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6155                 protected virtual void OnParentRightToLeftChanged(EventArgs e) {
6156                         if (right_to_left==RightToLeft.Inherit) {
6157                                 Invalidate();
6158                                 OnRightToLeftChanged(e);
6159                         }
6160                 }
6161
6162                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6163                 protected virtual void OnParentVisibleChanged(EventArgs e) {
6164                         if (is_visible) {
6165                                 OnVisibleChanged(e);
6166                         }
6167                 }
6168
6169                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6170                 protected virtual void OnQueryContinueDrag (QueryContinueDragEventArgs qcdevent)
6171                 {
6172                         QueryContinueDragEventHandler eh = (QueryContinueDragEventHandler)(Events [QueryContinueDragEvent]);
6173                         if (eh != null)
6174                                 eh (this, qcdevent);
6175                 }
6176
6177                 [EditorBrowsable (EditorBrowsableState.Advanced)]
6178                 protected virtual void OnPreviewKeyDown (PreviewKeyDownEventArgs e)
6179                 {
6180                         PreviewKeyDownEventHandler eh = (PreviewKeyDownEventHandler)(Events[PreviewKeyDownEvent]);
6181                         if (eh != null)
6182                                 eh (this, e);
6183                 }
6184
6185                 [EditorBrowsable (EditorBrowsableState.Advanced)]
6186                 protected virtual void OnPrint (PaintEventArgs e)
6187                 {
6188                         PaintEventHandler eh = (PaintEventHandler)(Events[PaintEvent]);
6189                         if (eh != null)
6190                                 eh (this, e);
6191                 }
6192
6193                 [EditorBrowsable (EditorBrowsableState.Advanced)]
6194                 protected virtual void OnRegionChanged (EventArgs e)
6195                 {
6196                         EventHandler eh = (EventHandler)(Events[RegionChangedEvent]);
6197                         if (eh != null)
6198                                 eh (this, e);
6199                 }
6200
6201                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6202                 protected virtual void OnResize(EventArgs e) {
6203                         OnResizeInternal (e);
6204                 }
6205                 
6206                 internal virtual void OnResizeInternal (EventArgs e) {
6207                         PerformLayout(this, "Bounds");
6208
6209                         EventHandler eh = (EventHandler)(Events [ResizeEvent]);
6210                         if (eh != null)
6211                                 eh (this, e);
6212                 }
6213
6214                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6215                 protected virtual void OnRightToLeftChanged(EventArgs e) {
6216                         EventHandler eh = (EventHandler)(Events [RightToLeftChangedEvent]);
6217                         if (eh != null)
6218                                 eh (this, e);
6219                         for (int i=0; i<child_controls.Count; i++) child_controls[i].OnParentRightToLeftChanged(e);
6220                 }
6221
6222                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6223                 protected virtual void OnSizeChanged(EventArgs e) {
6224                         DisposeBackBuffer ();
6225                         OnResize(e);
6226                         EventHandler eh = (EventHandler)(Events [SizeChangedEvent]);
6227                         if (eh != null)
6228                                 eh (this, e);
6229                 }
6230
6231                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6232                 protected virtual void OnStyleChanged(EventArgs e) {
6233                         EventHandler eh = (EventHandler)(Events [StyleChangedEvent]);
6234                         if (eh != null)
6235                                 eh (this, e);
6236                 }
6237
6238                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6239                 protected virtual void OnSystemColorsChanged(EventArgs e) {
6240                         EventHandler eh = (EventHandler)(Events [SystemColorsChangedEvent]);
6241                         if (eh != null)
6242                                 eh (this, e);
6243                 }
6244
6245                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6246                 protected virtual void OnTabIndexChanged(EventArgs e) {
6247                         EventHandler eh = (EventHandler)(Events [TabIndexChangedEvent]);
6248                         if (eh != null)
6249                                 eh (this, e);
6250                 }
6251
6252                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6253                 protected virtual void OnTabStopChanged(EventArgs e) {
6254                         EventHandler eh = (EventHandler)(Events [TabStopChangedEvent]);
6255                         if (eh != null)
6256                                 eh (this, e);
6257                 }
6258
6259                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6260                 protected virtual void OnTextChanged(EventArgs e) {
6261                         EventHandler eh = (EventHandler)(Events [TextChangedEvent]);
6262                         if (eh != null)
6263                                 eh (this, e);
6264                 }
6265
6266                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6267                 protected virtual void OnValidated(EventArgs e) {
6268                         EventHandler eh = (EventHandler)(Events [ValidatedEvent]);
6269                         if (eh != null)
6270                                 eh (this, e);
6271                 }
6272
6273                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6274                 protected virtual void OnValidating(System.ComponentModel.CancelEventArgs e) {
6275                         CancelEventHandler eh = (CancelEventHandler)(Events [ValidatingEvent]);
6276                         if (eh != null)
6277                                 eh (this, e);
6278                 }
6279
6280                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6281                 protected virtual void OnVisibleChanged(EventArgs e) {
6282                         if (Visible)
6283                                 CreateControl ();
6284                                 
6285                         EventHandler eh = (EventHandler)(Events [VisibleChangedEvent]);
6286                         if (eh != null)
6287                                 eh (this, e);
6288
6289                         // We need to tell our kids (including implicit ones)
6290                         foreach (Control c in Controls.GetAllControls ())
6291                                 if (c.Visible)
6292                                         c.OnParentVisibleChanged (e);
6293                 }
6294                 #endregion      // OnXXX methods
6295
6296                 #region Events
6297                 static object AutoSizeChangedEvent = new object ();
6298                 static object BackColorChangedEvent = new object ();
6299                 static object BackgroundImageChangedEvent = new object ();
6300                 static object BackgroundImageLayoutChangedEvent = new object ();
6301                 static object BindingContextChangedEvent = new object ();
6302                 static object CausesValidationChangedEvent = new object ();
6303                 static object ChangeUICuesEvent = new object ();
6304                 static object ClickEvent = new object ();
6305                 static object ClientSizeChangedEvent = new object ();
6306                 static object ContextMenuChangedEvent = new object ();
6307                 static object ContextMenuStripChangedEvent = new object ();
6308                 static object ControlAddedEvent = new object ();
6309                 static object ControlRemovedEvent = new object ();
6310                 static object CursorChangedEvent = new object ();
6311                 static object DockChangedEvent = new object ();
6312                 static object DoubleClickEvent = new object ();
6313                 static object DragDropEvent = new object ();
6314                 static object DragEnterEvent = new object ();
6315                 static object DragLeaveEvent = new object ();
6316                 static object DragOverEvent = new object ();
6317                 static object EnabledChangedEvent = new object ();
6318                 static object EnterEvent = new object ();
6319                 static object FontChangedEvent = new object ();
6320                 static object ForeColorChangedEvent = new object ();
6321                 static object GiveFeedbackEvent = new object ();
6322                 static object GotFocusEvent = new object ();
6323                 static object HandleCreatedEvent = new object ();
6324                 static object HandleDestroyedEvent = new object ();
6325                 static object HelpRequestedEvent = new object ();
6326                 static object ImeModeChangedEvent = new object ();
6327                 static object InvalidatedEvent = new object ();
6328                 static object KeyDownEvent = new object ();
6329                 static object KeyPressEvent = new object ();
6330                 static object KeyUpEvent = new object ();
6331                 static object LayoutEvent = new object ();
6332                 static object LeaveEvent = new object ();
6333                 static object LocationChangedEvent = new object ();
6334                 static object LostFocusEvent = new object ();
6335                 static object MarginChangedEvent = new object ();
6336                 static object MouseCaptureChangedEvent = new object ();
6337                 static object MouseClickEvent = new object ();
6338                 static object MouseDoubleClickEvent = new object ();
6339                 static object MouseDownEvent = new object ();
6340                 static object MouseEnterEvent = new object ();
6341                 static object MouseHoverEvent = new object ();
6342                 static object MouseLeaveEvent = new object ();
6343                 static object MouseMoveEvent = new object ();
6344                 static object MouseUpEvent = new object ();
6345                 static object MouseWheelEvent = new object ();
6346                 static object MoveEvent = new object ();
6347                 static object PaddingChangedEvent = new object ();
6348                 static object PaintEvent = new object ();
6349                 static object ParentChangedEvent = new object ();
6350                 static object PreviewKeyDownEvent = new object ();
6351                 static object QueryAccessibilityHelpEvent = new object ();
6352                 static object QueryContinueDragEvent = new object ();
6353                 static object RegionChangedEvent = new object ();
6354                 static object ResizeEvent = new object ();
6355                 static object RightToLeftChangedEvent = new object ();
6356                 static object SizeChangedEvent = new object ();
6357                 static object StyleChangedEvent = new object ();
6358                 static object SystemColorsChangedEvent = new object ();
6359                 static object TabIndexChangedEvent = new object ();
6360                 static object TabStopChangedEvent = new object ();
6361                 static object TextChangedEvent = new object ();
6362                 static object ValidatedEvent = new object ();
6363                 static object ValidatingEvent = new object ();
6364                 static object VisibleChangedEvent = new object ();
6365
6366                 [Browsable (false)]
6367                 [EditorBrowsable (EditorBrowsableState.Never)]
6368                 public event EventHandler AutoSizeChanged {
6369                         add { Events.AddHandler (AutoSizeChangedEvent, value);}
6370                         remove {Events.RemoveHandler (AutoSizeChangedEvent, value);}
6371                 }
6372                 public event EventHandler BackColorChanged {
6373                         add { Events.AddHandler (BackColorChangedEvent, value); }
6374                         remove { Events.RemoveHandler (BackColorChangedEvent, value); }
6375                 }
6376
6377                 public event EventHandler BackgroundImageChanged {
6378                         add { Events.AddHandler (BackgroundImageChangedEvent, value); }
6379                         remove { Events.RemoveHandler (BackgroundImageChangedEvent, value); }
6380                 }
6381
6382                 public event EventHandler BackgroundImageLayoutChanged {
6383                         add {Events.AddHandler (BackgroundImageLayoutChangedEvent, value);}
6384                         remove {Events.RemoveHandler (BackgroundImageLayoutChangedEvent, value);}
6385                 }
6386
6387                 public event EventHandler BindingContextChanged {
6388                         add { Events.AddHandler (BindingContextChangedEvent, value); }
6389                         remove { Events.RemoveHandler (BindingContextChangedEvent, value); }
6390                 }
6391
6392                 public event EventHandler CausesValidationChanged {
6393                         add { Events.AddHandler (CausesValidationChangedEvent, value); }
6394                         remove { Events.RemoveHandler (CausesValidationChangedEvent, value); }
6395                 }
6396
6397                 public event UICuesEventHandler ChangeUICues {
6398                         add { Events.AddHandler (ChangeUICuesEvent, value); }
6399                         remove { Events.RemoveHandler (ChangeUICuesEvent, value); }
6400                 }
6401
6402                 public event EventHandler Click {
6403                         add { Events.AddHandler (ClickEvent, value); }
6404                         remove { Events.RemoveHandler (ClickEvent, value); }
6405                 }
6406                 
6407                 public event EventHandler ClientSizeChanged {
6408                         add {Events.AddHandler (ClientSizeChangedEvent, value);}
6409                         remove {Events.RemoveHandler (ClientSizeChangedEvent, value);}
6410                 }
6411
6412                 [Browsable (false)]
6413                 public event EventHandler ContextMenuChanged {
6414                         add { Events.AddHandler (ContextMenuChangedEvent, value); }
6415                         remove { Events.RemoveHandler (ContextMenuChangedEvent, value); }
6416                 }
6417
6418                 public event EventHandler ContextMenuStripChanged {
6419                         add { Events.AddHandler (ContextMenuStripChangedEvent, value); }
6420                         remove { Events.RemoveHandler (ContextMenuStripChangedEvent, value);}
6421                 }
6422
6423
6424                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6425                 [Browsable(true)]
6426                 public event ControlEventHandler ControlAdded {
6427                         add { Events.AddHandler (ControlAddedEvent, value); }
6428                         remove { Events.RemoveHandler (ControlAddedEvent, value); }
6429                 }
6430
6431                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6432                 [Browsable(true)]
6433                 public event ControlEventHandler ControlRemoved {
6434                         add { Events.AddHandler (ControlRemovedEvent, value); }
6435                         remove { Events.RemoveHandler (ControlRemovedEvent, value); }
6436                 }
6437
6438                 [MWFDescription("Fired when the cursor for the control has been changed"), MWFCategory("PropertyChanged")]
6439                 public event EventHandler CursorChanged {
6440                         add { Events.AddHandler (CursorChangedEvent, value); }
6441                         remove { Events.RemoveHandler (CursorChangedEvent, value); }
6442                 }
6443                 public event EventHandler DockChanged {
6444                         add { Events.AddHandler (DockChangedEvent, value); }
6445                         remove { Events.RemoveHandler (DockChangedEvent, value); }
6446                 }
6447
6448                 public event EventHandler DoubleClick {
6449                         add { Events.AddHandler (DoubleClickEvent, value); }
6450                         remove { Events.RemoveHandler (DoubleClickEvent, value); }
6451                 }
6452
6453                 public event DragEventHandler DragDrop {
6454                         add { Events.AddHandler (DragDropEvent, value); }
6455                         remove { Events.RemoveHandler (DragDropEvent, value); }
6456                 }
6457
6458                 public event DragEventHandler DragEnter {
6459                         add { Events.AddHandler (DragEnterEvent, value); }
6460                         remove { Events.RemoveHandler (DragEnterEvent, value); }
6461                 }
6462
6463                 public event EventHandler DragLeave {
6464                         add { Events.AddHandler (DragLeaveEvent, value); }
6465                         remove { Events.RemoveHandler (DragLeaveEvent, value); }
6466                 }
6467
6468                 public event DragEventHandler DragOver {
6469                         add { Events.AddHandler (DragOverEvent, value); }
6470                         remove { Events.RemoveHandler (DragOverEvent, value); }
6471                 }
6472
6473                 public event EventHandler EnabledChanged {
6474                         add { Events.AddHandler (EnabledChangedEvent, value); }
6475                         remove { Events.RemoveHandler (EnabledChangedEvent, value); }
6476                 }
6477
6478                 public event EventHandler Enter {
6479                         add { Events.AddHandler (EnterEvent, value); }
6480                         remove { Events.RemoveHandler (EnterEvent, value); }
6481                 }
6482
6483                 public event EventHandler FontChanged {
6484                         add { Events.AddHandler (FontChangedEvent, value); }
6485                         remove { Events.RemoveHandler (FontChangedEvent, value); }
6486                 }
6487
6488                 public event EventHandler ForeColorChanged {
6489                         add { Events.AddHandler (ForeColorChangedEvent, value); }
6490                         remove { Events.RemoveHandler (ForeColorChangedEvent, value); }
6491                 }
6492
6493                 public event GiveFeedbackEventHandler GiveFeedback {
6494                         add { Events.AddHandler (GiveFeedbackEvent, value); }
6495                         remove { Events.RemoveHandler (GiveFeedbackEvent, value); }
6496                 }
6497
6498                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6499                 [Browsable(false)]
6500                 public event EventHandler GotFocus {
6501                         add { Events.AddHandler (GotFocusEvent, value); }
6502                         remove { Events.RemoveHandler (GotFocusEvent, value); }
6503                 }
6504
6505
6506                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6507                 [Browsable(false)]
6508                 public event EventHandler HandleCreated {
6509                         add { Events.AddHandler (HandleCreatedEvent, value); }
6510                         remove { Events.RemoveHandler (HandleCreatedEvent, value); }
6511                 }
6512
6513                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6514                 [Browsable(false)]
6515                 public event EventHandler HandleDestroyed {
6516                         add { Events.AddHandler (HandleDestroyedEvent, value); }
6517                         remove { Events.RemoveHandler (HandleDestroyedEvent, value); }
6518                 }
6519
6520                 public event HelpEventHandler HelpRequested {
6521                         add { Events.AddHandler (HelpRequestedEvent, value); }
6522                         remove { Events.RemoveHandler (HelpRequestedEvent, value); }
6523                 }
6524
6525                 public event EventHandler ImeModeChanged {
6526                         add { Events.AddHandler (ImeModeChangedEvent, value); }
6527                         remove { Events.RemoveHandler (ImeModeChangedEvent, value); }
6528                 }
6529
6530                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6531                 [Browsable(false)]
6532                 public event InvalidateEventHandler Invalidated {
6533                         add { Events.AddHandler (InvalidatedEvent, value); }
6534                         remove { Events.RemoveHandler (InvalidatedEvent, value); }
6535                 }
6536
6537                 public event KeyEventHandler KeyDown {
6538                         add { Events.AddHandler (KeyDownEvent, value); }
6539                         remove { Events.RemoveHandler (KeyDownEvent, value); }
6540                 }
6541
6542                 public event KeyPressEventHandler KeyPress {
6543                         add { Events.AddHandler (KeyPressEvent, value); }
6544                         remove { Events.RemoveHandler (KeyPressEvent, value); }
6545                 }
6546
6547                 public event KeyEventHandler KeyUp {
6548                         add { Events.AddHandler (KeyUpEvent, value); }
6549                         remove { Events.RemoveHandler (KeyUpEvent, value); }
6550                 }
6551
6552                 public event LayoutEventHandler Layout {
6553                         add { Events.AddHandler (LayoutEvent, value); }
6554                         remove { Events.RemoveHandler (LayoutEvent, value); }
6555                 }
6556
6557                 public event EventHandler Leave {
6558                         add { Events.AddHandler (LeaveEvent, value); }
6559                         remove { Events.RemoveHandler (LeaveEvent, value); }
6560                 }
6561
6562                 public event EventHandler LocationChanged {
6563                         add { Events.AddHandler (LocationChangedEvent, value); }
6564                         remove { Events.RemoveHandler (LocationChangedEvent, value); }
6565                 }
6566
6567                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6568                 [Browsable(false)]
6569                 public event EventHandler LostFocus {
6570                         add { Events.AddHandler (LostFocusEvent, value); }
6571                         remove { Events.RemoveHandler (LostFocusEvent, value); }
6572                 }
6573
6574                 public event EventHandler MarginChanged {
6575                         add { Events.AddHandler (MarginChangedEvent, value); }
6576                         remove {Events.RemoveHandler (MarginChangedEvent, value); }
6577                 }
6578
6579                 public event EventHandler MouseCaptureChanged {
6580                         add { Events.AddHandler (MouseCaptureChangedEvent, value); }
6581                         remove { Events.RemoveHandler (MouseCaptureChangedEvent, value); }
6582                 }
6583                 public event MouseEventHandler MouseClick
6584                 {
6585                         add { Events.AddHandler (MouseClickEvent, value); }
6586                         remove { Events.RemoveHandler (MouseClickEvent, value); }
6587                 }
6588                 public event MouseEventHandler MouseDoubleClick
6589                 {
6590                         add { Events.AddHandler (MouseDoubleClickEvent, value); }
6591                         remove { Events.RemoveHandler (MouseDoubleClickEvent, value); }
6592                 }
6593                 public event MouseEventHandler MouseDown {
6594                         add { Events.AddHandler (MouseDownEvent, value); }
6595                         remove { Events.RemoveHandler (MouseDownEvent, value); }
6596                 }
6597
6598                 public event EventHandler MouseEnter {
6599                         add { Events.AddHandler (MouseEnterEvent, value); }
6600                         remove { Events.RemoveHandler (MouseEnterEvent, value); }
6601                 }
6602
6603                 public event EventHandler MouseHover {
6604                         add { Events.AddHandler (MouseHoverEvent, value); }
6605                         remove { Events.RemoveHandler (MouseHoverEvent, value); }
6606                 }
6607
6608                 public event EventHandler MouseLeave {
6609                         add { Events.AddHandler (MouseLeaveEvent, value); }
6610                         remove { Events.RemoveHandler (MouseLeaveEvent, value); }
6611                 }
6612
6613                 public event MouseEventHandler MouseMove {
6614                         add { Events.AddHandler (MouseMoveEvent, value); }
6615                         remove { Events.RemoveHandler (MouseMoveEvent, value); }
6616                 }
6617
6618                 public event MouseEventHandler MouseUp {
6619                         add { Events.AddHandler (MouseUpEvent, value); }
6620                         remove { Events.RemoveHandler (MouseUpEvent, value); }
6621                 }
6622
6623                 [EditorBrowsable(EditorBrowsableState.Advanced)]
6624                 [Browsable(false)]
6625                 public event MouseEventHandler MouseWheel {
6626                         add { Events.AddHandler (MouseWheelEvent, value); }
6627                         remove { Events.RemoveHandler (MouseWheelEvent, value); }
6628                 }
6629
6630                 public event EventHandler Move {
6631                         add { Events.AddHandler (MoveEvent, value); }
6632                         remove { Events.RemoveHandler (MoveEvent, value); }
6633                 }
6634                 public event EventHandler PaddingChanged
6635                 {
6636                         add { Events.AddHandler (PaddingChangedEvent, value); }
6637                         remove { Events.RemoveHandler (PaddingChangedEvent, value); }
6638                 }
6639                 public event PaintEventHandler Paint {
6640                         add { Events.AddHandler (PaintEvent, value); }
6641                         remove { Events.RemoveHandler (PaintEvent, value); }
6642                 }
6643
6644                 public event EventHandler ParentChanged {
6645                         add { Events.AddHandler (ParentChangedEvent, value); }
6646                         remove { Events.RemoveHandler (ParentChangedEvent, value); }
6647                 }
6648
6649                 public event PreviewKeyDownEventHandler PreviewKeyDown {
6650                         add { Events.AddHandler (PreviewKeyDownEvent, value); }
6651                         remove { Events.RemoveHandler (PreviewKeyDownEvent, value); }
6652                 }
6653
6654                 public event QueryAccessibilityHelpEventHandler QueryAccessibilityHelp {
6655                         add { Events.AddHandler (QueryAccessibilityHelpEvent, value); }
6656                         remove { Events.RemoveHandler (QueryAccessibilityHelpEvent, value); }
6657                 }
6658
6659                 public event QueryContinueDragEventHandler QueryContinueDrag {
6660                         add { Events.AddHandler (QueryContinueDragEvent, value); }
6661                         remove { Events.RemoveHandler (QueryContinueDragEvent, value); }
6662                 }
6663
6664                 public event EventHandler RegionChanged {
6665                         add { Events.AddHandler (RegionChangedEvent, value); }
6666                         remove { Events.RemoveHandler (RegionChangedEvent, value); }
6667                 }
6668
6669                 [EditorBrowsable (EditorBrowsableState.Advanced)]
6670                 public event EventHandler Resize {
6671                         add { Events.AddHandler (ResizeEvent, value); }
6672                         remove { Events.RemoveHandler (ResizeEvent, value); }
6673                 }
6674
6675                 public event EventHandler RightToLeftChanged {
6676                         add { Events.AddHandler (RightToLeftChangedEvent, value); }
6677                         remove { Events.RemoveHandler (RightToLeftChangedEvent, value); }
6678                 }
6679
6680                 public event EventHandler SizeChanged {
6681                         add { Events.AddHandler (SizeChangedEvent, value); }
6682                         remove { Events.RemoveHandler (SizeChangedEvent, value); }
6683                 }
6684
6685                 public event EventHandler StyleChanged {
6686                         add { Events.AddHandler (StyleChangedEvent, value); }
6687                         remove { Events.RemoveHandler (StyleChangedEvent, value); }
6688                 }
6689
6690                 public event EventHandler SystemColorsChanged {
6691                         add { Events.AddHandler (SystemColorsChangedEvent, value); }
6692                         remove { Events.RemoveHandler (SystemColorsChangedEvent, value); }
6693                 }
6694
6695                 public event EventHandler TabIndexChanged {
6696                         add { Events.AddHandler (TabIndexChangedEvent, value); }
6697                         remove { Events.RemoveHandler (TabIndexChangedEvent, value); }
6698                 }
6699
6700                 public event EventHandler TabStopChanged {
6701                         add { Events.AddHandler (TabStopChangedEvent, value); }
6702                         remove { Events.RemoveHandler (TabStopChangedEvent, value); }
6703                 }
6704
6705                 public event EventHandler TextChanged {
6706                         add { Events.AddHandler (TextChangedEvent, value); }
6707                         remove { Events.RemoveHandler (TextChangedEvent, value); }
6708                 }
6709
6710                 public event EventHandler Validated {
6711                         add { Events.AddHandler (ValidatedEvent, value); }
6712                         remove { Events.RemoveHandler (ValidatedEvent, value); }
6713                 }
6714
6715                 public event CancelEventHandler Validating {
6716                         add { Events.AddHandler (ValidatingEvent, value); }
6717                         remove { Events.RemoveHandler (ValidatingEvent, value); }
6718                 }
6719
6720                 public event EventHandler VisibleChanged {
6721                         add { Events.AddHandler (VisibleChangedEvent, value); }
6722                         remove { Events.RemoveHandler (VisibleChangedEvent, value); }
6723                 }
6724
6725                 #endregion      // Events
6726         }
6727 }