* TreeView.cs: Don't draw the selected node when we lose
[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 void DndEnter (DragEventArgs e)
921                 {
922                         try {
923                                 OnDragEnter (e);
924                         } catch { }
925                 }
926
927                 internal void DndOver (DragEventArgs e)
928                 {
929                         try {
930                                 OnDragOver (e);
931                         } catch { }
932                 }
933
934                 internal 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 void DndLeave (EventArgs e)
945                 {
946                         try {
947                                 OnDragLeave (e);
948                         } catch { }
949                 }
950
951                 internal void DnDFeedback(GiveFeedbackEventArgs e)
952                 {
953                         OnGiveFeedback(e);
954                 }
955
956                 internal void DnDContinueDrag(QueryContinueDragEventArgs e) {
957                         OnQueryContinueDrag(e);
958                 }
959                 
960                 internal static MouseButtons FromParamToMouseButtons (int param) {              
961                         MouseButtons buttons = MouseButtons.None;
962                                         
963                         if ((param & (int) MsgButtons.MK_LBUTTON) != 0)
964                                 buttons |= MouseButtons.Left;
965                         
966                         if ((param & (int) MsgButtons.MK_MBUTTON) != 0)
967                                 buttons |= MouseButtons.Middle;
968                                 
969                         if ((param & (int) MsgButtons.MK_RBUTTON) != 0)
970                                 buttons |= MouseButtons.Right;          
971                                 
972                         return buttons;
973
974                 }
975
976                 internal virtual bool ProcessControlMnemonic(char charCode) {
977                         return ProcessMnemonic(charCode);
978                 }
979
980                 private static Control FindFlatForward(Control container, Control start) {
981                         Control found;
982                         int     index;
983                         int     end;
984
985                         found = null;
986                         end = container.child_controls.Count;
987
988                         if (start != null) {
989                                 index = start.tab_index;
990                         } else {
991                                 index = -1;
992                         }
993
994                         for (int i = 0; i < end; i++) {
995                                 if (found == null) {
996                                         if (container.child_controls[i].tab_index > index) {
997                                                 found = container.child_controls[i];
998                                         }
999                                 } else if (found.tab_index > container.child_controls[i].tab_index) {
1000                                         if (container.child_controls[i].tab_index > index) {
1001                                                 found = container.child_controls[i];
1002                                         }
1003                                 }
1004                         }
1005                         return found;
1006                 }
1007
1008                 private static Control FindControlForward(Control container, Control start) {
1009                         Control found;
1010                         Control p;
1011
1012                         found = null;
1013
1014                         if (start != null) {
1015                                 if ((start is IContainerControl) || start.GetStyle(ControlStyles.ContainerControl)) {
1016                                         found = FindControlForward(start, null);
1017                                         if (found != null) {
1018                                                 return found;
1019                                         }
1020                                 }
1021
1022                                 p = start.parent;
1023                                 while (p != container) {
1024                                         found = FindFlatForward(p, start);
1025                                         if (found != null) {
1026                                                 return found;
1027                                         }
1028                                         start = p;
1029                                         p = p.parent;
1030                                 }
1031                         }
1032                         return FindFlatForward(container, start);
1033                 }
1034
1035                 private static Control FindFlatBackward(Control container, Control start) {
1036                         Control found;
1037                         int     index;
1038                         int     end;
1039
1040                         found = null;
1041                         end = container.child_controls.Count;
1042
1043                         if (start != null) {
1044                                 index = start.tab_index;
1045                         } else {
1046                                 // FIXME: Possible speed-up: Keep the highest taborder index in the container
1047                                 index = -1;
1048                                 for (int i = 0; i < end; i++) {
1049                                         if (container.child_controls[i].tab_index > index) {
1050                                                 index = container.child_controls[i].tab_index;
1051                                         }
1052                                 }
1053                                 index++;
1054                         }
1055
1056                         for (int i = 0; i < end; i++) {
1057                                 if (found == null) {
1058                                         if (container.child_controls[i].tab_index < index) {
1059                                                 found = container.child_controls[i];
1060                                         }
1061                                 } else if (found.tab_index < container.child_controls[i].tab_index) {
1062                                         if (container.child_controls[i].tab_index < index) {
1063                                                 found = container.child_controls[i];
1064                                         }
1065                                 }
1066                         }
1067                         return found;
1068                 }
1069
1070                 private static Control FindControlBackward(Control container, Control start) {
1071                         Control found;
1072
1073                         found = null;
1074
1075                         if (start != null) {
1076                                 found = FindFlatBackward(start.parent, start);
1077                                 if (found == null && start.parent != container) {
1078                                         return start.parent;
1079                                 }
1080                         }
1081                         if (found == null) {
1082                                 found = FindFlatBackward(container, start);
1083                         }
1084
1085                         while ((found != null) && ((found is IContainerControl) || found.GetStyle(ControlStyles.ContainerControl))) {
1086                                 found = FindControlBackward(found, null);
1087                                 if (found != null) {
1088                                         return found;
1089                                 }
1090                         }
1091
1092                         return found;
1093                 }
1094
1095                 private void HandleClick(int clicks) {
1096                         if (GetStyle(ControlStyles.StandardClick)) {
1097                                 if (clicks > 1) {
1098                                         if (GetStyle(ControlStyles.StandardDoubleClick)) {
1099                                                 OnDoubleClick(EventArgs.Empty);
1100                                         } else {
1101                                                 OnClick(EventArgs.Empty);
1102                                         }
1103                                 } else {
1104                                         OnClick(EventArgs.Empty);
1105                                 }
1106                         }
1107                 }
1108
1109                 private void CheckDataBindings ()
1110                 {
1111                         if (data_bindings == null)
1112                                 return;
1113
1114                         BindingContext binding_context = BindingContext;
1115                         foreach (Binding binding in data_bindings) {
1116                                 binding.Check (binding_context);
1117                         }
1118                 }
1119                 #endregion      // Private & Internal Methods
1120
1121                 #region Public Static Properties
1122                 public static Color DefaultBackColor {
1123                         get {
1124                                 return ThemeEngine.Current.DefaultControlBackColor;
1125                         }
1126                 }
1127
1128                 public static Font DefaultFont {
1129                         get {
1130                                 return ThemeEngine.Current.DefaultFont;
1131                         }
1132                 }
1133
1134                 public static Color DefaultForeColor {
1135                         get {
1136                                 return ThemeEngine.Current.DefaultControlForeColor;
1137                         }
1138                 }
1139
1140                 public static Keys ModifierKeys {
1141                         get {
1142                                 return XplatUI.State.ModifierKeys;
1143                         }
1144                 }
1145
1146                 public static MouseButtons MouseButtons {
1147                         get {
1148                                 return XplatUI.State.MouseButtons;
1149                         }
1150                 }
1151
1152                 public static Point MousePosition {
1153                         get {
1154                                 return Cursor.Position;
1155                         }
1156                 }
1157                 
1158 #if NET_2_0
1159                 [MonoTODO]
1160                 public static bool CheckForIllegalCrossThreadCalls 
1161                 {
1162                         set {
1163                         }
1164                         get {
1165                                 return false;
1166                         }
1167                 }
1168 #endif
1169                 #endregion      // Public Static Properties
1170
1171                 #region Public Instance Properties
1172                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1173                 [Browsable(false)]
1174                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1175                 public AccessibleObject AccessibilityObject {
1176                         get {
1177                                 if (accessibility_object==null) {
1178                                         accessibility_object=CreateAccessibilityInstance();
1179                                 }
1180                                 return accessibility_object;
1181                         }
1182                 }
1183
1184                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1185                 [Browsable(false)]
1186                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1187                 public string AccessibleDefaultActionDescription {
1188                         get {
1189                                 return AccessibilityObject.default_action;
1190                         }
1191
1192                         set {
1193                                 AccessibilityObject.default_action=value;
1194                         }
1195                 }
1196
1197                 [Localizable(true)]
1198                 [DefaultValue(null)]
1199                 public string AccessibleDescription {
1200                         get {
1201                                 return AccessibilityObject.description;
1202                         }
1203
1204                         set {
1205                                 AccessibilityObject.description=value;
1206                         }
1207                 }
1208
1209                 [Localizable(true)]
1210                 [DefaultValue(null)]
1211                 public string AccessibleName {
1212                         get {
1213                                 return AccessibilityObject.Name;
1214                         }
1215
1216                         set {
1217                                 AccessibilityObject.Name=value;
1218                         }
1219                 }
1220
1221                 [DefaultValue(AccessibleRole.Default)]
1222                 [MWFDescription("Role of the control"), MWFCategory("Accessibility")]
1223                 public AccessibleRole AccessibleRole {
1224                         get {
1225                                 return AccessibilityObject.role;
1226                         }
1227
1228                         set {
1229                                 AccessibilityObject.role=value;
1230                         }
1231                 }
1232
1233                 [DefaultValue(false)]
1234                 public virtual bool AllowDrop {
1235                         get {
1236                                 return allow_drop;
1237                         }
1238
1239                         set {
1240                                 if (allow_drop == value)
1241                                         return;
1242                                 allow_drop = value;
1243                                 UpdateStyles();
1244                                 XplatUI.SetAllowDrop (Handle, value);
1245                         }
1246                 }
1247
1248                 [Localizable(true)]
1249                 [RefreshProperties(RefreshProperties.Repaint)]
1250                 [DefaultValue(AnchorStyles.Top | AnchorStyles.Left)]
1251                 public virtual AnchorStyles Anchor {
1252                         get {
1253                                 return anchor_style;
1254                         }
1255
1256                         set {
1257                                 anchor_style=value;
1258
1259                                 if (parent != null) {
1260                                         parent.PerformLayout(this, "Parent");
1261                                 }
1262                         }
1263                 }
1264
1265                 [DispId(-501)]
1266                 public virtual Color BackColor {
1267                         get {
1268                                 if (background_color.IsEmpty) {
1269                                         if (parent!=null) {
1270                                                 return parent.BackColor;
1271                                         }
1272                                         return DefaultBackColor;
1273                                 }
1274                                 return background_color;
1275                         }
1276
1277                         set {
1278                                 background_color=value;
1279                                 SetChildColor(this);
1280                                 OnBackColorChanged(EventArgs.Empty);
1281                                 Invalidate();
1282                         }
1283                 }
1284
1285                 [Localizable(true)]
1286                 [DefaultValue(null)]
1287                 public virtual Image BackgroundImage {
1288                         get {
1289                                 return background_image;
1290                         }
1291
1292                         set {
1293                                 if (background_image!=value) {
1294                                         background_image=value;
1295                                         OnBackgroundImageChanged(EventArgs.Empty);
1296                                 }
1297                         }
1298                 }
1299
1300                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1301                 [Browsable(false)]
1302                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1303                 public virtual BindingContext BindingContext {
1304                         get {
1305                                 if (binding_context != null)
1306                                         return binding_context;
1307                                 if (Parent == null)
1308                                         return null;
1309                                 binding_context = Parent.BindingContext;
1310                                 return binding_context;
1311                         }
1312                         set {
1313                                 if (binding_context != value) {
1314                                         binding_context = value;
1315                                         OnBindingContextChanged(EventArgs.Empty);
1316                                 }
1317                         }
1318                 }
1319
1320                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1321                 [Browsable(false)]
1322                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1323                 public int Bottom {
1324                         get {
1325                                 return bounds.Y+bounds.Height;
1326                         }
1327                 }
1328
1329                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1330                 [Browsable(false)]
1331                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1332                 public Rectangle Bounds {
1333                         get {
1334                                 return this.bounds;
1335                         }
1336
1337                         set {
1338                                 SetBoundsCore(value.Left, value.Top, value.Width, value.Height, BoundsSpecified.All);
1339                         }
1340                 }
1341
1342                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1343                 [Browsable(false)]
1344                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1345                 public bool CanFocus {
1346                         get {
1347                                 if (Visible && is_enabled && GetStyle(ControlStyles.Selectable)) {
1348                                         return true;
1349                                 }
1350                                 return false;
1351                         }
1352                 }
1353
1354                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1355                 [Browsable(false)]
1356                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1357                 public bool CanSelect {
1358                         get {
1359                                 Control parent;
1360
1361                                 if (!GetStyle(ControlStyles.Selectable) || this.parent == null) {
1362                                         return false;
1363                                 }
1364
1365                                 parent = this.parent;
1366                                 while (parent != null) {
1367                                         if (!parent.is_visible || !parent.is_enabled) {
1368                                                 return false;
1369                                         }
1370
1371                                         parent = parent.parent;
1372                                 }
1373                                 return true;
1374                         }
1375                 }
1376
1377                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1378                 [Browsable(false)]
1379                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1380                 public bool Capture {
1381                         get {
1382                                 return this.is_captured;
1383                         }
1384
1385                         set {
1386                                 if (this.IsHandleCreated) {
1387                                         if (value && !is_captured) {
1388                                                 is_captured = true;
1389                                                 XplatUI.GrabWindow(this.window.Handle, IntPtr.Zero);
1390                                         } else if (!value && is_captured) {
1391                                                 XplatUI.UngrabWindow(this.window.Handle);
1392                                                 is_captured = false;
1393                                         }
1394                                 }
1395                         }
1396                 }
1397
1398                 [DefaultValue(true)]
1399                 public bool CausesValidation {
1400                         get {
1401                                 return this.causes_validation;
1402                         }
1403
1404                         set {
1405                                 if (this.causes_validation != value) {
1406                                         causes_validation = value;
1407                                         OnCausesValidationChanged(EventArgs.Empty);
1408                                 }
1409                         }
1410                 }
1411
1412                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1413                 [Browsable(false)]
1414                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1415                 public Rectangle ClientRectangle {
1416                         get {
1417                                 client_rect.Width = client_size.Width;
1418                                 client_rect.Height = client_size.Height;
1419                                 return client_rect;
1420                         }
1421                 }
1422
1423                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1424                 [Browsable(false)]
1425                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1426                 public Size ClientSize {
1427                         get {
1428 #if notneeded
1429                                 if ((this is Form) && (((Form)this).form_parent_window != null)) {
1430                                         return ((Form)this).form_parent_window.ClientSize;
1431                                 }
1432 #endif
1433
1434                                 return client_size;
1435                         }
1436
1437                         set {
1438                                 this.SetClientSizeCore(value.Width, value.Height);
1439                         }
1440                 }
1441
1442                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1443                 [Browsable(false)]
1444                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1445                 [DescriptionAttribute("ControlCompanyNameDescr")]
1446                 public String CompanyName {
1447                         get {
1448                                 return "Mono Project, Novell, Inc.";
1449                         }
1450                 }
1451
1452                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1453                 [Browsable(false)]
1454                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1455                 public bool ContainsFocus {
1456                         get {
1457                                 if (this.Focused) {
1458                                         return true;
1459                                 }
1460
1461                                 for (int i=0; i < child_controls.Count; i++) {
1462                                         if (child_controls[i].ContainsFocus) {
1463                                                 return true;
1464                                         }
1465                                 }
1466                                 return false;
1467                         }
1468                 }
1469
1470                 [DefaultValue(null)]
1471                 public virtual ContextMenu ContextMenu {
1472                         get {
1473                                 return context_menu;
1474                         }
1475
1476                         set {
1477                                 if (context_menu != value) {
1478                                         context_menu = value;
1479                                         OnContextMenuChanged(EventArgs.Empty);
1480                                 }
1481                         }
1482                 }
1483
1484                 [Browsable(false)]
1485                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
1486                 public ControlCollection Controls {
1487                         get {
1488                                 return this.child_controls;
1489                         }
1490                 }
1491
1492                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1493                 [Browsable(false)]
1494                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1495                 public bool Created {
1496                         get {
1497                                 if (!this.is_disposed && (this.window.Handle != IntPtr.Zero)) {
1498                                         return true;
1499                                 }
1500                                 return false;
1501                         }
1502                 }
1503
1504                 [AmbientValue(null)]
1505                 public virtual Cursor Cursor {
1506                         get {
1507                                 if (cursor != null) {
1508                                         return cursor;
1509                                 }
1510
1511                                 if (parent != null) {
1512                                         return parent.Cursor;
1513                                 }
1514
1515                                 return Cursors.Default;
1516                         }
1517
1518                         set {
1519                                 if (cursor != value) {
1520                                         Point   pt;
1521
1522                                         cursor = value;
1523                                         
1524                                         pt = Cursor.Position;
1525                                         if (bounds.Contains(pt)) {
1526                                                 if (GetChildAtPoint(pt) == null) {
1527                                                         if (cursor != null) {
1528                                                                 XplatUI.SetCursor(window.Handle, cursor.handle);
1529                                                         } else {
1530                                                                 if (parent != null) {
1531                                                                         XplatUI.SetCursor(window.Handle, parent.Cursor.handle);
1532                                                                 } else {
1533                                                                         XplatUI.SetCursor(window.Handle, Cursors.def.handle);
1534                                                                 }
1535                                                         }
1536                                                 }
1537                                         }
1538
1539                                         OnCursorChanged(EventArgs.Empty);
1540                                 }
1541                         }
1542                 }
1543
1544
1545                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
1546                 [ParenthesizePropertyName(true)]
1547                 [RefreshProperties(RefreshProperties.All)]
1548                 public ControlBindingsCollection DataBindings {
1549                         get {
1550                                 if (data_bindings == null)
1551                                         data_bindings = new ControlBindingsCollection (this);
1552                                 return data_bindings;
1553                         }
1554                 }
1555
1556                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1557                 [Browsable(false)]
1558                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1559                 public virtual Rectangle DisplayRectangle {
1560                         get {
1561                                 return ClientRectangle;
1562                         }
1563                 }
1564
1565                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1566                 [Browsable(false)]
1567                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1568                 public bool Disposing {
1569                         get {
1570                                 return is_disposed;
1571                         }
1572                 }
1573
1574                 [Localizable(true)]
1575                 [RefreshProperties(RefreshProperties.Repaint)]
1576                 [DefaultValue(DockStyle.None)]
1577                 public virtual DockStyle Dock {
1578                         get {
1579                                 return dock_style;
1580                         }
1581
1582                         set {
1583                                 if (dock_style == value) {
1584                                         return;
1585                                 }
1586
1587                                 dock_style = value;
1588
1589                                 if (parent != null) {
1590                                         parent.PerformLayout(this, "Parent");
1591                                 }
1592
1593                                 OnDockChanged(EventArgs.Empty);
1594                         }
1595                 }
1596
1597                 [DispId(-514)]
1598                 [Localizable(true)]
1599                 public bool Enabled {
1600                         get {
1601                                 return is_enabled;
1602                         }
1603
1604                         set {
1605                                 if (is_enabled == value) {
1606                                         return;
1607                                 }
1608
1609                                 is_enabled = value;
1610                                 Refresh();
1611                                 OnEnabledChanged (EventArgs.Empty);                             
1612                         }
1613                 }
1614
1615                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1616                 [Browsable(false)]
1617                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1618                 public virtual bool Focused {
1619                         get {
1620                                 return this.has_focus;
1621                         }
1622                 }
1623
1624                 [DispId(-512)]
1625                 [AmbientValue(null)]
1626                 [Localizable(true)]
1627                 public virtual Font Font {
1628                         get {
1629                                 if (font != null) {
1630                                         return font;
1631                                 }
1632
1633                                 if (Parent != null && Parent.Font != null) {
1634                                         return Parent.Font;
1635                                 }
1636
1637                                 return DefaultFont;
1638                         }
1639
1640                         set {
1641                                 if (font != null && font.Equals (value)) {
1642                                         return;
1643                                 }
1644
1645                                 font = value;   
1646                                 Invalidate();
1647                                 OnFontChanged (EventArgs.Empty);                                
1648                         }
1649                 }
1650
1651                 [DispId(-513)]
1652                 public virtual Color ForeColor {
1653                         get {
1654                                 if (foreground_color.IsEmpty) {
1655                                         if (parent!=null) {
1656                                                 return parent.ForeColor;
1657                                         }
1658                                         return DefaultForeColor;
1659                                 }
1660                                 return foreground_color;
1661                         }
1662
1663                         set {
1664                                 if (foreground_color != value) {
1665                                         foreground_color=value;
1666                                         Invalidate();
1667                                         OnForeColorChanged(EventArgs.Empty);
1668                                 }
1669                         }
1670                 }
1671
1672                 [DispId(-515)]
1673                 [Browsable(false)]
1674                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1675                 public IntPtr Handle {                                                  // IWin32Window
1676                         get {
1677                                 if (!IsHandleCreated) {
1678                                         CreateHandle();
1679                                 }
1680                                 return window.Handle;
1681                         }
1682                 }
1683
1684                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1685                 [Browsable(false)]
1686                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1687                 public bool HasChildren {
1688                         get {
1689                                 if (this.child_controls.Count>0) {
1690                                         return true;
1691                                 }
1692                                 return false;
1693                         }
1694                 }
1695
1696                 [EditorBrowsable(EditorBrowsableState.Always)]
1697                 [Browsable(false)]
1698                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1699                 public int Height {
1700                         get {
1701                                 return this.bounds.Height;
1702                         }
1703
1704                         set {
1705                                 SetBoundsCore(bounds.X, bounds.Y, bounds.Width, value, BoundsSpecified.Height);
1706                         }
1707                 }
1708
1709                 [AmbientValue(ImeMode.Inherit)]
1710                 [Localizable(true)]
1711                 public ImeMode ImeMode {
1712                         get {
1713                                  if (ime_mode == DefaultImeMode) {
1714                                         if (parent != null)
1715                                                 return parent.ImeMode;
1716                                         else
1717                                                 return ImeMode.NoControl; // default value
1718                                 }
1719                                 return ime_mode;
1720                         }
1721
1722                         set {
1723                                 if (ime_mode != value) {
1724                                         ime_mode = value;
1725
1726                                         OnImeModeChanged(EventArgs.Empty);
1727                                 }
1728                         }
1729                 }
1730
1731                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1732                 [Browsable(false)]
1733                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1734                 public bool InvokeRequired {                                            // ISynchronizeInvoke
1735                         get {
1736                                 if (creator_thread!=Thread.CurrentThread) {
1737                                         return true;
1738                                 }
1739                                 return false;
1740                         }
1741                 }
1742
1743                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1744                 [Browsable(false)]
1745                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1746                 public bool IsAccessible {
1747                         get {
1748                                 return is_accessible;
1749                         }
1750
1751                         set {
1752                                 is_accessible = value;
1753                         }
1754                 }
1755
1756                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1757                 [Browsable(false)]
1758                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1759                 public bool IsDisposed {
1760                         get {
1761                                 return this.is_disposed;
1762                         }
1763                 }
1764
1765                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1766                 [Browsable(false)]
1767                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1768                 public bool IsHandleCreated {
1769                         get {
1770                                 if ((window!=null) && (window.Handle!=IntPtr.Zero)) {
1771                                         return true;
1772                                 }
1773
1774                                 return false;
1775                         }
1776                 }
1777
1778                 [EditorBrowsable(EditorBrowsableState.Always)]
1779                 [Browsable(false)]
1780                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1781                 public int Left {
1782                         get {
1783                                 return this.bounds.X;
1784                         }
1785
1786                         set {
1787                                 SetBoundsCore(value, bounds.Y, bounds.Width, bounds.Height, BoundsSpecified.X);
1788                         }
1789                 }
1790
1791                 [Localizable(true)]
1792                 public Point Location {
1793                         get {
1794                                 return new Point(bounds.X, bounds.Y);
1795                         }
1796
1797                         set {
1798                                 SetBoundsCore(value.X, value.Y, bounds.Width, bounds.Height, BoundsSpecified.Location);
1799                         }
1800                 }
1801
1802                 [Browsable(false)]
1803                 public string Name {
1804                         get {
1805                                 return this.name;
1806                         }
1807
1808                         set {
1809                                 this.name=value;
1810                         }
1811                 }
1812
1813                 [Browsable(false)]
1814                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1815                 public Control Parent {
1816                         get {
1817                                 return this.parent;
1818                         }
1819
1820                         set {
1821                                 if (value == this) {
1822                                         throw new ArgumentException("A circular control reference has been made. A control cannot be owned or parented to itself.");
1823                                 }
1824
1825                                 if (parent!=value) {
1826                                         if (value==null) {
1827                                                 parent.Controls.Remove(this);
1828                                                 return;
1829                                         }
1830
1831                                         parent=value;
1832
1833                                         if (!parent.Controls.AllContains (this)) {
1834                                                 Console.WriteLine ("Adding child:  " + this);
1835                                                 parent.Controls.Add(this);
1836                                         }
1837
1838                                         if (IsHandleCreated) {
1839                                                 XplatUI.SetParent(Handle, value.Handle);
1840                                         }
1841
1842                                         OnParentChanged(EventArgs.Empty);
1843                                         InitLayout();
1844                                 }
1845                         }
1846                 }
1847
1848                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1849                 [Browsable(false)]
1850                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1851                 public string ProductName {
1852                         get {
1853                                 Type t = typeof (AssemblyProductAttribute);
1854                                 Assembly assembly = GetType().Module.Assembly;
1855                                 object [] attrs = assembly.GetCustomAttributes (t, false);
1856                                 AssemblyProductAttribute a = null;
1857                                 // On MS we get a NullRefException if product attribute is not
1858                                 // set. 
1859                                 if (attrs != null && attrs.Length > 0)
1860                                         a = (AssemblyProductAttribute) attrs [0];
1861                                 return a.Product;
1862                         }
1863                 }
1864
1865                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1866                 [Browsable(false)]
1867                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1868                 public string ProductVersion {
1869                         get {
1870                                 Type t = typeof (AssemblyVersionAttribute);
1871                                 Assembly assembly = GetType().Module.Assembly;
1872                                 object [] attrs = assembly.GetCustomAttributes (t, false);
1873                                 if (attrs == null || attrs.Length < 1)
1874                                         return "1.0.0.0";
1875                                 return ((AssemblyVersionAttribute)attrs [0]).Version;
1876                         }
1877                 }
1878
1879                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1880                 [Browsable(false)]
1881                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1882                 public bool RecreatingHandle {
1883                         get {
1884                                 return is_recreating;
1885                         }
1886                 }
1887
1888                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1889                 [Browsable(false)]
1890                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1891                 public Region Region {
1892                         get {
1893                                 return new Region(this.bounds);
1894                         }
1895
1896                         set {
1897                                 Graphics        g;
1898                                 RectangleF      r;
1899
1900                                 g = this.CreateGraphics();
1901                                 r = value.GetBounds(g);
1902
1903                                 SetBounds((int)r.X, (int)r.Y, (int)r.Width, (int)r.Height);
1904
1905                                 g.Dispose();
1906                         }
1907                 }
1908
1909                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1910                 [Browsable(false)]
1911                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
1912                 public int Right {
1913                         get {
1914                                 return this.bounds.X+this.bounds.Width;
1915                         }
1916                 }
1917
1918                 [AmbientValue(RightToLeft.Inherit)]
1919                 [Localizable(true)]
1920                 public virtual RightToLeft RightToLeft {
1921                         get {
1922                                 if (right_to_left == RightToLeft.Inherit) {
1923                                         if (parent != null)
1924                                                 return parent.RightToLeft;
1925                                         else
1926                                                 return RightToLeft.No; // default value
1927                                 }
1928                                 return right_to_left;
1929                         }
1930
1931                         set {
1932                                 if (value != right_to_left) {
1933                                         right_to_left = value;
1934                                         OnRightToLeftChanged(EventArgs.Empty);
1935                                 }
1936                         }
1937                 }
1938
1939                 [EditorBrowsable(EditorBrowsableState.Advanced)]
1940                 public override ISite Site {
1941                         get {
1942                                 return base.Site;
1943                         }
1944
1945                         set {
1946                                 base.Site = value;
1947                         }
1948                 }
1949
1950                 [Localizable(true)]
1951                 public Size Size {
1952                         get {
1953                                 return new Size(Width, Height);
1954                         }
1955
1956                         set {
1957                                 SetBoundsCore(bounds.X, bounds.Y, value.Width, value.Height, BoundsSpecified.Size);
1958                         }
1959                 }
1960
1961                 [Localizable(true)]
1962                 [MergableProperty(false)]
1963                 public int TabIndex {
1964                         get {
1965                                 if (tab_index != -1) {
1966                                         return tab_index;
1967                                 }
1968                                 return 0;
1969                         }
1970
1971                         set {
1972                                 if (tab_index != value) {
1973                                         tab_index = value;
1974                                         OnTabIndexChanged(EventArgs.Empty);
1975                                 }
1976                         }
1977                 }
1978
1979                 [DispId(-516)]
1980                 [DefaultValue(true)]
1981                 public bool TabStop {
1982                         get {
1983                                 return tab_stop;
1984                         }
1985
1986                         set {
1987                                 if (tab_stop != value) {
1988                                         tab_stop = value;
1989                                         OnTabStopChanged(EventArgs.Empty);
1990                                 }
1991                         }
1992                 }
1993
1994                 [Localizable(false)]
1995                 [Bindable(true)]
1996                 [TypeConverter(typeof(StringConverter))]
1997                 [DefaultValue(null)]
1998                 public object Tag {
1999                         get {
2000                                 return control_tag;
2001                         }
2002
2003                         set {
2004                                 control_tag = value;
2005                         }
2006                 }
2007
2008                 [DispId(-517)]
2009                 [Localizable(true)]
2010                 [BindableAttribute(true)]
2011                 public virtual string Text {
2012                         get {
2013                                 // Our implementation ignores ControlStyles.CacheText - we always cache
2014                                 return this.text;
2015                         }
2016
2017                         set {
2018                                 if (value == null) {
2019                                         value = String.Empty;
2020                                 }
2021
2022                                 if (text!=value) {
2023                                         text=value;
2024                                         if (IsHandleCreated) {
2025                                                 XplatUI.Text(Handle, text);
2026                                         }
2027                                         OnTextChanged (EventArgs.Empty);
2028                                 }
2029                         }
2030                 }
2031
2032                 [EditorBrowsable(EditorBrowsableState.Always)]
2033                 [Browsable(false)]
2034                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2035                 public int Top {
2036                         get {
2037                                 return this.bounds.Y;
2038                         }
2039
2040                         set {
2041                                 SetBoundsCore(bounds.X, value, bounds.Width, bounds.Height, BoundsSpecified.Y);
2042                         }
2043                 }
2044
2045                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2046                 [Browsable(false)]
2047                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2048                 public Control TopLevelControl {
2049                         get {
2050                                 Control p = this;
2051
2052                                 while (p.parent != null) {
2053                                         p = p.parent;
2054                                 }
2055
2056                                 return p;
2057                         }
2058                 }
2059
2060                 [Localizable(true)]
2061                 public bool Visible {
2062                         get {
2063                                 if (!is_visible) {
2064                                         return false;
2065                                 } else if (parent != null) {
2066                                         return parent.Visible;
2067                                 }
2068
2069                                 return true;
2070                         }
2071
2072                         set {
2073                                 SetVisibleCore(value);
2074                         }
2075                 }
2076
2077                 [EditorBrowsable(EditorBrowsableState.Always)]
2078                 [Browsable(false)]
2079                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2080                 public int Width {
2081                         get {
2082                                 return this.bounds.Width;
2083                         }
2084
2085                         set {
2086                                 SetBoundsCore(bounds.X, bounds.Y, value, bounds.Height, BoundsSpecified.Width);
2087                         }
2088                 }
2089
2090                 [EditorBrowsable(EditorBrowsableState.Never)]
2091                 [Browsable(false)]
2092                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2093                 public IWindowTarget WindowTarget {
2094                         get {
2095                                 return null;
2096                         }
2097
2098                         set {
2099                                 ;       // MS Internal
2100                         }
2101                 }
2102                 #endregion      // Public Instance Properties
2103
2104                 #region Protected Instance Properties
2105                 protected virtual CreateParams CreateParams {
2106                         get {
2107                                 CreateParams create_params = new CreateParams();
2108
2109                                 try {
2110                                         create_params.Caption = Text;
2111                                 }
2112                                 catch {
2113                                         create_params.Caption = text;
2114                                 }
2115
2116                                 try {
2117                                         create_params.X = Left;
2118                                 }
2119                                 catch {
2120                                         create_params.X = this.bounds.X;
2121                                 }
2122
2123                                 try {
2124                                         create_params.Y = Top;
2125                                 }
2126                                 catch {
2127                                         create_params.Y = this.bounds.Y;
2128                                 }
2129
2130                                 try {
2131                                         create_params.Width = Width;
2132                                 }
2133                                 catch {
2134                                         create_params.Width = this.bounds.Width;
2135                                 }
2136
2137                                 try {
2138                                         create_params.Height = Height;
2139                                 }
2140                                 catch {
2141                                         create_params.Height = this.bounds.Height;
2142                                 }
2143
2144
2145                                 create_params.ClassName = XplatUI.DefaultClassName;
2146                                 create_params.ClassStyle = 0;
2147                                 create_params.ExStyle = 0;
2148                                 create_params.Param = 0;
2149
2150                                 if (allow_drop) {
2151                                         create_params.ExStyle |= (int)WindowStyles.WS_EX_ACCEPTFILES;
2152                                 }
2153
2154                                 if (parent!=null) {
2155                                         create_params.Parent = parent.Handle;
2156                                 }
2157
2158                                 create_params.Style = (int)WindowStyles.WS_CHILD | (int)WindowStyles.WS_CLIPCHILDREN | (int)WindowStyles.WS_CLIPSIBLINGS;
2159
2160                                 if (is_visible) {
2161                                         create_params.Style |= (int)WindowStyles.WS_VISIBLE;
2162                                 }
2163
2164                                 return create_params;
2165                         }
2166                 }
2167
2168                 protected virtual ImeMode DefaultImeMode {
2169                         get {
2170                                 return ImeMode.Inherit;
2171                         }
2172                 }
2173
2174                 protected virtual Size DefaultSize {
2175                         get {
2176                                 return new Size(100, 23);
2177                         }
2178                 }
2179
2180                 protected int FontHeight {
2181                         get {
2182                                 return Font.Height;
2183                         }
2184
2185                         set {
2186                                 ;; // Nothing to do
2187                         }
2188                 }
2189
2190                 protected bool RenderRightToLeft {
2191                         get {
2192                                 return (this.right_to_left == RightToLeft.Yes);
2193                         }
2194                 }
2195
2196                 protected bool ResizeRedraw {
2197                         get {
2198                                 return GetStyle(ControlStyles.ResizeRedraw);
2199                         }
2200
2201                         set {
2202                                 SetStyle(ControlStyles.ResizeRedraw, value);
2203                         }
2204                 }
2205
2206                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2207                 [Browsable(false)]
2208                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2209                 protected virtual bool ShowFocusCues {
2210                         get {
2211                                 return true;
2212                         }
2213                 }
2214
2215                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2216                 [Browsable(false)]
2217                 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
2218                 protected bool ShowKeyboardCues {
2219                         get {
2220                                 return true;
2221                         }
2222                 }
2223                 #endregion      // Protected Instance Properties
2224
2225                 #region Public Static Methods
2226                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2227                 public static Control FromChildHandle(IntPtr handle) {
2228                         IEnumerator control = Control.controls.GetEnumerator();
2229
2230                         while (control.MoveNext()) {
2231                                 if (((Control)control.Current).window.Handle == handle) {
2232                                         // Found it
2233                                         if (((Control)control.Current).Parent != null) {
2234                                                 return ((Control)control.Current).Parent;
2235                                         }
2236                                 }
2237                         }
2238                         return null;
2239                 }
2240
2241                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2242                 public static Control FromHandle(IntPtr handle) {
2243                         IEnumerator control = Control.controls.GetEnumerator();
2244
2245                         while (control.MoveNext()) {
2246                                 if (((Control)control.Current).window.Handle == handle) {
2247                                         // Found it
2248                                         return ((Control)control.Current);
2249                                 }
2250                         }
2251                         return null;
2252                 }
2253
2254                 public static bool IsMnemonic(char charCode, string text) {
2255                         int amp;                        
2256
2257                         amp = text.IndexOf('&');
2258
2259                         if (amp != -1) {
2260                                 if (amp + 1 < text.Length) {
2261                                         if (text[amp + 1] != '&') {
2262                                                 if (Char.ToUpper(charCode) == Char.ToUpper(text.ToCharArray(amp + 1, 1)[0])) {
2263                                                         return true;
2264                                                 }       
2265                                         }
2266                                 }
2267                         }
2268                         return false;
2269                 }
2270                 #endregion
2271
2272                 #region Protected Static Methods
2273                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2274                 protected static bool ReflectMessage(IntPtr hWnd, ref Message m) {
2275                         Control c;
2276
2277                         c = Control.FromHandle(hWnd);
2278
2279                         if (c != null) {
2280                                 c.WndProc(ref m);
2281                                 return true;
2282                         }
2283                         return false;
2284                 }
2285                 #endregion
2286
2287                 #region Public Instance Methods
2288                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2289                 public IAsyncResult BeginInvoke(Delegate method) {
2290                         return BeginInvokeInternal(method, null);
2291                 }
2292
2293                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2294                 public IAsyncResult BeginInvoke (Delegate method, object[] args) {
2295                         return BeginInvokeInternal (method, args);
2296                 }
2297
2298                 public void BringToFront() {
2299                         if ((parent != null) && (parent.child_controls[0]!=this)) {
2300                                 if (parent.child_controls.Contains(this)) {
2301                                         parent.child_controls.SetChildIndex(this, 0);
2302                                 }
2303                         }
2304
2305                         XplatUI.SetZOrder(this.window.Handle, IntPtr.Zero, true, false);
2306
2307                         if (parent != null) {
2308                                 parent.Refresh();
2309                         }
2310                 }
2311
2312                 public bool Contains(Control ctl) {
2313                         while (ctl != null) {
2314                                 ctl = ctl.parent;
2315                                 if (ctl == this) {
2316                                         return true;
2317                                 }
2318                         }
2319                         return false;
2320                 }
2321
2322                 public void CreateControl() {
2323
2324                         if (!IsHandleCreated) {
2325                                 CreateHandle();
2326                         }
2327
2328                         if (!create_handled) {
2329                                 create_handled = true;
2330                                 OnCreateControl();
2331                         }
2332
2333                         Control [] controls = child_controls.GetAllControls ();
2334                         for (int i=0; i<controls.Length; i++) {
2335                                 controls [i].CreateControl ();
2336                         }
2337                 }
2338
2339                 public Graphics CreateGraphics() {
2340                         if (!IsHandleCreated) {
2341                                 this.CreateControl();
2342                         }
2343                         return Graphics.FromHwnd(this.window.Handle);
2344                 }
2345
2346                 public DragDropEffects DoDragDrop(object data, DragDropEffects allowedEffects) {
2347                         return XplatUI.StartDrag(this.window.Handle, data, allowedEffects);
2348                 }
2349
2350                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2351                 public object EndInvoke (IAsyncResult async_result) {
2352                         AsyncMethodResult result = (AsyncMethodResult) async_result;
2353                         return result.EndInvoke ();
2354                 }
2355
2356                 public Form FindForm() {
2357                         Control c;
2358
2359                         c = this;
2360                         while (c != null) {
2361                                 if (c is Form) {
2362                                         return (Form)c;
2363                                 }
2364                                 c = c.Parent;
2365                         }
2366                         return null;
2367                 }
2368
2369                 public bool Focus() {
2370                         if (IsHandleCreated && !has_focus) {
2371                                 has_focus = true;
2372                                 XplatUI.SetFocus(window.Handle);
2373                         }
2374                         return true;
2375                 }
2376
2377                 public Control GetChildAtPoint(Point pt) {
2378                         // Microsoft's version of this function doesn't seem to work, so I can't check
2379                         // if we only consider children or also grandchildren, etc.
2380                         // I'm gonna say 'children only'
2381                         for (int i=0; i<child_controls.Count; i++) {
2382                                 if (child_controls[i].Bounds.Contains(pt)) {
2383                                         return child_controls[i];
2384                                 }
2385                         }
2386                         return null;
2387                 }
2388
2389                 public IContainerControl GetContainerControl() {
2390                         Control current = this;
2391
2392                         while (current!=null) {
2393                                 if ((current is IContainerControl) && ((current.control_style & ControlStyles.ContainerControl)!=0)) {
2394                                         return (IContainerControl)current;
2395                                 }
2396                                 current = current.parent;
2397                         }
2398                         return null;
2399                 }
2400
2401                 public Control GetNextControl(Control ctl, bool forward) {
2402                         // If we're not a container we don't play
2403                         if (!(this is IContainerControl) && !this.GetStyle(ControlStyles.ContainerControl)) {
2404                                 return null;
2405                         }
2406
2407                         // If ctl is not contained by this, we start at the first child of this
2408                         if (!this.Contains(ctl)) {
2409                                 ctl = null;
2410                         }
2411
2412                         // Search through our controls, starting at ctl, stepping into children as we encounter them
2413                         // try to find the control with the tabindex closest to our own, or, if we're looking into
2414                         // child controls, the one with the smallest tabindex
2415                         if (forward) {
2416                                 return FindControlForward(this, ctl);
2417                         }
2418                         return FindControlBackward(this, ctl);
2419                 }
2420
2421                 public void Hide() {
2422                         this.Visible = false;
2423                 }
2424
2425                 public void Invalidate() {
2426                         Invalidate(ClientRectangle, false);
2427                 }
2428
2429                 public void Invalidate(bool invalidateChildren) {
2430                         Invalidate(ClientRectangle, invalidateChildren);
2431                 }
2432
2433                 public void Invalidate(System.Drawing.Rectangle rc) {
2434                         Invalidate(rc, false);
2435                 }
2436
2437                 public void Invalidate(System.Drawing.Rectangle rc, bool invalidateChildren) {
2438                         if (!IsHandleCreated || !Visible || rc.Width == 0 || rc.Height == 0) {
2439                                 return;
2440                         }
2441
2442                         NotifyInvalidate(rc);
2443
2444                         XplatUI.Invalidate(Handle, rc, false);
2445
2446                         if (invalidateChildren) {
2447                                 Control [] controls = child_controls.GetAllControls ();
2448                                 for (int i=0; i<controls.Length; i++)
2449                                         controls [i].Invalidate ();
2450                         }
2451                         OnInvalidated(new InvalidateEventArgs(rc));
2452                 }
2453
2454                 public void Invalidate(System.Drawing.Region region) {
2455                         Invalidate(region, false);
2456                 }
2457
2458                 [MonoTODO("Figure out if GetRegionScans is usable")]
2459                 public void Invalidate(System.Drawing.Region region, bool invalidateChildren) {
2460                         throw new NotImplementedException();
2461
2462                         // FIXME - should use the GetRegionScans function of the region to invalidate each area
2463                         //if (invalidateChildren) {
2464                         //      for (int i=0; i<child_controls.Count; i++) child_controls[i].Invalidate();
2465                         //}
2466                 }
2467
2468                 public object Invoke (Delegate method) {
2469                         return Invoke(method, null);
2470                 }
2471
2472                 public object Invoke (Delegate method, object[] args) {
2473                         if (!this.InvokeRequired) {
2474                                 return method.DynamicInvoke(args);
2475                         }
2476
2477                         IAsyncResult result = BeginInvoke (method, args);
2478                         return EndInvoke(result);
2479                 }
2480
2481                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2482                 public void PerformLayout() {
2483                         PerformLayout(null, null);
2484                 }
2485
2486                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2487                 public void PerformLayout(Control affectedControl, string affectedProperty) {
2488                         LayoutEventArgs levent = new LayoutEventArgs(affectedControl, affectedProperty);
2489
2490                         if (layout_suspended > 0) {
2491                                 layout_pending = true;
2492                                 return;
2493                         }
2494
2495                         layout_pending = false;
2496
2497                         // Prevent us from getting messed up
2498                         layout_suspended++;
2499
2500                         // Perform all Dock and Anchor calculations
2501                         try {
2502                                 Control         child;
2503                                 AnchorStyles    anchor;
2504                                 Rectangle       space;
2505
2506                                 space=this.DisplayRectangle;
2507
2508                                 // Deal with docking; go through in reverse, MS docs say that lowest Z-order is closest to edge
2509                                 Control [] controls = child_controls.GetAllControls ();
2510                                 for (int i = controls.Length - 1; i >= 0; i--) {
2511                                         child = controls [i];
2512                                         switch (child.Dock) {
2513                                                 case DockStyle.None: {
2514                                                         // Do nothing
2515                                                         break;
2516                                                 }
2517
2518                                                 case DockStyle.Left: {
2519                                                         child.SetBounds(space.Left, space.Y, child.Width, space.Height);
2520                                                         space.X+=child.Width;
2521                                                         space.Width-=child.Width;
2522                                                         break;
2523                                                 }
2524
2525                                                 case DockStyle.Top: {
2526                                                         child.SetBounds(space.Left, space.Y, space.Width, child.Height);
2527                                                         space.Y+=child.Height;
2528                                                         space.Height-=child.Height;
2529                                                         break;
2530                                                 }
2531                                         
2532                                                 case DockStyle.Right: {
2533                                                         child.SetBounds(space.Right-child.Width, space.Y, child.Width, space.Height);
2534                                                         space.Width-=child.Width;
2535                                                         break;
2536                                                 }
2537
2538                                                 case DockStyle.Bottom: {
2539                                                         child.SetBounds(space.Left, space.Bottom-child.Height, space.Width, child.Height);
2540                                                         space.Height-=child.Height;
2541                                                         break;
2542                                                 }
2543                                         }
2544                                 }
2545
2546                                 for (int i = controls.Length - 1; i >= 0; i--) {
2547                                         child=controls[i];
2548
2549                                         if (child.Dock == DockStyle.Fill) {
2550                                                 child.SetBounds(space.Left, space.Top, space.Width, space.Height);
2551                                                 space.Width=0;
2552                                                 space.Height=0;
2553                                         }
2554                                 }
2555
2556                                 space=this.DisplayRectangle;
2557
2558                                 for (int i=0; i < controls.Length; i++) {
2559                                         int left;
2560                                         int top;
2561                                         int width;
2562                                         int height;
2563
2564                                         child = controls[i];
2565                                         anchor = child.Anchor;
2566
2567                                         left = child.Left;
2568                                         top = child.Top;
2569                                         width = child.Width;
2570                                         height = child.Height;
2571
2572                                         // If the control is docked we don't need to do anything
2573                                         if (child.Dock != DockStyle.None) {
2574                                                 continue;
2575                                         }
2576
2577                                         if ((anchor & AnchorStyles.Left) !=0 ) {
2578                                                 if ((anchor & AnchorStyles.Right) != 0) {
2579                                                         width = client_size.Width - child.dist_right - left;
2580                                                 } else {
2581                                                         ; // Left anchored only, nothing to be done
2582                                                 }
2583                                         } else if ((anchor & AnchorStyles.Right) != 0) {
2584                                                 left = client_size.Width - child.dist_right - width;
2585                                         } else {
2586                                                 // left+=diff_width/2 will introduce rounding errors (diff_width removed from svn after r51780)
2587                                                 // This calculates from scratch every time:
2588                                                 left = child.dist_left + (client_size.Width - (child.dist_left + width + child.dist_right)) / 2;
2589                                         }
2590
2591                                         if ((anchor & AnchorStyles.Top) !=0 ) {
2592                                                 if ((anchor & AnchorStyles.Bottom) != 0) {
2593                                                         height = client_size.Height - child.dist_bottom - top;
2594                                                 } else {
2595                                                         ; // Top anchored only, nothing to be done
2596                                                 }
2597                                         } else if ((anchor & AnchorStyles.Bottom) != 0) {
2598                                                 top = client_size.Height - child.dist_bottom - height;
2599                                         } else {
2600                                                 // top += diff_height/2 will introduce rounding errors (diff_height removed from after r51780)
2601                                                 // This calculates from scratch every time:
2602                                                 top = child.dist_top + (client_size.Height - (child.dist_top + height + child.dist_bottom)) / 2;
2603                                         }
2604                                         
2605                                         // Sanity
2606                                         if (width < 0) {
2607                                                 width=0;
2608                                         }
2609
2610                                         if (height < 0) {
2611                                                 height=0;
2612                                         }
2613
2614                                         child.SetBounds(left, top, width, height);
2615                                 }
2616
2617                                 // Let everyone know
2618                                 OnLayout(levent);
2619                         }
2620
2621                                 // Need to make sure we decremend layout_suspended
2622                         finally {
2623                                 layout_suspended--;
2624                         }
2625                 }
2626
2627                 public Point PointToClient (Point p) {
2628                         int x = p.X;
2629                         int y = p.Y;
2630
2631                         XplatUI.ScreenToClient (Handle, ref x, ref y);
2632
2633                         return new Point (x, y);
2634                 }
2635
2636                 public Point PointToScreen(Point p) {
2637                         int x = p.X;
2638                         int y = p.Y;
2639
2640                         XplatUI.ClientToScreen(Handle, ref x, ref y);
2641
2642                         return new Point(x, y);
2643                 }
2644
2645                 public virtual bool PreProcessMessage(ref Message msg) {
2646                         Keys key_data;
2647
2648                         if ((msg.Msg == (int)Msg.WM_KEYDOWN) || (msg.Msg == (int)Msg.WM_SYSKEYDOWN)) {
2649                                 key_data = (Keys)msg.WParam.ToInt32();
2650                                 if (!ProcessCmdKey(ref msg, key_data)) {
2651                                         if (IsInputKey(key_data)) {
2652                                                 return true;
2653                                         }
2654
2655                                         return ProcessDialogKey(key_data);
2656                                 }
2657
2658                                 return true;
2659                         } else if (msg.Msg == (int)Msg.WM_CHAR) {
2660                                 if (IsInputChar((char)msg.WParam)) {
2661                                         return true;
2662                                 }
2663                         } else if (msg.Msg == (int)Msg.WM_SYSCHAR) {
2664                                 if (IsInputChar((char)msg.WParam)) {
2665                                         return true;
2666                                 }
2667                                 return ProcessDialogChar((char)msg.WParam);
2668                         }
2669                         return false;
2670                 }
2671
2672                 public Rectangle RectangleToClient(Rectangle r) {
2673                         return new Rectangle(PointToClient(r.Location), r.Size);
2674                 }
2675
2676                 public Rectangle RectangleToScreen(Rectangle r) {
2677                         return new Rectangle(PointToScreen(r.Location), r.Size);
2678                 }
2679
2680                 public virtual void Refresh() {                 
2681                         if (IsHandleCreated == true) {
2682
2683                                 Invalidate();
2684                                 XplatUI.UpdateWindow(window.Handle);
2685
2686                                 Control [] controls = child_controls.GetAllControls ();
2687                                 for (int i=0; i < controls.Length; i++) {
2688                                         controls[i].Refresh();
2689                                 }
2690                                 
2691                         }
2692                 }
2693
2694                 [EditorBrowsable(EditorBrowsableState.Never)]
2695                 public virtual void ResetBackColor() {
2696                         background_color = Color.Empty;
2697                 }
2698
2699                 [EditorBrowsable(EditorBrowsableState.Never)]
2700                 [MonoTODO]
2701                 public void ResetBindings() {
2702                         // Do something
2703                 }
2704
2705                 [EditorBrowsable(EditorBrowsableState.Never)]
2706                 public virtual void ResetCursor() {
2707                         cursor = null;
2708                 }
2709
2710                 [EditorBrowsable(EditorBrowsableState.Never)]
2711                 public virtual void ResetFont() {
2712                         font = null;
2713                 }
2714
2715                 [EditorBrowsable(EditorBrowsableState.Never)]
2716                 public virtual void ResetForeColor() {
2717                         foreground_color = Color.Empty;
2718                 }
2719
2720                 [EditorBrowsable(EditorBrowsableState.Never)]
2721                 public void ResetImeMode() {
2722                         ime_mode = DefaultImeMode;
2723                 }
2724
2725                 [EditorBrowsable(EditorBrowsableState.Never)]
2726                 public virtual void ResetRightToLeft() {
2727                         right_to_left = RightToLeft.Inherit;
2728                 }
2729
2730                 public virtual void ResetText() {
2731                         text = String.Empty;
2732                 }
2733
2734                 public void ResumeLayout() {
2735                         ResumeLayout (true);
2736                 }
2737
2738                 public void ResumeLayout(bool performLayout) {
2739                         layout_suspended--;
2740                         
2741                         if (layout_suspended > 0) {
2742                                 return;
2743                         }
2744
2745                         if (performLayout || layout_pending) {
2746                                 PerformLayout();
2747                         }
2748                 }
2749
2750                 public void Scale(float ratio) {
2751                         ScaleCore(ratio, ratio);
2752                 }
2753
2754                 public void Scale(float dx, float dy) {
2755                         ScaleCore(dx, dy);
2756                 }
2757
2758                 public void Select() {
2759                         Select(false, false);
2760                 }
2761
2762                 public bool SelectNextControl(Control ctl, bool forward, bool tabStopOnly, bool nested, bool wrap) {
2763                         Control c;
2764                                 
2765                         c = ctl;
2766                         do {
2767                                 c = GetNextControl(c, forward);
2768                                 if (c == null) {
2769                                         if (wrap) {
2770                                                 wrap = false;
2771                                                 continue;
2772                                         }
2773                                         break;
2774                                 }
2775
2776                                 if (c.CanSelect && ((c.parent == ctl.parent) || nested) && (c.tab_stop || !tabStopOnly)) {
2777                                         Select(c);
2778                                         return true;
2779                                 }
2780                         } while (c != ctl);     // If we wrap back to ourselves we stop
2781
2782                         return false;
2783                 }
2784
2785                 public void SendToBack() {
2786                         if ((parent != null) && (parent.child_controls[parent.child_controls.Count-1]!=this)) {
2787                                 if (parent.child_controls.Contains(this)) {
2788                                         parent.child_controls.SetChildIndex(this, parent.child_controls.Count);
2789                                 }
2790                         }
2791
2792                         XplatUI.SetZOrder(this.window.Handle, IntPtr.Zero, false, true);
2793                         if (parent != null) {
2794                                 parent.Refresh();
2795                         }
2796                 }
2797
2798                 public void SetBounds(int x, int y, int width, int height) {
2799                         SetBoundsCore(x, y, width, height, BoundsSpecified.All);
2800                 }
2801
2802                 public void SetBounds(int x, int y, int width, int height, BoundsSpecified specified) {
2803                         SetBoundsCore(x, y, width, height, specified);
2804                 }
2805
2806                 public void Show() {
2807                         if (!IsHandleCreated) {
2808                                 this.CreateControl();
2809                         }
2810
2811                         this.Visible=true;
2812                 }
2813
2814                 public void SuspendLayout() {
2815                         layout_suspended++;
2816                 }
2817
2818                 public void Update() {
2819                         needs_redraw = true;
2820                         if (IsHandleCreated) {
2821                                 XplatUI.UpdateWindow(window.Handle);
2822                         }
2823                 }
2824                 #endregion      // Public Instance Methods
2825
2826                 #region Protected Instance Methods
2827                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2828                 [MonoTODO("Implement this and tie it into Control.ControlAccessibleObject.NotifyClients")]
2829                 protected void AccessibilityNotifyClients(AccessibleEvents accEvent, int childID) {
2830                         throw new NotImplementedException();
2831                 }
2832
2833                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2834                 protected virtual AccessibleObject CreateAccessibilityInstance() {
2835                         return new Control.ControlAccessibleObject(this);
2836                 }
2837
2838                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2839                 protected virtual ControlCollection CreateControlsInstance() {
2840                         return new ControlCollection(this);
2841                 }
2842
2843                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2844                 protected virtual void CreateHandle() {
2845                         if (IsDisposed) {
2846                                 throw new ObjectDisposedException(Name);
2847                         }
2848
2849                         if (IsHandleCreated) {
2850                                 return;
2851                         }
2852
2853                         window.CreateHandle(CreateParams);
2854
2855                         // Find out where the window manager placed us
2856                         UpdateStyles();
2857                         if ((CreateParams.Style & (int)WindowStyles.WS_CHILD) != 0) {
2858                                 XplatUI.SetBorderStyle(window.Handle, (FormBorderStyle)border_style);
2859                         }
2860                         UpdateBounds();
2861
2862                         if (window.Handle!=IntPtr.Zero) {
2863                                 if (!controls.Contains(window.Handle)) {
2864                                         controls.Add(this);
2865                                 }
2866
2867                                 creator_thread = Thread.CurrentThread;
2868
2869                                 OnHandleCreated(EventArgs.Empty);
2870                         }
2871                 }
2872
2873                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2874                 protected virtual void DefWndProc(ref Message m) {
2875                         window.DefWndProc(ref m);
2876                 }
2877
2878                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2879                 protected virtual void DestroyHandle() {
2880                         if (IsHandleCreated) {
2881                                 // Destroy our children before we destroy ourselves, to prevent them from
2882                                 // being implictly (without us knowing) destroyed
2883                                 Control [] controls = child_controls.GetAllControls ();
2884                                 for (int i=0; i < controls.Length; i++) {
2885                                         controls[i].DestroyHandle();
2886                                 }
2887
2888
2889                                 if (window != null) {
2890                                         window.DestroyHandle();
2891                                 }
2892                                 OnHandleDestroyed(EventArgs.Empty);
2893                         }
2894                 }
2895
2896                 protected bool GetStyle(ControlStyles flag) {
2897                         return (control_style & flag) != 0;
2898                 }
2899
2900                 protected bool GetTopLevel() {
2901                         return is_toplevel;
2902                 }
2903
2904                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2905                 protected virtual void InitLayout() {
2906                         dist_left = bounds.X;
2907                         dist_top = bounds.Y;
2908                         if (parent != null) {
2909                                 dist_right = parent.ClientSize.Width - bounds.X - bounds.Width;
2910                                 dist_bottom = parent.ClientSize.Height - bounds.Y - bounds.Height;
2911                         }
2912                 }
2913
2914                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2915                 protected void InvokeGotFocus(Control toInvoke, EventArgs e) {
2916                         toInvoke.OnGotFocus(e);
2917                 }
2918
2919                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2920                 protected void InvokeLostFocus(Control toInvoke, EventArgs e) {
2921                         toInvoke.OnLostFocus(e);
2922                 }
2923
2924                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2925                 protected void InvokeOnClick(Control toInvoke, EventArgs e) {
2926                         toInvoke.OnClick(e);
2927                 }
2928
2929                 protected void InvokePaint(Control toInvoke, PaintEventArgs e) {
2930                         toInvoke.OnPaint(e);
2931                 }
2932
2933                 protected void InvokePaintBackground(Control toInvoke, PaintEventArgs e) {
2934                         toInvoke.OnPaintBackground(e);
2935                 }
2936
2937                 protected virtual bool IsInputChar (char charCode) {
2938                         if (parent != null) {
2939                                 return parent.IsInputChar(charCode);
2940                         }
2941
2942                         return false;
2943                 }
2944
2945                 protected virtual bool IsInputKey (Keys keyData) {
2946                         // Doc says this one calls IsInputChar; not sure what to do with that
2947                         return false;
2948                 }
2949
2950                 [EditorBrowsable(EditorBrowsableState.Advanced)]
2951                 protected virtual void NotifyInvalidate(Rectangle invalidatedArea) {
2952                         // override me?
2953                 }
2954
2955                 protected virtual bool ProcessCmdKey(ref Message msg, Keys keyData) {
2956                         if ((context_menu != null) && context_menu.ProcessCmdKey(ref msg, keyData)) {
2957                                 return true;
2958                         }
2959
2960                         if (parent != null) {
2961                                 return parent.ProcessCmdKey(ref msg, keyData);
2962                         }
2963
2964                         return false;
2965                 }
2966
2967                 protected virtual bool ProcessDialogChar(char charCode) {
2968                         if (parent != null) {
2969                                 return parent.ProcessDialogChar (charCode);
2970                         }
2971
2972                         return false;
2973                 }
2974
2975                 protected virtual bool ProcessDialogKey (Keys keyData) {
2976                         if (parent != null) {
2977                                 return parent.ProcessDialogKey (keyData);
2978                         }
2979
2980                         return false;
2981                 }
2982
2983                 protected virtual bool ProcessKeyEventArgs (ref Message msg)
2984                 {
2985                         KeyEventArgs            key_event;
2986
2987                         switch (msg.Msg) {
2988                                 case (int)Msg.WM_KEYDOWN: {
2989                                         key_event = new KeyEventArgs ((Keys)msg.WParam.ToInt32 ());
2990                                         OnKeyDown (key_event);
2991                                         return key_event.Handled;
2992                                 }
2993                                 case (int)Msg.WM_KEYUP: {
2994                                         key_event = new KeyEventArgs ((Keys)msg.WParam.ToInt32 ());
2995                                         OnKeyUp (key_event);
2996                                         return key_event.Handled;
2997                                 }
2998
2999                                 case (int)Msg.WM_CHAR: {
3000                                         KeyPressEventArgs       key_press_event;
3001
3002                                         key_press_event = new KeyPressEventArgs((char)msg.WParam);
3003                                         OnKeyPress(key_press_event);
3004                                         return key_press_event.Handled;
3005                                 }
3006
3007                                 default: {
3008                                         break;
3009                                 }
3010                         }
3011
3012                         return false;
3013                 }
3014
3015                 protected internal virtual bool ProcessKeyMessage(ref Message msg) {
3016                         if (parent != null) {
3017                                 if (parent.ProcessKeyPreview(ref msg)) {
3018                                         return true;
3019                                 }
3020                         }
3021
3022                         return false;
3023                 }
3024
3025                 protected virtual bool ProcessKeyPreview(ref Message msg) {
3026                         if (parent != null) {
3027                                 return parent.ProcessKeyPreview(ref msg);
3028                         }
3029
3030                         return false;
3031                 }
3032
3033                 protected virtual bool ProcessMnemonic(char charCode) {
3034                         // override me
3035                         return false;
3036                 }
3037
3038                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3039                 protected void RaiseDragEvent(object key, DragEventArgs e) {
3040                         // MS Internal
3041                 }
3042
3043                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3044                 protected void RaiseKeyEvent(object key, KeyEventArgs e) {
3045                         // MS Internal
3046                 }
3047
3048                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3049                 protected void RaiseMouseEvent(object key, MouseEventArgs e) {
3050                         // MS Internal
3051                 }
3052
3053                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3054                 protected void RaisePaintEvent(object key, PaintEventArgs e) {
3055                         // MS Internal
3056                 }
3057
3058                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3059                 protected void RecreateHandle() {
3060                         IEnumerator child = child_controls.GetAllEnumerator();
3061
3062                         is_recreating=true;
3063
3064                         if (IsHandleCreated) {
3065                                 DestroyHandle();
3066                                 CreateHandle();
3067
3068                                 // FIXME ZOrder?
3069
3070                                 while (child.MoveNext()) {
3071                                         ((Control)child.Current).RecreateHandle();
3072                                 }
3073                         } else {
3074                                 CreateControl();
3075                         }
3076
3077                         is_recreating = false;
3078                 }
3079
3080                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3081                 protected void ResetMouseEventArgs() {
3082                         // MS Internal
3083                 }
3084
3085                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3086                 protected ContentAlignment RtlTranslateAlignment(ContentAlignment align) {
3087                         if (right_to_left == RightToLeft.No) {
3088                                 return align;
3089                         }
3090
3091                         switch (align) {
3092                                 case ContentAlignment.TopLeft: {
3093                                         return ContentAlignment.TopRight;
3094                                 }
3095
3096                                 case ContentAlignment.TopRight: {
3097                                         return ContentAlignment.TopLeft;
3098                                 }
3099
3100                                 case ContentAlignment.MiddleLeft: {
3101                                         return ContentAlignment.MiddleRight;
3102                                 }
3103
3104                                 case ContentAlignment.MiddleRight: {
3105                                         return ContentAlignment.MiddleLeft;
3106                                 }
3107
3108                                 case ContentAlignment.BottomLeft: {
3109                                         return ContentAlignment.BottomRight;
3110                                 }
3111
3112                                 case ContentAlignment.BottomRight: {
3113                                         return ContentAlignment.BottomLeft;
3114                                 }
3115
3116                                 default: {
3117                                         // if it's center it doesn't change
3118                                         return align;
3119                                 }
3120                         }
3121                 }
3122
3123                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3124                 protected HorizontalAlignment RtlTranslateAlignment(HorizontalAlignment align) {
3125                         if ((right_to_left == RightToLeft.No) || (align == HorizontalAlignment.Center)) {
3126                                 return align;
3127                         }
3128
3129                         if (align == HorizontalAlignment.Left) {
3130                                 return HorizontalAlignment.Right;
3131                         }
3132
3133                         // align must be HorizontalAlignment.Right
3134                         return HorizontalAlignment.Left;
3135                 }
3136
3137                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3138                 protected LeftRightAlignment RtlTranslateAlignment(LeftRightAlignment align) {
3139                         if (right_to_left == RightToLeft.No) {
3140                                 return align;
3141                         }
3142
3143                         if (align == LeftRightAlignment.Left) {
3144                                 return LeftRightAlignment.Right;
3145                         }
3146
3147                         // align must be LeftRightAlignment.Right;
3148                         return LeftRightAlignment.Left;
3149                 }
3150
3151                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3152                 protected ContentAlignment RtlTranslateContent(ContentAlignment align) {
3153                         return RtlTranslateAlignment(align);
3154                 }
3155
3156                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3157                 protected HorizontalAlignment RtlTranslateHorizontal(HorizontalAlignment align) {
3158                         return RtlTranslateAlignment(align);
3159                 }
3160
3161                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3162                 protected LeftRightAlignment RtlTranslateLeftRight(LeftRightAlignment align) {
3163                         return RtlTranslateAlignment(align);
3164                 }
3165
3166                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3167                 protected virtual void ScaleCore(float dx, float dy) {
3168                         Point   location;
3169                         Size    size;
3170
3171                         SuspendLayout();
3172
3173                         location = new Point((int)(Left * dx), (int)(Top * dy));
3174                         size = this.ClientSize;
3175                         
3176
3177                         if (!GetStyle(ControlStyles.FixedWidth)) {
3178                                 size.Width = (int)(size.Width * dx);
3179                         }
3180
3181                         if (!GetStyle(ControlStyles.FixedHeight)) {
3182                                 size.Height = (int)(size.Height * dy);
3183                         }
3184
3185                         Location = location;
3186                         ClientSize = size;
3187
3188                         /* Now scale our children */
3189                         Control [] controls = child_controls.GetAllControls ();
3190                         for (int i=0; i < controls.Length; i++) {
3191                                 controls[i].Scale(dx, dy);
3192                         }
3193
3194                         ResumeLayout();
3195                 }
3196
3197                 protected virtual void Select(bool directed, bool forward) {
3198                         int     index;
3199                         bool    result;
3200
3201                         if (!directed) {
3202                                 // Select this control
3203                                 Select(this);
3204                                 return;
3205                         }
3206
3207                         if (parent == null) {
3208                                 return;
3209                         }
3210
3211                         // FIXME - this thing is doing the wrong stuff, needs to be similar to SelectNextControl
3212
3213                         index = parent.child_controls.IndexOf(this);
3214                         result = false;
3215
3216                         do {
3217                                 if (forward) {
3218                                         if ((index+1) < parent.child_controls.Count) {
3219                                                 index++;
3220                                         } else {
3221                                                 index = 0;
3222                                         }
3223                                 } else {
3224                                         if (index>0) {
3225                                                 index++;
3226                                         } else {
3227                                                 index = parent.child_controls.Count-1;
3228                                         }
3229                                 }
3230                                 result = Select(parent.child_controls[index]);
3231                         } while (!result && parent.child_controls[index] != this);
3232                 }
3233
3234                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3235                 protected virtual void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) {
3236                         // SetBoundsCore updates the Win32 control itself. UpdateBounds updates the controls variables and fires events, I'm guessing - pdb
3237                         if ((specified & BoundsSpecified.X) != BoundsSpecified.X) {
3238                                 x = Left;
3239                         }
3240
3241                         if ((specified & BoundsSpecified.Y) != BoundsSpecified.Y) {
3242                                 y = Top;
3243                         }
3244
3245                         if ((specified & BoundsSpecified.Width) != BoundsSpecified.Width) {
3246                                 width = Width;
3247                         }
3248
3249                         if ((specified & BoundsSpecified.Height) != BoundsSpecified.Height) {
3250                                 height = Height;
3251                         }
3252
3253                         if (IsHandleCreated) {
3254                                 XplatUI.SetWindowPos(Handle, x, y, width, height);
3255                         }
3256
3257                         UpdateBounds(x, y, width, height);
3258
3259                         // 
3260                         Control [] controls = child_controls.GetAllControls ();
3261                         for (int i = controls.Length - 1; i >= 0; i--) {
3262                                 controls[i].InitLayout();
3263                         }
3264                 }
3265
3266                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3267                 protected virtual void SetClientSizeCore(int x, int y) {
3268                         // Calculate the actual window size from the client size (it usually stays the same or grows)
3269                         Rectangle       ClientRect;
3270                         Rectangle       WindowRect;
3271                         CreateParams    cp;
3272
3273                         ClientRect = new Rectangle(0, 0, x, y);
3274                         cp = this.CreateParams;
3275
3276                         if (XplatUI.CalculateWindowRect(Handle, ref ClientRect, cp.Style, cp.ExStyle, IntPtr.Zero, out WindowRect)==false) {
3277                                 return;
3278                         }
3279
3280                         SetBoundsCore(bounds.X, bounds.Y, WindowRect.Width, WindowRect.Height, BoundsSpecified.Size);
3281                 }
3282
3283                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3284                 protected void SetStyle(ControlStyles flag, bool value) {
3285                         if (value) {
3286                                 control_style |= flag;
3287                         } else {
3288                                 control_style &= ~flag;
3289                         }
3290                         OnStyleChanged(EventArgs.Empty);
3291                 }
3292
3293                 protected void SetTopLevel(bool value) {
3294                         if ((GetTopLevel() != value) && (parent != null)) {
3295                                 throw new Exception();
3296                         }
3297
3298                         if (this is Form) {
3299                                 if (value == true) {
3300                                         if (!Visible) {
3301                                                 Visible = true;
3302                                         }
3303                                 } else {
3304                                         if (Visible) {
3305                                                 Visible = false;
3306                                         }
3307                                 }
3308                         }
3309                         is_toplevel = value;
3310                 }
3311
3312                 protected virtual void SetVisibleCore(bool value) {
3313                         if (value!=is_visible) {
3314                                 is_visible=value;
3315
3316                                 if (IsHandleCreated) {
3317                                         XplatUI.SetVisible(Handle, value);
3318                                         // Explicitly move Toplevel windows to where we want them;
3319                                         // apparently moving unmapped toplevel windows doesn't work
3320                                         if (is_visible && (this is Form)) {
3321                                                 XplatUI.SetWindowPos(window.Handle, bounds.X, bounds.Y, bounds.Width, bounds.Height);
3322                                         }
3323                                 }
3324
3325                                 OnVisibleChanged(EventArgs.Empty);
3326
3327                                 if (!is_visible) {
3328                                         if (dc_mem != null) {
3329                                                 dc_mem.Dispose();
3330                                                 dc_mem = null;
3331                                         }
3332
3333                                         if (bmp_mem != null) {
3334                                                 bmp_mem.Dispose();
3335                                                 bmp_mem = null;
3336                                         }
3337                                 } else {
3338                                         this.CreateBuffers(bounds.Width, bounds.Height);
3339                                         CreateControl();
3340                                 }
3341
3342                                 if (value == false && parent != null) {
3343                                         Control container;
3344
3345                                         // Need to start at parent, GetContainerControl might return ourselves if we're a container
3346                                         container = (Control)parent.GetContainerControl();
3347                                         if (container != null) {
3348                                                 container.SelectNextControl(this, true, true, true, true);
3349                                         }
3350                                 }
3351
3352                                 if (parent != null) {
3353                                         parent.PerformLayout(this, "visible");
3354                                 } else {
3355                                         PerformLayout(this, "visible");
3356                                 }
3357                         }
3358                 }
3359         
3360                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3361                 protected void UpdateBounds() {
3362                         int     x;
3363                         int     y;
3364                         int     width;
3365                         int     height;
3366                         int     client_width;
3367                         int     client_height;
3368
3369                         if (!IsHandleCreated) {
3370                                 CreateHandle();
3371                         }
3372
3373                         XplatUI.GetWindowPos(this.Handle, this is Form, out x, out y, out width, out height, out client_width, out client_height);
3374
3375                         UpdateBounds(x, y, width, height, client_width, client_height);
3376                 }
3377
3378                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3379                 protected void UpdateBounds(int x, int y, int width, int height) {
3380                         // UpdateBounds only seems to set our sizes and fire events but not update the GUI window to match
3381                         bool    moved   = false;
3382                         bool    resized = false;
3383
3384                         int     client_x_diff = this.bounds.Width-this.client_size.Width;
3385                         int     client_y_diff = this.bounds.Height-this.client_size.Height;
3386
3387                         // Needed to generate required notifications
3388                         if ((this.bounds.X!=x) || (this.bounds.Y!=y)) {
3389                                 moved=true;
3390                         }
3391
3392                         if ((this.Bounds.Width!=width) || (this.Bounds.Height!=height)) {
3393                                 resized=true;
3394                         }
3395
3396                         bounds.X=x;
3397                         bounds.Y=y;
3398                         bounds.Width=width;
3399                         bounds.Height=height;
3400
3401                         // Update client rectangle as well
3402                         client_size.Width=width-client_x_diff;
3403                         client_size.Height=height-client_y_diff;
3404
3405                         if (moved) {
3406                                 OnLocationChanged(EventArgs.Empty);
3407                         }
3408
3409                         if (resized) {
3410                                 OnSizeChanged(EventArgs.Empty);
3411                         }
3412                 }
3413
3414                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3415                 protected void UpdateBounds(int x, int y, int width, int height, int clientWidth, int clientHeight) {
3416                         UpdateBounds(x, y, width, height);
3417
3418                         this.client_size.Width=clientWidth;
3419                         this.client_size.Height=clientHeight;
3420                 }
3421
3422                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3423                 protected void UpdateStyles() {
3424                         if (!IsHandleCreated) {
3425                                 return;
3426                         }
3427
3428                         XplatUI.SetWindowStyle(window.Handle, CreateParams);
3429                 }
3430
3431                 [EditorBrowsable(EditorBrowsableState.Advanced)]
3432                 protected void UpdateZOrder() {
3433                         Control [] controls;
3434 #if not
3435                         Control ctl;
3436
3437                         if (parent == null) {
3438                                 return;
3439                         }
3440
3441                         ctl = parent;
3442
3443                         controls = ctl.child_controls.GetAllControls ();
3444                         for (int i = 1; i < controls.Length; i++ ) {
3445                                 XplatUI.SetZOrder(controls[i].window.Handle, controls[i-1].window.Handle, false, false); 
3446                         }
3447 #else
3448                         if (!IsHandleCreated) {
3449                                 return;
3450                         }
3451
3452                         controls = child_controls.GetAllControls ();
3453                         for (int i = 1; i < controls.Length; i++ ) {
3454                                 XplatUI.SetZOrder(controls[i].Handle, controls[i-1].Handle, false, false); 
3455                         }
3456 #endif
3457                 }
3458
3459                 protected virtual void WndProc(ref Message m) {
3460 #if debug
3461                         Console.WriteLine("Control received message {0}", (Msg)m.Msg);
3462 #endif
3463                         if ((this.control_style & ControlStyles.EnableNotifyMessage) != 0) {
3464                                 OnNotifyMessage(m);
3465                         }
3466
3467                         switch((Msg)m.Msg) {
3468                                 case Msg.WM_WINDOWPOSCHANGED: {
3469                                         if (Visible) {
3470                                                 UpdateBounds();
3471                                                 if (GetStyle(ControlStyles.ResizeRedraw)) {
3472                                                         Invalidate();
3473                                                 }
3474                                         }
3475                                         return;
3476                                 }
3477
3478                                 case Msg.WM_PAINT: {                            
3479                                         PaintEventArgs  paint_event;
3480
3481                                         paint_event = XplatUI.PaintEventStart(Handle, true);
3482
3483                                         if (!needs_redraw) {
3484                                                 // Just blit the previous image
3485                                                 paint_event.Graphics.DrawImage (ImageBuffer, paint_event.ClipRectangle, paint_event.ClipRectangle, GraphicsUnit.Pixel);
3486                                                 XplatUI.PaintEventEnd(Handle, true);
3487                                                 return;
3488                                         }
3489
3490                                         Graphics dc = null;
3491                                         if ((control_style & ControlStyles.DoubleBuffer) != 0) {
3492                                                 dc = paint_event.SetGraphics (DeviceContext);
3493                                         }
3494
3495                                         if ((control_style & (ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint)) == (ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint)) {
3496                                                 OnPaintBackground(paint_event);
3497                                         } else {
3498                                                 PaintControlBackground(paint_event);
3499                                         }
3500
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 }