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