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