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