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