2006-05-10 Peter Dennis Bartok <pbartok@novell.com>
[mono.git] / mcs / class / Managed.Windows.Forms / System.Windows.Forms / Control.cs
index d52bca00ac6a0707534f99b6c8458dfa154388ad..a23b86308881afcbfde200ab39205cadbcc11071 100644 (file)
 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
-// Copyright (c) 2004 Novell, Inc.
+// Copyright (c) 2004-2006 Novell, Inc.
 //
 // Authors:
 //     Peter Bartok            pbartok@novell.com
 //
-// Based on work by:
+// Partially based on work by:
 //     Aleksey Ryabchuk        ryabchuk@yahoo.com
 //     Alexandre Pigolkine     pigolkine@gmx.de
 //     Dennis Hayes            dennish@raytek.com
 // COMPLETE 
 
 using System;
-using System.Drawing;
 using System.ComponentModel;
 using System.ComponentModel.Design;
+using System.ComponentModel.Design.Serialization;
 using System.Collections;
 using System.Diagnostics;
-using System.Threading;
+using System.Drawing;
+using System.Drawing.Drawing2D;
+using System.Reflection;
 using System.Runtime.InteropServices;
-using System.ComponentModel.Design.Serialization;
+using System.Security;
+using System.Threading;
 
 
 namespace System.Windows.Forms
 {
-       [Designer("System.Windows.Forms.Design.ContolDesigner, System.Design")]
+       [Designer("System.Windows.Forms.Design.ControlDesigner, " + Consts.AssemblySystem_Design, "System.ComponentModel.Design.IDesigner")]
        [DefaultProperty("Text")]
        [DefaultEvent("Click")]
-       [DesignerSerializer("System.Windows.Forms.Design.ControlCodeDomSerializer, System.Design", "System.ComponentModel.Design.Serialization.CodeDomSerializer, System.Design")]
+       [DesignerSerializer("System.Windows.Forms.Design.ControlCodeDomSerializer, " + Consts.AssemblySystem_Design, "System.ComponentModel.Design.Serialization.CodeDomSerializer, " + Consts.AssemblySystem_Design)]
        [ToolboxItemFilter("System.Windows.Forms")]
        public class Control : Component, ISynchronizeInvoke, IWin32Window
         {
@@ -61,6 +64,7 @@ namespace System.Windows.Forms
                internal string                 name;                   // for object naming
 
                // State
+               internal bool                   is_created;             // true if OnCreateControl has been sent
                internal bool                   has_focus;              // true if control has focus
                internal bool                   is_visible;             // true if control is visible
                internal bool                   is_entered;             // is the mouse inside the control?
@@ -82,6 +86,7 @@ namespace System.Windows.Forms
                internal object                 control_tag;            // object that contains data about our control
                internal int                    mouse_clicks;           // Counter for mouse clicks
                internal Cursor                 cursor;                 // Cursor for the window
+               internal bool                   allow_drop;             // true if the control accepts droping objects on it   
 
                // Visuals
                internal Color                  foreground_color;       // foreground color for control
@@ -89,26 +94,37 @@ namespace System.Windows.Forms
                internal Image                  background_image;       // background image for control
                internal Font                   font;                   // font for control
                internal string                 text;                   // window/title text for control
+               internal BorderStyle            border_style;           // Border style of control
 
                // Layout
                internal AnchorStyles           anchor_style;           // anchoring requirements for our control
                internal DockStyle              dock_style;             // docking requirements for our control (supercedes anchoring)
-               internal SizeF                  size_ratio;             // size ratio of our control to it's parent; required for anchoring
-               internal Size                   prev_size;              // previous size of the control; required for anchoring
+               internal int                    dist_left;              // distance to the left border of the parent
+               internal int                    dist_top;               // distance to the top border of the parent
+               internal int                    dist_right;             // distance to the right border of the parent
+               internal int                    dist_bottom;            // distance to the bottom border of the parent
 
                // to be categorized...
-               static internal ArrayList       controls = new ArrayList();             // All of the applications controls, in a flat list
+               static internal ArrayList       controls = new ArrayList();             // All of the application's controls, in a flat list
                internal ControlCollection      child_controls;         // our children
                internal Control                parent;                 // our parent control
                internal AccessibleObject       accessibility_object;   // object that contains accessibility information about our control
                internal BindingContext         binding_context;        // TODO
                internal RightToLeft            right_to_left;          // drawing direction for control
                internal int                    layout_suspended;
-               internal bool                   double_buffering;
                internal ContextMenu            context_menu;           // Context menu associated with the control
 
                private Graphics                dc_mem;                 // Graphics context for double buffering
                private Bitmap                  bmp_mem;                // Bitmap for double buffering control
+               private bool                    needs_redraw = true;
+
+               private ControlBindingsCollection data_bindings;
+
+#if NET_2_0
+               internal bool                   use_compatible_text_rendering;
+               static internal bool            verify_thread_handle;
+               private Padding                 padding;
+#endif
 
                #endregion      // Local Variables
 
@@ -132,8 +148,11 @@ namespace System.Windows.Forms
                                ControlNativeWindow     window;
 
                                window = (ControlNativeWindow)window_collection[hWnd];
+                               if (window != null) {
+                                       return window.owner;
+                               }
 
-                               return window.owner;
+                               return null;
                        }
 
                        protected override void WndProc(ref Message m) {
@@ -143,11 +162,8 @@ namespace System.Windows.Forms
                #endregion
                
                #region Public Classes
+               [ComVisible(true)]
                public class ControlAccessibleObject : AccessibleObject {                       
-                       #region ControlAccessibleObject Local Variables
-                       private Control owner;
-                       #endregion      // ControlAccessibleObject Local Variables
-
                        #region ControlAccessibleObject Constructors
                        public ControlAccessibleObject(Control ownerControl) {
                                this.owner = ownerControl;
@@ -205,6 +221,13 @@ namespace System.Windows.Forms
                                }
                        }
 
+                       public override AccessibleObject Parent {
+                               get {
+                                       return base.Parent;
+                               }
+                       }
+
+
                        public override AccessibleRole Role {
                                get {
                                        return base.Role;
@@ -234,9 +257,13 @@ namespace System.Windows.Forms
                        #endregion      // ControlAccessibleObject Public Instance Methods
                }
 
+               [DesignerSerializer("System.Windows.Forms.Design.ControlCollectionCodeDomSerializer, " + Consts.AssemblySystem_Design, "System.ComponentModel.Design.Serialization.CodeDomSerializer, " + Consts.AssemblySystem_Design)]
+               [ListBindable(false)]
                public class ControlCollection : IList, ICollection, ICloneable, IEnumerable {
                        #region ControlCollection Local Variables
-                       internal ArrayList      list;
+                       private ArrayList       list;
+                       internal ArrayList      impl_list;
+                       private Control []      all_controls;
                        internal Control        owner;
                        #endregion      // ControlCollection Local Variables
 
@@ -273,12 +300,12 @@ namespace System.Windows.Forms
                        #region ControlCollection Private Instance Methods
                        public virtual void Add (Control value)
                        {
+                               if (value == null)
+                                       return;
                                
-                               for (int i = 0; i < list.Count; i++) {
-                                       if (list [i] == value) {
-                                               // Do we need to do anything here?
-                                               return;
-                                       }
+                                if (Contains (value)) {
+                                       owner.PerformLayout();
+                                        return;
                                }
 
                                if (value.tab_index == -1) {
@@ -297,12 +324,42 @@ namespace System.Windows.Forms
                                        value.tab_index = use;
                                }
 
+                               if (value.parent != null) {
+                                       value.parent.Controls.Remove(value);
+                               }
+
+                               all_controls = null;
                                list.Add (value);
-                               value.Parent = owner;
+
+                               value.ChangeParent(owner);
+
+                               value.InitLayout();
+
                                owner.UpdateZOrder();
+                               owner.PerformLayout(value, "Parent");
                                owner.OnControlAdded(new ControlEventArgs(value));
                        }
                        
+                       internal void AddToList (Control c)
+                       {
+                               all_controls = null;
+                               list.Add (c);
+                       }
+
+                       internal virtual void AddImplicit (Control control)
+                       {
+                               if (impl_list == null)
+                                       impl_list = new ArrayList ();
+                               all_controls = null;
+                               impl_list.Add (control);
+
+                               control.ChangeParent (owner);
+                               control.InitLayout ();
+                               owner.UpdateZOrder ();
+                               owner.PerformLayout (control, "Parent");
+                               owner.OnControlAdded (new ControlEventArgs (control));
+                       }
+
                        public virtual void AddRange (Control[] controls)
                        {
                                if (controls == null)
@@ -318,19 +375,71 @@ namespace System.Windows.Forms
                                }
                        }
 
+                       internal virtual void AddRangeImplicit (Control [] controls)
+                       {
+                               if (controls == null)
+                                       throw new ArgumentNullException ("controls");
+
+                               owner.SuspendLayout ();
+
+                               try {
+                                       for (int i = 0; i < controls.Length; i++)
+                                               AddImplicit (controls [i]);
+                               } finally {
+                                       owner.ResumeLayout ();
+                               }
+                       }
+
                        public virtual void Clear ()
                        {
-                               owner.SuspendLayout();
-                               for (int i = 0; i < list.Count; i++) {
-                                       owner.OnControlRemoved(new ControlEventArgs((Control)list[i]));
+                               all_controls = null;
+
+                               // MS sends remove events in reverse order
+                               while (list.Count > 0) {
+                                       RemoveAt(list.Count - 1);
                                }
-                               list.Clear();
-                               owner.ResumeLayout();
                        }
 
-                       public virtual bool Contains (Control value)
+                       internal virtual void ClearImplicit ()
                        {
-                               return list.Contains (value);
+                               if (impl_list == null)
+                                       return;
+                               all_controls = null;
+                               impl_list.Clear ();
+                       }
+
+                       public bool Contains (Control value)
+                       {
+                               for (int i = list.Count; i > 0; ) {
+                                       i--;
+                                       
+                                       if (list [i] == value) {
+                                               // Do we need to do anything here?
+                                               return true;
+                                       }
+                               }
+                               return false;
+                       }
+
+                       internal bool ImplicitContains (Control value)
+                       {
+                               if (impl_list == null)
+                                       return false;
+
+                               for (int i = impl_list.Count; i > 0; ) {
+                                       i--;
+                                       
+                                       if (impl_list [i] == value) {
+                                               // Do we need to do anything here?
+                                               return true;
+                                       }
+                               }
+                               return false;
+                       }
+
+                       internal bool AllContains (Control value)
+                       {
+                               return Contains (value) || ImplicitContains (value);
                        }
 
                        public void CopyTo (Array array, int index)
@@ -365,6 +474,27 @@ namespace System.Windows.Forms
                                return list.GetEnumerator();
                        }
 
+                       internal IEnumerator GetAllEnumerator ()
+                       {
+                               Control [] res = GetAllControls ();
+                               return res.GetEnumerator ();
+                       }
+
+                       internal Control [] GetAllControls ()
+                       {
+                               if (all_controls != null)
+                                       return all_controls;
+
+                               if (impl_list == null)
+                                       return (Control []) list.ToArray (typeof (Control));
+                               
+                               Control [] res = new Control [list.Count + impl_list.Count];
+                               impl_list.CopyTo (res);
+                               list.CopyTo (res, impl_list.Count);
+
+                               return res;
+                       }
+
                        public override int GetHashCode() {
                                return base.GetHashCode();
                        }
@@ -374,19 +504,34 @@ namespace System.Windows.Forms
                        }
 
                        public virtual void Remove(Control value) {
+                               all_controls = null;
+
+                               owner.PerformLayout(value, "Parent");
                                owner.OnControlRemoved(new ControlEventArgs(value));
                                list.Remove(value);
+
+                               value.ChangeParent(null);
+
                                owner.UpdateZOrder();
                        }
 
+                       internal virtual void RemoveImplicit (Control control)
+                       {
+                               if (impl_list != null) {
+                                       all_controls = null;
+                                       owner.PerformLayout (control, "Parent");
+                                       owner.OnControlRemoved (new ControlEventArgs (control));
+                                       impl_list.Remove (control);
+                               }
+                               control.ChangeParent (null);
+                               owner.UpdateZOrder ();
+                       }
+
                        public void RemoveAt(int index) {
-                               if (index<0 || index>=list.Count) {
+                               if (index < 0 || index >= list.Count) {
                                        throw new ArgumentOutOfRangeException("index", index, "ControlCollection does not have that many controls");
                                }
-
-                               owner.OnControlRemoved(new ControlEventArgs((Control)list[index]));
-                               list.RemoveAt(index);
-                               owner.UpdateZOrder();
+                               Remove ((Control)list[index]);
                        }
 
                        public void SetChildIndex(Control child, int newIndex) {
@@ -401,7 +546,7 @@ namespace System.Windows.Forms
                                        return;
                                }
 
-                               RemoveAt(old_index);
+                               list.RemoveAt(old_index);
 
                                if (newIndex>list.Count) {
                                        list.Add(child);
@@ -436,12 +581,6 @@ namespace System.Windows.Forms
                                }
                        }
 
-                       bool IList.IsReadOnly {
-                               get {
-                                       return list.IsReadOnly;
-                               }
-                       }
-
                        bool ICollection.IsSynchronized {
                                get {
                                        return list.IsSynchronized;
@@ -488,6 +627,7 @@ namespace System.Windows.Forms
                                if (!(value is Control)) {
                                        throw new ArgumentException("Object of type Control required", "value");
                                }
+                               all_controls = null;
                                list.Insert(index, value);
                        }
 
@@ -495,15 +635,10 @@ namespace System.Windows.Forms
                                if (!(value is Control)) {
                                        throw new ArgumentException("Object of type Control required", "value");
                                }
+                               all_controls = null;
                                list.Remove(value);
                        }
 
-                       void ICollection.CopyTo(Array array, int index) {
-                               if (list.Count>0) {
-                                       list.CopyTo(array, index);
-                               }
-                       }
-
                        Object ICloneable.Clone() {
                                ControlCollection clone = new ControlCollection(this.owner);
                                clone.list=(ArrayList)list.Clone();             // FIXME: Do we need this?
@@ -515,11 +650,10 @@ namespace System.Windows.Forms
                
                #region Public Constructors
                public Control() {                      
-                       creator_thread = Thread.CurrentThread;
 
-                       prev_size = Size.Empty;
                        anchor_style = AnchorStyles.Top | AnchorStyles.Left;
 
+                       is_created = false;
                        is_visible = true;
                        is_captured = false;
                        is_disposed = false;
@@ -530,23 +664,36 @@ namespace System.Windows.Forms
                        causes_validation = true;
                        has_focus = false;
                        layout_suspended = 0;           
-                       double_buffering = true;
                        mouse_clicks = 1;
                        tab_index = -1;
                        cursor = null;
                        right_to_left = RightToLeft.Inherit;
+                       border_style = BorderStyle.None;
+                       background_color = Color.Empty;
+                       dist_left = 0;
+                       dist_right = 0;
+                       dist_top = 0;
+                       dist_bottom = 0;
+
+#if NET_2_0
+                       use_compatible_text_rendering = Application.use_compatible_text_rendering;
+                       padding = new Padding(0);
+#endif
 
-                       control_style = ControlStyles.Selectable | ControlStyles.StandardClick | ControlStyles.StandardDoubleClick;
+                       control_style = ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | 
+                                       ControlStyles.Selectable | ControlStyles.StandardClick | 
+                                       ControlStyles.StandardDoubleClick;
 
                        parent = null;
                        background_image = null;
                        text = string.Empty;
                        name = string.Empty;                    
 
+                       window = new ControlNativeWindow(this);
                        child_controls = CreateControlsInstance();
                        client_size = new Size(DefaultSize.Width, DefaultSize.Height);
                        client_rect = new Rectangle(0, 0, DefaultSize.Width, DefaultSize.Height);
-                       XplatUI.CalculateWindowRect(IntPtr.Zero, ref client_rect, CreateParams.Style, false, out bounds);
+                       XplatUI.CalculateWindowRect(ref client_rect, CreateParams.Style, CreateParams.ExStyle, null, out bounds);
                        if ((CreateParams.Style & (int)WindowStyles.WS_CHILD) == 0) {
                                bounds.X=-1;
                                bounds.Y=-1;
@@ -581,8 +728,9 @@ namespace System.Windows.Forms
                        Text=text;
                }
 
+               private delegate void RemoveDelegate(object c);
+
                protected override void Dispose(bool disposing) {
-                       is_disposed = true;
                        if (dc_mem!=null) {
                                dc_mem.Dispose();
                                dc_mem=null;
@@ -593,28 +741,116 @@ namespace System.Windows.Forms
                                bmp_mem=null;
                        }
 
-                       DestroyHandle();
-                       OnHandleDestroyed(EventArgs.Empty);
-                       controls.Remove(this);
+                       if (this.InvokeRequired) {
+                               if (Application.MessageLoop) {
+                                       this.BeginInvokeInternal(new MethodInvoker(DestroyHandle), null, true);
+                                       this.BeginInvokeInternal(new RemoveDelegate(controls.Remove), new object[] {this}, true);
+                               }
+                       } else {
+                               DestroyHandle();
+                               controls.Remove(this);
+                       }
+                       is_disposed = true;
+                       base.Dispose(disposing);
                }
                #endregion      // Public Constructors
 
                #region Internal Properties
+               internal BorderStyle InternalBorderStyle {
+                       get {
+                               return border_style;
+                       }
+
+                       set {
+                               if (!Enum.IsDefined (typeof (BorderStyle), value))
+                                       throw new InvalidEnumArgumentException (string.Format("Enum argument value '{0}' is not valid for BorderStyle", value));
+
+                               if (border_style != value) {
+                                       border_style = value;
+
+                                       if (IsHandleCreated) {
+                                               XplatUI.SetBorderStyle(window.Handle, (FormBorderStyle)border_style);
+                                               Refresh();
+                                       }
+                               }
+                       }
+               }
                #endregion      // Internal Properties
 
                #region Private & Internal Methods
-               internal static IAsyncResult BeginInvokeInternal (Delegate method, object [] args) {
-                       AsyncMethodResult result = new AsyncMethodResult ();
-                       AsyncMethodData data = new AsyncMethodData ();
+               internal IAsyncResult BeginInvokeInternal (Delegate method, object [] args, bool disposing) {
+                       AsyncMethodResult       result;
+                       AsyncMethodData         data;
+
+                       if (!disposing) {
+                               Control                 p;
+
+                               p = this;
+                               do {
+                                       if (!p.IsHandleCreated) {
+                                               throw new InvalidOperationException("Cannot call Invoke or InvokeAsync on a control until the window handle is created");
+                                       }
+                                       p = p.parent;
+                               } while (p != null);
+                       }
+
+                       result = new AsyncMethodResult ();
+                       data = new AsyncMethodData ();
 
                        data.Method = method;
                        data.Args = args;
-                       data.Result = new WeakReference (result);
+                       data.Result = result;
+
+#if NET_2_0
+                       if (!ExecutionContext.IsFlowSuppressed ()) {
+                               data.Context = ExecutionContext.Capture ();
+                       }
+#else
+#if !MWF_ON_MSRUNTIME
+                       if (SecurityManager.SecurityEnabled) {
+                               data.Stack = CompressedStack.GetCompressedStack ();
+                       }
+#endif
+#endif
 
                        XplatUI.SendAsyncMethod (data);
                        return result;
                }
 
+               
+               internal void PointToClient (ref int x, ref int y)
+               {
+                       XplatUI.ScreenToClient (Handle, ref x, ref y);
+               }
+
+               internal void PointToScreen (ref int x, ref int y)
+               {
+                       XplatUI.ClientToScreen (Handle, ref x, ref y);
+               }
+
+               private bool IsRecreating {
+                       get {
+                               if (is_recreating) {
+                                       return true;
+                               }
+
+                               if (parent != null) {
+                                       return parent.IsRecreating;
+                               }
+
+                               return false;
+                       }
+               }
+
+               private bool ParentIsRecreating {
+                       get {
+                               if (parent != null) {
+                                       return parent.IsRecreating;
+                               }
+                               return false;
+                       }
+               }
+
                internal Graphics DeviceContext {
                        get { 
                                if (dc_mem==null) {
@@ -624,7 +860,7 @@ namespace System.Windows.Forms
                        }
                }
 
-               internal Bitmap ImageBuffer {
+               private Bitmap ImageBuffer {
                        get {
                                if (bmp_mem==null) {
                                        CreateBuffers(this.Width, this.Height);
@@ -634,11 +870,9 @@ namespace System.Windows.Forms
                }
 
                internal void CreateBuffers (int width, int height) {
-                       if (double_buffering == false)
-                               return;
-
-                       if (dc_mem != null)
+                       if (dc_mem != null) {
                                dc_mem.Dispose ();
+                       }
                        if (bmp_mem != null)
                                bmp_mem.Dispose ();
 
@@ -652,20 +886,20 @@ namespace System.Windows.Forms
 
                        bmp_mem = new Bitmap (width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                        dc_mem = Graphics.FromImage (bmp_mem);
+                       needs_redraw = true;
                }
 
                internal void InvalidateBuffers ()
                {
-                       if (double_buffering == false)
-                               return;
-
-                       if (dc_mem != null)
+                       if (dc_mem != null) {
                                dc_mem.Dispose ();
+                       }
                        if (bmp_mem != null)
                                bmp_mem.Dispose ();
 
                        dc_mem = null;
                        bmp_mem = null;
+                       needs_redraw = true;
                }
 
                internal static void SetChildColor(Control parent) {
@@ -673,9 +907,6 @@ namespace System.Windows.Forms
 
                        for (int i=0; i < parent.child_controls.Count; i++) {
                                child=parent.child_controls[i];
-                               if (child.IsHandleCreated) {
-                                       XplatUI.SetWindowBackground(child.window.Handle, child.BackColor);
-                               }
                                if (child.child_controls.Count>0) {
                                        SetChildColor(child);
                                }
@@ -684,8 +915,8 @@ namespace System.Windows.Forms
                }
 
                internal bool Select(Control control) {
-                       Control parent;
-                       IContainerControl container;
+                       Control                 parent;
+                       IContainerControl       container;
 
                        if (control == null) {
                                return false;
@@ -695,7 +926,7 @@ namespace System.Windows.Forms
 
                        if (((control.control_style & ControlStyles.Selectable) !=0)  && (parent != null)) {
                                while (parent != null) {
-                                       if (!parent.is_visible || !parent.is_enabled) {
+                                       if (!parent.Visible || !parent.is_enabled) {
                                                return false;
                                        }
                                        parent = parent.parent;
@@ -704,34 +935,109 @@ namespace System.Windows.Forms
 
                        control.is_selected = true;
 
-                       XplatUI.SetFocus(control.window.Handle);
                        container = GetContainerControl();
                        if (container != null) {
                                container.ActiveControl = control;
                        }
+                       if (control.IsHandleCreated) {
+                               XplatUI.SetFocus(control.window.Handle);
+                       }
                        return true;
                }
 
+               internal virtual void DoDefaultAction() {
+                       // Only here to be overriden by our actual controls; this is needed by the accessibility class
+               }
 
-               private Control FindTabStop(Control control, bool forward) {
-                       if (control == null) {
-                               return null;
+               internal static int LowOrder (int param) {
+                       return ((int)(short)(param & 0xffff));
+               }
+
+               internal static int HighOrder (int param) {
+                       return ((int)(short)(param >> 16));
+               }
+
+               // This method exists so controls overriding OnPaintBackground can have default background painting done
+               internal virtual void PaintControlBackground (PaintEventArgs pevent)
+               {
+                       if (GetStyle(ControlStyles.SupportsTransparentBackColor) && (BackColor.A != 0xff)) {
+                               if (parent != null) {
+                                       PaintEventArgs  parent_pe;
+                                       GraphicsState   state;
+
+                                       parent_pe = new PaintEventArgs(pevent.Graphics, new Rectangle(pevent.ClipRectangle.X + Left, pevent.ClipRectangle.Y + Top, pevent.ClipRectangle.Width, pevent.ClipRectangle.Height));
+
+                                       state = parent_pe.Graphics.Save();
+                                       parent_pe.Graphics.TranslateTransform(-Left, -Top);
+                                       parent.OnPaintBackground(parent_pe);
+                                       parent_pe.Graphics.Restore(state);
+
+                                       state = parent_pe.Graphics.Save();
+                                       parent_pe.Graphics.TranslateTransform(-Left, -Top);
+                                       parent.OnPaint(parent_pe);
+                                       parent_pe.Graphics.Restore(state);
+                                       parent_pe.SetGraphics(null);
+                               }
                        }
 
-                       return null;
+                       if (background_image == null) {
+                               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));
+                               return;
+                       }
+
+                       DrawBackgroundImage (pevent.Graphics);
                }
 
+               void DrawBackgroundImage (Graphics g)
+               {
+                       using (TextureBrush b = new TextureBrush (background_image, WrapMode.Tile)) {
+                               g.FillRectangle (b, ClientRectangle);
+                       }
+               }
 
-               internal virtual void DoDefaultAction() {
-                       // Only here to be overriden by our actual controls; this is needed by the accessibility class
+               internal virtual void DndEnter (DragEventArgs e)
+               {
+                       try {
+                               OnDragEnter (e);
+                       } catch { }
                }
 
-               internal static int LowOrder (int param) {
-                       return (param & 0xffff);
+               internal virtual void DndOver (DragEventArgs e)
+               {
+                       try {
+                               OnDragOver (e);
+                       } catch { }
                }
 
-               internal static int HighOrder (int param) {
-                       return (param >> 16);
+               internal virtual void DndDrop (DragEventArgs e)
+               {
+                       try {
+                               OnDragDrop (e);
+                       } catch (Exception exc) {
+                               Console.Error.WriteLine ("MWF: Exception while dropping:");
+                               Console.Error.WriteLine (exc);
+                       }
+               }
+
+               internal virtual void DndLeave (EventArgs e)
+               {
+                       try {
+                               OnDragLeave (e);
+                       } catch { }
+               }
+
+               internal virtual void DndFeedback(GiveFeedbackEventArgs e)
+               {
+                       try {
+                               OnGiveFeedback(e);
+                       } catch { }
+               }
+
+               internal virtual void DndContinueDrag(QueryContinueDragEventArgs e)
+               {
+                       try {
+                               OnQueryContinueDrag(e);
+                       } catch { }
                }
                
                internal static MouseButtons FromParamToMouseButtons (int param) {              
@@ -750,6 +1056,10 @@ namespace System.Windows.Forms
 
                }
 
+               internal virtual bool ProcessControlMnemonic(char charCode) {
+                       return ProcessMnemonic(charCode);
+               }
+
                private static Control FindFlatForward(Control container, Control start) {
                        Control found;
                        int     index;
@@ -865,19 +1175,105 @@ namespace System.Windows.Forms
                        return found;
                }
 
-               private void HandleClick(int clicks) {
+               private void HandleClick(int clicks, MouseEventArgs me) {
                        if (GetStyle(ControlStyles.StandardClick)) {
-                               if (clicks > 1) {
-                                       if (GetStyle(ControlStyles.StandardDoubleClick)) {
-                                               OnDoubleClick(EventArgs.Empty);
-                                       } else {
-                                               OnClick(EventArgs.Empty);
-                                       }
+                               if ((clicks > 1) && GetStyle(ControlStyles.StandardDoubleClick)) {
+#if !NET_2_0
+                                       OnDoubleClick(EventArgs.Empty);
                                } else {
                                        OnClick(EventArgs.Empty);
+#else
+                                       OnDoubleClick(me);
+                               } else {
+                                       OnClick(me);
+#endif
                                }
                        }
                }
+
+               private void CheckDataBindings ()
+               {
+                       if (data_bindings == null)
+                               return;
+
+                       BindingContext binding_context = BindingContext;
+                       foreach (Binding binding in data_bindings) {
+                               binding.Check (binding_context);
+                       }
+               }
+
+
+               private void ChangeParent(Control new_parent) {
+                       bool            pre_enabled;
+                       bool            pre_visible;
+                       Font            pre_font;
+                       Color           pre_fore_color;
+                       Color           pre_back_color;
+                       RightToLeft     pre_rtl;
+
+                       // These properties are inherited from our parent
+                       // Get them pre parent-change and then send events
+                       // if they are changed after we have our new parent
+                       pre_enabled = Enabled;
+                       pre_visible = Visible;
+                       pre_font = Font;
+                       pre_fore_color = ForeColor;
+                       pre_back_color = BackColor;
+                       pre_rtl = RightToLeft;
+                       // MS doesn't seem to send a CursorChangedEvent
+
+                       parent = new_parent;
+
+                       if (IsHandleCreated && (new_parent != null) && new_parent.IsHandleCreated) {
+                               XplatUI.SetParent(Handle, new_parent.Handle);
+                       }
+
+                       OnParentChanged(EventArgs.Empty);
+
+                       if (pre_enabled != Enabled) {
+                               OnEnabledChanged(EventArgs.Empty);
+                       }
+
+                       if (pre_visible != Visible) {
+                               OnVisibleChanged(EventArgs.Empty);
+                       }
+
+                       if (pre_font != Font) {
+                               OnFontChanged(EventArgs.Empty);
+                       }
+
+                       if (pre_fore_color != ForeColor) {
+                               OnForeColorChanged(EventArgs.Empty);
+                       }
+
+                       if (pre_back_color != BackColor) {
+                               OnBackColorChanged(EventArgs.Empty);
+                       }
+
+                       if (pre_rtl != RightToLeft) {
+                               // MS sneaks a OnCreateControl and OnHandleCreated in here, I guess
+                               // because when RTL changes they have to recreate the win32 control
+                               // We don't really need that (until someone runs into compatibility issues)
+                               OnRightToLeftChanged(EventArgs.Empty);
+                       }
+
+                       if ((new_parent != null) && new_parent.Created && !Created) {
+                               CreateControl();
+                       }
+
+                       if ((binding_context == null) && Created) {
+                               OnBindingContextChanged(EventArgs.Empty);
+                       }
+               }
+
+               private void UpdateDistances() {
+                       if ((parent != null) && (parent.layout_suspended == 0)) {
+                               dist_left = bounds.X;
+                               dist_top = bounds.Y;
+                               dist_right = parent.ClientSize.Width - bounds.X - bounds.Width;
+                               dist_bottom = parent.ClientSize.Height - bounds.Y - bounds.Height;
+                       }
+               }
                #endregion      // Private & Internal Methods
 
                #region Public Static Properties
@@ -916,6 +1312,20 @@ namespace System.Windows.Forms
                                return Cursor.Position;
                        }
                }
+               
+#if NET_2_0
+               [MonoTODO]
+               public static bool CheckForIllegalCrossThreadCalls 
+               {
+                       get {
+                               return verify_thread_handle;
+                       }
+
+                       set {
+                               verify_thread_handle = value;
+                       }
+               }
+#endif
                #endregion      // Public Static Properties
 
                #region Public Instance Properties
@@ -945,7 +1355,8 @@ namespace System.Windows.Forms
                }
 
                [Localizable(true)]
-               [DefaultValue("")]
+               [DefaultValue(null)]
+               [MWFCategory("Accessibility")]
                public string AccessibleDescription {
                        get {
                                return AccessibilityObject.description;
@@ -957,7 +1368,8 @@ namespace System.Windows.Forms
                }
 
                [Localizable(true)]
-               [DefaultValue("")]
+               [DefaultValue(null)]
+               [MWFCategory("Accessibility")]
                public string AccessibleName {
                        get {
                                return AccessibilityObject.Name;
@@ -968,7 +1380,8 @@ namespace System.Windows.Forms
                        }
                }
 
-               [DefaultValue("")]
+               [DefaultValue(AccessibleRole.Default)]
+               [MWFDescription("Role of the control"), MWFCategory("Accessibility")]
                public AccessibleRole AccessibleRole {
                        get {
                                return AccessibilityObject.role;
@@ -980,19 +1393,27 @@ namespace System.Windows.Forms
                }
 
                [DefaultValue(false)]
+               [MWFCategory("Behavior")]
                public virtual bool AllowDrop {
                        get {
-                               return XplatUI.State.DropTarget;
+                               return allow_drop;
                        }
 
                        set {
-                               XplatUI.State.DropTarget=value;
+                               if (allow_drop == value)
+                                       return;
+                               allow_drop = value;
+                               if (IsHandleCreated) {
+                                       UpdateStyles();
+                                       XplatUI.SetAllowDrop (Handle, value);
+                               }
                        }
                }
 
                [Localizable(true)]
                [RefreshProperties(RefreshProperties.Repaint)]
-               [DefaultValue(AnchorStyles.Top | AnchorStyles.Left)]
+               [DefaultValue(AnchorStyles.Top | AnchorStyles.Left)]
+               [MWFCategory("Layout")]
                public virtual AnchorStyles Anchor {
                        get {
                                return anchor_style;
@@ -1007,12 +1428,31 @@ namespace System.Windows.Forms
                        }
                }
 
+#if NET_2_0
+               // XXX: Implement me!
+               bool auto_size;
+
+               public virtual bool AutoSize {
+                       get {
+                               Console.Error.WriteLine("Unimplemented: Control::get_AutoSize()");
+                               return auto_size;
+                       }
+                       set {
+                               Console.Error.WriteLine("Unimplemented: Control::set_AutoSize(bool)");
+                               auto_size = value;
+                       }
+               }
+#endif // NET_2_0
+
                [DispId(-501)]
+               [MWFCategory("Appearance")]
                public virtual Color BackColor {
                        get {
                                if (background_color.IsEmpty) {
                                        if (parent!=null) {
-                                               return parent.BackColor;
+                                               Color pcolor = parent.BackColor;
+                                               if (pcolor.A == 0xff || GetStyle(ControlStyles.SupportsTransparentBackColor))
+                                                       return pcolor;
                                        }
                                        return DefaultBackColor;
                                }
@@ -1020,10 +1460,11 @@ namespace System.Windows.Forms
                        }
 
                        set {
-                               background_color=value;
-                               if (this.IsHandleCreated) {
-                                       XplatUI.SetWindowBackground(this.window.Handle, value);
+                               if (!value.IsEmpty && (value.A != 0xff) && !GetStyle(ControlStyles.SupportsTransparentBackColor)) {
+                                       throw new ArgumentException("Transparent background colors are not supported on this control");
                                }
+
+                               background_color=value;
                                SetChildColor(this);
                                OnBackColorChanged(EventArgs.Empty);
                                Invalidate();
@@ -1032,6 +1473,7 @@ namespace System.Windows.Forms
 
                [Localizable(true)]
                [DefaultValue(null)]
+               [MWFCategory("Appearance")]
                public virtual Image BackgroundImage {
                        get {
                                return background_image;
@@ -1050,9 +1492,13 @@ namespace System.Windows.Forms
                [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
                public virtual BindingContext BindingContext {
                        get {
+                               if (binding_context != null)
+                                       return binding_context;
+                               if (Parent == null)
+                                       return null;
+                               binding_context = Parent.BindingContext;
                                return binding_context;
                        }
-
                        set {
                                if (binding_context != value) {
                                        binding_context = value;
@@ -1066,10 +1512,6 @@ namespace System.Windows.Forms
                [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
                public int Bottom {
                        get {
-                               if ((this is Form) && (((Form)this).form_parent_window != null)) {
-                                       return ((Form)this).form_parent_window.Bottom;
-                               }
-
                                return bounds.Y+bounds.Height;
                        }
                }
@@ -1092,7 +1534,7 @@ namespace System.Windows.Forms
                [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
                public bool CanFocus {
                        get {
-                               if (is_visible && is_enabled && GetStyle(ControlStyles.Selectable)) {
+                               if (IsHandleCreated && Visible && Enabled) {
                                        return true;
                                }
                                return false;
@@ -1106,11 +1548,11 @@ namespace System.Windows.Forms
                        get {
                                Control parent;
 
-                               if (!GetStyle(ControlStyles.Selectable) || this.parent == null) {
+                               if (!GetStyle(ControlStyles.Selectable)) {
                                        return false;
                                }
 
-                               parent = this.parent;
+                               parent = this;
                                while (parent != null) {
                                        if (!parent.is_visible || !parent.is_enabled) {
                                                return false;
@@ -1122,6 +1564,16 @@ namespace System.Windows.Forms
                        }
                }
 
+               internal virtual bool InternalCapture {
+                       get {
+                               return Capture;
+                       }
+
+                       set {
+                               Capture = value;
+                       }
+               }
+
                [EditorBrowsable(EditorBrowsableState.Advanced)]
                [Browsable(false)]
                [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
@@ -1136,7 +1588,7 @@ namespace System.Windows.Forms
                                                is_captured = true;
                                                XplatUI.GrabWindow(this.window.Handle, IntPtr.Zero);
                                        } else if (!value && is_captured) {
-                                               XplatUI.ReleaseWindow(this.window.Handle);
+                                               XplatUI.UngrabWindow(this.window.Handle);
                                                is_captured = false;
                                        }
                                }
@@ -1144,6 +1596,7 @@ namespace System.Windows.Forms
                }
 
                [DefaultValue(true)]
+               [MWFCategory("Focus")]
                public bool CausesValidation {
                        get {
                                return this.causes_validation;
@@ -1183,11 +1636,6 @@ namespace System.Windows.Forms
                        }
 
                        set {
-                               if ((this is Form) && (((Form)this).form_parent_window != null)) {
-                                       ((Form)this).form_parent_window.ClientSize = value;
-                                       return;
-                               }
-
                                this.SetClientSizeCore(value.Width, value.Height);
                        }
                }
@@ -1221,6 +1669,7 @@ namespace System.Windows.Forms
                }
 
                [DefaultValue(null)]
+               [MWFCategory("Behavior")]
                public virtual ContextMenu ContextMenu {
                        get {
                                return context_menu;
@@ -1247,14 +1696,12 @@ namespace System.Windows.Forms
                [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
                public bool Created {
                        get {
-                               if (!this.is_disposed && (this.window.Handle != IntPtr.Zero)) {
-                                       return true;
-                               }
-                               return false;
+                               return (!is_disposed && is_created);
                        }
                }
 
                [AmbientValue(null)]
+               [MWFCategory("Appearance")]
                public virtual Cursor Cursor {
                        get {
                                if (cursor != null) {
@@ -1274,16 +1721,19 @@ namespace System.Windows.Forms
 
                                        cursor = value;
                                        
-                                       pt = Cursor.Position;
-                                       if (bounds.Contains(pt)) {
-                                               if (GetChildAtPoint(pt) == null) {
-                                                       if (cursor != null) {
-                                                               XplatUI.SetCursor(window.Handle, cursor.handle);
-                                                       } else {
-                                                               if (parent != null) {
-                                                                       XplatUI.SetCursor(window.Handle, parent.Cursor.handle);
+                                       if (IsHandleCreated) {
+                                               pt = Cursor.Position;
+
+                                               if (bounds.Contains(pt)) {
+                                                       if (GetChildAtPoint(pt) == null) {
+                                                               if (cursor != null) {
+                                                                       XplatUI.SetCursor(window.Handle, cursor.handle);
                                                                } else {
-                                                                       XplatUI.SetCursor(window.Handle, Cursors.def.handle);
+                                                                       if (parent != null) {
+                                                                               XplatUI.SetCursor(window.Handle, parent.Cursor.handle);
+                                                                       } else {
+                                                                               XplatUI.SetCursor(window.Handle, Cursors.def.handle);
+                                                                       }
                                                                }
                                                        }
                                                }
@@ -1294,16 +1744,18 @@ namespace System.Windows.Forms
                        }
                }
 
-#if haveDataBindings
-               [EditorBrowsable(EditorBrowsableState.Advanced)]
-               [Browsable(false)]
-               [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
+
+               [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
+               [ParenthesizePropertyName(true)]
+               [RefreshProperties(RefreshProperties.All)]
+               [MWFCategory("Data")]
                public ControlBindingsCollection DataBindings {
                        get {
-                               throw new NotImplementedException();
+                               if (data_bindings == null)
+                                       data_bindings = new ControlBindingsCollection (this);
+                               return data_bindings;
                        }
                }
-#endif
 
                [EditorBrowsable(EditorBrowsableState.Advanced)]
                [Browsable(false)]
@@ -1326,6 +1778,7 @@ namespace System.Windows.Forms
                [Localizable(true)]
                [RefreshProperties(RefreshProperties.Repaint)]
                [DefaultValue(DockStyle.None)]
+               [MWFCategory("Layout")]
                public virtual DockStyle Dock {
                        get {
                                return dock_style;
@@ -1348,9 +1801,18 @@ namespace System.Windows.Forms
 
                [DispId(-514)]
                [Localizable(true)]
+               [MWFCategory("Behavior")]
                public bool Enabled {
                        get {
-                               return is_enabled;
+                               if (!is_enabled) {
+                                       return false;
+                               }
+
+                               if (parent != null) {
+                                       return parent.Enabled;
+                               }
+
+                               return true;
                        }
 
                        set {
@@ -1358,6 +1820,15 @@ namespace System.Windows.Forms
                                        return;
                                }
 
+                               if (IsHandleCreated) {
+                                       if (this is Form) {
+                                               if (((Form)this).context == null) {
+                                                       XplatUI.EnableWindow(window.Handle, value);
+                                               }
+                                       } else {
+                                               XplatUI.EnableWindow(window.Handle, value);
+                                       }
+                               }
                                is_enabled = value;
                                Refresh();
                                OnEnabledChanged (EventArgs.Empty);                             
@@ -1376,6 +1847,7 @@ namespace System.Windows.Forms
                [DispId(-512)]
                [AmbientValue(null)]
                [Localizable(true)]
+               [MWFCategory("Appearance")]
                public virtual Font Font {
                        get {
                                if (font != null) {
@@ -1389,8 +1861,9 @@ namespace System.Windows.Forms
                                return DefaultFont;
                        }
 
+                       [param:MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(Font))]
                        set {
-                               if (font == value) {
+                               if (font != null && font.Equals (value)) {
                                        return;
                                }
 
@@ -1401,6 +1874,7 @@ namespace System.Windows.Forms
                }
 
                [DispId(-513)]
+               [MWFCategory("Appearance")]
                public virtual Color ForeColor {
                        get {
                                if (foreground_color.IsEmpty) {
@@ -1426,6 +1900,13 @@ namespace System.Windows.Forms
                [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
                public IntPtr Handle {                                                  // IWin32Window
                        get {
+#if NET_2_0
+                               if (verify_thread_handle) {
+                                       if (this.InvokeRequired) {
+                                               throw new InvalidOperationException("Cross-thread access of handle detected. Handle access only valid on thread that created the control");
+                                       }
+                               }
+#endif
                                if (!IsHandleCreated) {
                                        CreateHandle();
                                }
@@ -1450,26 +1931,25 @@ namespace System.Windows.Forms
                [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
                public int Height {
                        get {
-                               if ((this is Form) && (((Form)this).form_parent_window != null)) {
-                                       return ((Form)this).form_parent_window.Height;
-                               }
                                return this.bounds.Height;
                        }
 
                        set {
-                               if ((this is Form) && (((Form)this).form_parent_window != null)) {
-                                       ((Form)this).form_parent_window.Height = value;
-                                       return;
-                               }
-
                                SetBoundsCore(bounds.X, bounds.Y, bounds.Width, value, BoundsSpecified.Height);
                        }
                }
 
                [AmbientValue(ImeMode.Inherit)]
                [Localizable(true)]
+               [MWFCategory("Behavior")]
                public ImeMode ImeMode {
                        get {
+                                if (ime_mode == DefaultImeMode) {
+                                       if (parent != null)
+                                                return parent.ImeMode;
+                                        else
+                                                return ImeMode.NoControl; // default value
+                                }
                                return ime_mode;
                        }
 
@@ -1487,7 +1967,7 @@ namespace System.Windows.Forms
                [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
                public bool InvokeRequired {                                            // ISynchronizeInvoke
                        get {
-                               if (creator_thread!=Thread.CurrentThread) {
+                               if (creator_thread != null && creator_thread!=Thread.CurrentThread) {
                                        return true;
                                }
                                return false;
@@ -1521,7 +2001,7 @@ namespace System.Windows.Forms
                [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
                public bool IsHandleCreated {
                        get {
-                               if ((window!=null) && (window.Handle!=IntPtr.Zero)) {
+                               if ((window != null) && (window.Handle != IntPtr.Zero)) {
                                        return true;
                                }
 
@@ -1534,38 +2014,22 @@ namespace System.Windows.Forms
                [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
                public int Left {
                        get {
-                               if ((this is Form) && (((Form)this).form_parent_window != null)) {
-                                       return ((Form)this).form_parent_window.Left;
-                               }
-
                                return this.bounds.X;
                        }
 
                        set {
-                               if ((this is Form) && (((Form)this).form_parent_window != null)) {
-                                       ((Form)this).form_parent_window.Left = value;
-                                       return;
-                               }
-
                                SetBoundsCore(value, bounds.Y, bounds.Width, bounds.Height, BoundsSpecified.X);
                        }
                }
 
                [Localizable(true)]
+               [MWFCategory("Layout")]
                public Point Location {
                        get {
-                               if ((this is Form) && (((Form)this).form_parent_window != null)) {
-                                       return ((Form)this).form_parent_window.Location;
-                               }
                                return new Point(bounds.X, bounds.Y);
                        }
 
                        set {
-                               if ((this is Form) && (((Form)this).form_parent_window != null)) {
-                                       ((Form)this).form_parent_window.Location = value;
-                                       return;
-                               }
-
                                SetBoundsCore(value.X, value.Y, bounds.Width, bounds.Height, BoundsSpecified.Location);
                        }
                }
@@ -1573,13 +2037,26 @@ namespace System.Windows.Forms
                [Browsable(false)]
                public string Name {
                        get {
-                               return this.name;
+                               return name;
+                       }
+
+                       set {
+                               name = value;
+                       }
+               }
+
+#if NET_2_0
+               [Localizable(true)]
+               public Padding Padding {
+                       get {
+                               return padding;
                        }
 
                        set {
-                               this.name=value;
+                               padding = value;
                        }
                }
+#endif
 
                [Browsable(false)]
                [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
@@ -1594,21 +2071,12 @@ namespace System.Windows.Forms
                                }
 
                                if (parent!=value) {
-                                       if (parent!=null) {
+                                       if (value==null) {
                                                parent.Controls.Remove(this);
+                                               return;
                                        }
 
-                                       parent=value;
-
-                                       if (!parent.Controls.Contains(this)) {
-                                               parent.Controls.Add(this);
-                                       }
-
-                                       XplatUI.SetParent(Handle, value.Handle);
-
-                                       InitLayout();
-
-                                       OnParentChanged(EventArgs.Empty);
+                                       value.Controls.Add(this);
                                }
                        }
                }
@@ -1618,7 +2086,15 @@ namespace System.Windows.Forms
                [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
                public string ProductName {
                        get {
-                               return "Novell Mono MWF";
+                                Type t = typeof (AssemblyProductAttribute);
+                                Assembly assembly = GetType().Module.Assembly;
+                                object [] attrs = assembly.GetCustomAttributes (t, false);
+                                AssemblyProductAttribute a = null;
+                                // On MS we get a NullRefException if product attribute is not
+                                // set. 
+                               if (attrs != null && attrs.Length > 0)
+                                       a = (AssemblyProductAttribute) attrs [0];
+                               return a.Product;
                        }
                }
 
@@ -1627,7 +2103,12 @@ namespace System.Windows.Forms
                [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
                public string ProductVersion {
                        get {
-                               return "1.1.4322.573";
+                               Type t = typeof (AssemblyVersionAttribute);
+                               Assembly assembly = GetType().Module.Assembly;
+                               object [] attrs = assembly.GetCustomAttributes (t, false);
+                               if (attrs == null || attrs.Length < 1)
+                                       return "1.0.0.0";
+                               return ((AssemblyVersionAttribute)attrs [0]).Version;
                        }
                }
 
@@ -1666,18 +2147,21 @@ namespace System.Windows.Forms
                [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
                public int Right {
                        get {
-                               if ((this is Form) && (((Form)this).form_parent_window != null)) {
-                                       return ((Form)this).form_parent_window.Right;
-                               }
-
                                return this.bounds.X+this.bounds.Width;
                        }
                }
 
                [AmbientValue(RightToLeft.Inherit)]
                [Localizable(true)]
+               [MWFCategory("Appearance")]
                public virtual RightToLeft RightToLeft {
                        get {
+                               if (right_to_left == RightToLeft.Inherit) {
+                                       if (parent != null)
+                                               return parent.RightToLeft;
+                                       else
+                                               return RightToLeft.No; // default value
+                               }
                                return right_to_left;
                        }
 
@@ -1697,29 +2181,32 @@ namespace System.Windows.Forms
 
                        set {
                                base.Site = value;
+
+                               AmbientProperties ap = (AmbientProperties) value.GetService (typeof (AmbientProperties));
+                               if (ap != null) {
+                                       BackColor = ap.BackColor;
+                                       ForeColor = ap.ForeColor;
+                                       Cursor = ap.Cursor;
+                                       Font = ap.Font;
+                               }
                        }
                }
 
                [Localizable(true)]
+               [MWFCategory("Layout")]
                public Size Size {
                        get {
-                               if ((this is Form) && (((Form)this).form_parent_window != null)) {
-                                       return ((Form)this).form_parent_window.Size;
-                               }
                                return new Size(Width, Height);
                        }
 
                        set {
-                               if ((this is Form) && (((Form)this).form_parent_window != null)) {
-                                       ((Form)this).form_parent_window.Size = value;
-                                       return;
-                               }
                                SetBoundsCore(bounds.X, bounds.Y, value.Width, value.Height, BoundsSpecified.Size);
                        }
                }
 
                [Localizable(true)]
                [MergableProperty(false)]
+               [MWFCategory("Behavior")]
                public int TabIndex {
                        get {
                                if (tab_index != -1) {
@@ -1738,6 +2225,7 @@ namespace System.Windows.Forms
 
                [DispId(-516)]
                [DefaultValue(true)]
+               [MWFCategory("Behavior")]
                public bool TabStop {
                        get {
                                return tab_stop;
@@ -1755,6 +2243,7 @@ namespace System.Windows.Forms
                [Bindable(true)]
                [TypeConverter(typeof(StringConverter))]
                [DefaultValue(null)]
+               [MWFCategory("Data")]
                public object Tag {
                        get {
                                return control_tag;
@@ -1768,8 +2257,10 @@ namespace System.Windows.Forms
                [DispId(-517)]
                [Localizable(true)]
                [BindableAttribute(true)]
+               [MWFCategory("Appearance")]
                public virtual string Text {
                        get {
+                               // Our implementation ignores ControlStyles.CacheText - we always cache
                                return this.text;
                        }
 
@@ -1780,30 +2271,23 @@ namespace System.Windows.Forms
 
                                if (text!=value) {
                                        text=value;
-                                       XplatUI.Text(Handle, text);
-                                       // FIXME: Do we need a Refresh() here?
+                                       if (IsHandleCreated) {
+                                               XplatUI.Text(Handle, text);
+                                       }
                                        OnTextChanged (EventArgs.Empty);
                                }
                        }
                }
 
-               [EditorBrowsable(EditorBrowsableState.Advanced)]
+               [EditorBrowsable(EditorBrowsableState.Always)]
                [Browsable(false)]
                [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
                public int Top {
                        get {
-                               if ((this is Form) && (((Form)this).form_parent_window != null)) {
-                                       return ((Form)this).form_parent_window.Top;
-                               }
                                return this.bounds.Y;
                        }
 
                        set {
-                               if ((this is Form) && (((Form)this).form_parent_window != null)) {
-                                       ((Form)this).form_parent_window.Top = value;
-                                       return;
-                               }
-
                                SetBoundsCore(bounds.X, value, bounds.Width, bounds.Height, BoundsSpecified.Y);
                        }
                }
@@ -1824,24 +2308,19 @@ namespace System.Windows.Forms
                }
 
                [Localizable(true)]
+               [MWFCategory("Behavior")]
                public bool Visible {
                        get {
-                               if ((this is Form) && (((Form)this).form_parent_window != null)) {
-                                       return ((Form)this).form_parent_window.Visible;
-                               }
                                if (!is_visible) {
                                        return false;
+                               } else if (parent != null) {
+                                       return parent.Visible;
                                }
 
                                return true;
                        }
 
                        set {
-                               if ((this is Form) && (((Form)this).form_parent_window != null)) {
-                                       ((Form)this).form_parent_window.Visible = value;
-                                       return;
-                               }
-
                                SetVisibleCore(value);
                        }
                }
@@ -1851,18 +2330,10 @@ namespace System.Windows.Forms
                [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
                public int Width {
                        get {
-                               if ((this is Form) && (((Form)this).form_parent_window != null)) {
-                                       return ((Form)this).form_parent_window.Width;
-                               }
                                return this.bounds.Width;
                        }
 
                        set {
-                               if ((this is Form) && (((Form)this).form_parent_window != null)) {
-                                       ((Form)this).form_parent_window.Width = value;
-                                       return;
-                               }
-
                                SetBoundsCore(bounds.X, bounds.Y, value, bounds.Height, BoundsSpecified.Width);
                        }
                }
@@ -1886,18 +2357,52 @@ namespace System.Windows.Forms
                        get {
                                CreateParams create_params = new CreateParams();
 
-                               create_params.Caption = Text;
-                               create_params.X = Left;
-                               create_params.Y = Top;
-                               create_params.Width = Width;
-                               create_params.Height = Height;
+                               try {
+                                       create_params.Caption = Text;
+                               }
+                               catch {
+                                       create_params.Caption = text;
+                               }
+
+                               try {
+                                       create_params.X = Left;
+                               }
+                               catch {
+                                       create_params.X = this.bounds.X;
+                               }
+
+                               try {
+                                       create_params.Y = Top;
+                               }
+                               catch {
+                                       create_params.Y = this.bounds.Y;
+                               }
+
+                               try {
+                                       create_params.Width = Width;
+                               }
+                               catch {
+                                       create_params.Width = this.bounds.Width;
+                               }
+
+                               try {
+                                       create_params.Height = Height;
+                               }
+                               catch {
+                                       create_params.Height = this.bounds.Height;
+                               }
+
 
                                create_params.ClassName = XplatUI.DefaultClassName;
                                create_params.ClassStyle = 0;
                                create_params.ExStyle = 0;
                                create_params.Param = 0;
 
-                               if (parent!=null) {
+                               if (allow_drop) {
+                                       create_params.ExStyle |= (int)WindowExStyles.WS_EX_ACCEPTFILES;
+                               }
+
+                               if ((parent!=null) && (parent.IsHandleCreated)) {
                                        create_params.Parent = parent.Handle;
                                }
 
@@ -1907,6 +2412,19 @@ namespace System.Windows.Forms
                                        create_params.Style |= (int)WindowStyles.WS_VISIBLE;
                                }
 
+                               if (!is_enabled) {
+                                       create_params.Style |= (int)WindowStyles.WS_DISABLED;
+                               }
+
+                               switch (border_style) {
+                               case BorderStyle.FixedSingle:
+                                       create_params.Style |= (int) WindowStyles.WS_BORDER;
+                                       break;
+                               case BorderStyle.Fixed3D:
+                                       create_params.ExStyle |= (int) WindowExStyles.WS_EX_CLIENTEDGE;
+                                       break;
+                               }
+
                                return create_params;
                        }
                }
@@ -1919,7 +2437,7 @@ namespace System.Windows.Forms
 
                protected virtual Size DefaultSize {
                        get {
-                               return new Size(100, 23);
+                               return new Size(0, 0);
                        }
                }
 
@@ -1986,6 +2504,7 @@ namespace System.Windows.Forms
 
                [EditorBrowsable(EditorBrowsableState.Advanced)]
                public static Control FromHandle(IntPtr handle) {
+#if not
                        IEnumerator control = Control.controls.GetEnumerator();
 
                        while (control.MoveNext()) {
@@ -1994,7 +2513,11 @@ namespace System.Windows.Forms
                                        return ((Control)control.Current);
                                }
                        }
+
                        return null;
+#else
+                       return Control.ControlNativeWindow.ControlFromHandle(handle);
+#endif
                }
 
                public static bool IsMnemonic(char charCode, string text) {
@@ -2033,12 +2556,15 @@ namespace System.Windows.Forms
                #region Public Instance Methods
                [EditorBrowsable(EditorBrowsableState.Advanced)]
                public IAsyncResult BeginInvoke(Delegate method) {
-                       return BeginInvokeInternal(method, null);
+                       object [] prms = null;
+                       if (method is EventHandler)
+                               prms = new object [] { this, EventArgs.Empty };
+                       return BeginInvokeInternal(method, prms, false);
                }
 
                [EditorBrowsable(EditorBrowsableState.Advanced)]
                public IAsyncResult BeginInvoke (Delegate method, object[] args) {
-                       return BeginInvokeInternal (method, args);
+                       return BeginInvokeInternal (method, args, false);
                }
 
                public void BringToFront() {
@@ -2046,10 +2572,19 @@ namespace System.Windows.Forms
                                if (parent.child_controls.Contains(this)) {
                                        parent.child_controls.SetChildIndex(this, 0);
                                }
+                       } else if (parent != null) {
+                               if (parent.child_controls.impl_list != null) {
+                                       Control last_impl = (Control) parent.child_controls.impl_list [parent.child_controls.impl_list.Count - 1];
+                                       if (IsHandleCreated) {
+                                               XplatUI.SetZOrder (this.window.Handle, last_impl.Handle, false, false);
+                                       }
+                               } else {
+                                       if (IsHandleCreated) {
+                                               XplatUI.SetZOrder(this.window.Handle, IntPtr.Zero, true, false);
+                                       }
+                               }
                        }
 
-                       XplatUI.SetZOrder(this.window.Handle, IntPtr.Zero, true, false);
-
                        if (parent != null) {
                                parent.Refresh();
                        }
@@ -2066,13 +2601,29 @@ namespace System.Windows.Forms
                }
 
                public void CreateControl() {
+                       if (is_created) {
+                               return;
+                       }
 
-                       if (!IsHandleCreated)
+                       if (!IsHandleCreated) {
                                CreateHandle();
+                       }
 
-                       for (int i=0; i<child_controls.Count; i++) {
-                               child_controls[i].CreateControl();
+                       if (!is_created) {
+                               is_created = true;
+                       }
+
+                       Control [] controls = child_controls.GetAllControls ();
+                       for (int i=0; i<controls.Length; i++) {
+                               controls [i].CreateControl ();
                        }
+
+                       UpdateZOrder();
+
+                       if (binding_context == null) {  // seem to be sent whenever it's null?
+                               OnBindingContextChanged(EventArgs.Empty);
+                       }
+
                        OnCreateControl();
                }
 
@@ -2083,9 +2634,8 @@ namespace System.Windows.Forms
                        return Graphics.FromHwnd(this.window.Handle);
                }
 
-               [MonoTODO("Come up with cross platform drag-drop driver interface")]
                public DragDropEffects DoDragDrop(object data, DragDropEffects allowedEffects) {
-                       return DragDropEffects.None;
+                       return XplatUI.StartDrag(this.window.Handle, data, allowedEffects);
                }
 
                [EditorBrowsable(EditorBrowsableState.Advanced)]
@@ -2108,11 +2658,10 @@ namespace System.Windows.Forms
                }
 
                public bool Focus() {
-                       if (IsHandleCreated && !has_focus) {
+                       if (CanFocus && IsHandleCreated && !has_focus) {
                                XplatUI.SetFocus(window.Handle);
                        }
-                       has_focus = true;
-                       return true;
+                       return has_focus;
                }
 
                public Control GetChildAtPoint(Point pt) {
@@ -2176,16 +2725,18 @@ namespace System.Windows.Forms
                }
 
                public void Invalidate(System.Drawing.Rectangle rc, bool invalidateChildren) {
-                       if (!IsHandleCreated || !Visible) {
+                       if (!IsHandleCreated || !Visible || rc.Width == 0 || rc.Height == 0) {
                                return;
                        }
 
                        NotifyInvalidate(rc);
 
-                       XplatUI.Invalidate(Handle, rc, !GetStyle (ControlStyles.AllPaintingInWmPaint));
+                       XplatUI.Invalidate(Handle, rc, false);
 
                        if (invalidateChildren) {
-                               for (int i=0; i<child_controls.Count; i++) child_controls[i].Invalidate();
+                               Control [] controls = child_controls.GetAllControls ();
+                               for (int i=0; i<controls.Length; i++)
+                                       controls [i].Invalidate ();
                        }
                        OnInvalidated(new InvalidateEventArgs(rc));
                }
@@ -2194,25 +2745,42 @@ namespace System.Windows.Forms
                        Invalidate(region, false);
                }
 
-               [MonoTODO("Figure out if GetRegionScans is usable")]
                public void Invalidate(System.Drawing.Region region, bool invalidateChildren) {
-                       throw new NotImplementedException();
-
-                       // FIXME - should use the GetRegionScans function of the region to invalidate each area
-                       //if (invalidateChildren) {
-                       //      for (int i=0; i<child_controls.Count; i++) child_controls[i].Invalidate();
-                       //}
+                       RectangleF bounds = region.GetBounds (CreateGraphics ());
+                       Invalidate (new Rectangle ((int) bounds.X, (int) bounds.Y, (int) bounds.Width, (int) bounds.Height),
+                                       invalidateChildren);
                }
 
                public object Invoke (Delegate method) {
-                       return Invoke(method, null);
+                       object [] prms = null;
+                       if (method is EventHandler)
+                               prms = new object [] { this, EventArgs.Empty };
+
+                       return Invoke(method, prms);
                }
 
                public object Invoke (Delegate method, object[] args) {
+                       if (!this.InvokeRequired) {
+                               return method.DynamicInvoke(args);
+                       }
+
                        IAsyncResult result = BeginInvoke (method, args);
                        return EndInvoke(result);
                }
 
+               internal object InvokeInternal (Delegate method, bool disposing) {
+                       return InvokeInternal(method, null, disposing);
+               }
+
+               internal object InvokeInternal (Delegate method, object[] args, bool disposing) {
+                       if (!this.InvokeRequired) {
+                               return method.DynamicInvoke(args);
+                       }
+
+                       IAsyncResult result = BeginInvokeInternal (method, args, disposing);
+                       return EndInvoke(result);
+               }
+
                [EditorBrowsable(EditorBrowsableState.Advanced)]
                public void PerformLayout() {
                        PerformLayout(null, null);
@@ -2222,7 +2790,7 @@ namespace System.Windows.Forms
                public void PerformLayout(Control affectedControl, string affectedProperty) {
                        LayoutEventArgs levent = new LayoutEventArgs(affectedControl, affectedProperty);
 
-                       if (layout_suspended>0) {
+                       if (layout_suspended > 0) {
                                layout_pending = true;
                                return;
                        }
@@ -2237,109 +2805,112 @@ namespace System.Windows.Forms
                                Control         child;
                                AnchorStyles    anchor;
                                Rectangle       space;
-                               int             diff_width;
-                               int             diff_height;
 
-                               space=this.DisplayRectangle;
-                               if (prev_size != Size.Empty) {
-                                       diff_width = space.Width - prev_size.Width;
-                                       diff_height = space.Height - prev_size.Height;
-                               } else {
-                                       diff_width = 0;
-                                       diff_height = 0;
-                               }
+                               space= DisplayRectangle;
 
                                // Deal with docking; go through in reverse, MS docs say that lowest Z-order is closest to edge
-                               for (int i = child_controls.Count - 1; i >= 0; i--) {
-                                       child=child_controls[i];
-                                       switch (child.Dock) {
-                                       case DockStyle.None: {
-                                               // Do nothing
-                                               break;
-                                       }
+                               Control [] controls = child_controls.GetAllControls ();
+                               for (int i = controls.Length - 1; i >= 0; i--) {
+                                       child = controls [i];
 
-                                       case DockStyle.Left: {
-                                               child.SetBounds(space.Left, space.Y, child.Width, space.Height);
-                                               space.X+=child.Width;
-                                               space.Width-=child.Width;
-                                               break;
+                                       if (!child.Visible) {
+                                               continue;
                                        }
 
-                                       case DockStyle.Top: {
-                                               child.SetBounds(space.Left, space.Y, space.Width, child.Height);
-                                               space.Y+=child.Height;
-                                               space.Height-=child.Height;
-                                               break;
-                                       }
-                               
-                                       case DockStyle.Right: {
-                                               child.SetBounds(space.Right-child.Width, space.Y, child.Width, space.Height);
-                                               space.Width-=child.Width;
-                                               break;
-                                       }
+                                       switch (child.Dock) {
+                                               case DockStyle.None: {
+                                                       // Do nothing
+                                                       break;
+                                               }
+
+                                               case DockStyle.Left: {
+                                                       child.SetBounds(space.Left, space.Y, child.Width, space.Height);
+                                                       space.X+=child.Width;
+                                                       space.Width-=child.Width;
+                                                       break;
+                                               }
+
+                                               case DockStyle.Top: {
+                                                       child.SetBounds(space.Left, space.Y, space.Width, child.Height);
+                                                       space.Y+=child.Height;
+                                                       space.Height-=child.Height;
+                                                       break;
+                                               }
+                                       
+                                               case DockStyle.Right: {
+                                                       child.SetBounds(space.Right-child.Width, space.Y, child.Width, space.Height);
+                                                       space.Width-=child.Width;
+                                                       break;
+                                               }
 
-                                       case DockStyle.Bottom: {
-                                               child.SetBounds(space.Left, space.Bottom-child.Height, space.Width, child.Height);
-                                               space.Height-=child.Height;
-                                               break;
+                                               case DockStyle.Bottom: {
+                                                       child.SetBounds(space.Left, space.Bottom-child.Height, space.Width, child.Height);
+                                                       space.Height-=child.Height;
+                                                       break;
+                                               }
                                        }
+                               }
 
-                                       case DockStyle.Fill: {
+                               for (int i = controls.Length - 1; i >= 0; i--) {
+                                       child=controls[i];
+
+                                       if (child.Visible && (child.Dock == DockStyle.Fill)) {
                                                child.SetBounds(space.Left, space.Top, space.Width, space.Height);
                                                space.Width=0;
                                                space.Height=0;
-                                               break;
-                                       }
                                        }
                                }
 
-                               space=this.DisplayRectangle;
+                               space=DisplayRectangle;
 
-                               // Deal with anchoring
-                               for (int i=0; i < child_controls.Count; i++) {
+                               for (int i=0; i < controls.Length; i++) {
                                        int left;
                                        int top;
                                        int width;
                                        int height;
 
-                                       child=child_controls[i];
-                                       anchor=child.Anchor;
-
-                                       left=child.Left;
-                                       top=child.Top;
-                                       width=child.Width;
-                                       height=child.Height;
+                                       child = controls[i];
 
                                        // If the control is docked we don't need to do anything
                                        if (child.Dock != DockStyle.None) {
                                                continue;
                                        }
 
+                                       anchor = child.Anchor;
+
+                                       left = child.Left;
+                                       top = child.Top;
+                                       width = child.Width;
+                                       height = child.Height;
+
                                        if ((anchor & AnchorStyles.Left) !=0 ) {
                                                if ((anchor & AnchorStyles.Right) != 0) {
-                                                       // Anchoring to left and right
-                                                       width=width+diff_width;
+                                                       width = space.Width - child.dist_right - left;
                                                } else {
-                                                       ; // nothing to do
+                                                       ; // Left anchored only, nothing to be done
                                                }
                                        } else if ((anchor & AnchorStyles.Right) != 0) {
-                                               left+=diff_width;
+                                               left = space.Width - child.dist_right - width;
                                        } else {
-                                               left+=diff_width/2;
+                                               // left+=diff_width/2 will introduce rounding errors (diff_width removed from svn after r51780)
+                                               // This calculates from scratch every time:
+                                               left = child.dist_left + (space.Width - (child.dist_left + width + child.dist_right)) / 2;
                                        }
 
                                        if ((anchor & AnchorStyles.Top) !=0 ) {
                                                if ((anchor & AnchorStyles.Bottom) != 0) {
-                                                       height+=diff_height;
+                                                       height = space.Height - child.dist_bottom - top;
                                                } else {
-                                                       ; // nothing to do
+                                                       ; // Top anchored only, nothing to be done
                                                }
                                        } else if ((anchor & AnchorStyles.Bottom) != 0) {
-                                               top+=diff_height;
+                                               top = space.Height - child.dist_bottom - height;
                                        } else {
-                                               top+=diff_height/2;
+                                               // top += diff_height/2 will introduce rounding errors (diff_height removed from after r51780)
+                                               // This calculates from scratch every time:
+                                               top = child.dist_top + (space.Height - (child.dist_top + height + child.dist_bottom)) / 2;
                                        }
-
+                                       
                                        // Sanity
                                        if (width < 0) {
                                                width=0;
@@ -2383,8 +2954,9 @@ namespace System.Windows.Forms
                public virtual bool PreProcessMessage(ref Message msg) {
                        Keys key_data;
 
-                       if (msg.Msg == (int)Msg.WM_KEYDOWN) {
-                               key_data = (Keys)msg.WParam.ToInt32();
+                       if ((msg.Msg == (int)Msg.WM_KEYDOWN) || (msg.Msg == (int)Msg.WM_SYSKEYDOWN)) {
+                               key_data = (Keys)msg.WParam.ToInt32() | XplatUI.State.ModifierKeys;
+
                                if (!ProcessCmdKey(ref msg, key_data)) {
                                        if (IsInputKey(key_data)) {
                                                return false;
@@ -2398,10 +2970,12 @@ namespace System.Windows.Forms
                                if (IsInputChar((char)msg.WParam)) {
                                        return false;
                                }
-
+                       } else if (msg.Msg == (int)Msg.WM_SYSCHAR) {
+                               if (IsInputChar((char)msg.WParam)) {
+                                       return false;
+                               }
                                return ProcessDialogChar((char)msg.WParam);
                        }
-
                        return false;
                }
 
@@ -2417,6 +2991,12 @@ namespace System.Windows.Forms
                        if (IsHandleCreated == true) {
                                Invalidate();
                                XplatUI.UpdateWindow(window.Handle);
+
+                               Control [] controls = child_controls.GetAllControls ();
+                               for (int i=0; i < controls.Length; i++) {
+                                       controls[i].Refresh();
+                               }
+                               
                        }
                }
 
@@ -2425,17 +3005,14 @@ namespace System.Windows.Forms
                        background_color = Color.Empty;
                }
 
-#if haveDataBindings
                [EditorBrowsable(EditorBrowsableState.Never)]
-               [MonoTODO]
                public void ResetBindings() {
-                       // Do something
+                       data_bindings.Clear();
                }
-#endif
 
                [EditorBrowsable(EditorBrowsableState.Never)]
                public virtual void ResetCursor() {
-                       cursor = null;
+                       Cursor = null;
                }
 
                [EditorBrowsable(EditorBrowsableState.Never)]
@@ -2459,7 +3036,7 @@ namespace System.Windows.Forms
                }
 
                public virtual void ResetText() {
-                       text = null;
+                       text = String.Empty;
                }
 
                public void ResumeLayout() {
@@ -2467,14 +3044,19 @@ namespace System.Windows.Forms
                }
 
                public void ResumeLayout(bool performLayout) {
-                       layout_suspended--;
-                       
                        if (layout_suspended > 0) {
-                               return;
+                               layout_suspended--;
                        }
 
-                       if (performLayout || layout_pending) {
-                               PerformLayout();
+                       if (layout_suspended == 0) {
+                               Control [] controls = child_controls.GetAllControls ();
+                               for (int i=0; i<controls.Length; i++) {
+                                       controls [i].UpdateDistances ();
+                               }
+
+                               if (performLayout && layout_pending) {
+                                       PerformLayout();
+                               }
                        }
                }
 
@@ -2504,7 +3086,7 @@ namespace System.Windows.Forms
                                        break;
                                }
 
-                               if (c.CanSelect && ((c.parent == this) || nested) && (c.tab_stop || !tabStopOnly)) {
+                               if (c.CanSelect && ((c.parent == ctl.parent) || nested) && (c.tab_stop || !tabStopOnly)) {
                                        Select(c);
                                        return true;
                                }
@@ -2520,7 +3102,10 @@ namespace System.Windows.Forms
                                }
                        }
 
-                       XplatUI.SetZOrder(this.window.Handle, IntPtr.Zero, false, true);
+                       if (IsHandleCreated) {
+                               XplatUI.SetZOrder(this.window.Handle, IntPtr.Zero, false, true);
+                       }
+
                        if (parent != null) {
                                parent.Refresh();
                        }
@@ -2535,8 +3120,8 @@ namespace System.Windows.Forms
                }
 
                public void Show() {
-                       if (!IsHandleCreated) {
-                               this.CreateHandle();
+                       if (!is_created) {
+                               this.CreateControl();
                        }
 
                        this.Visible=true;
@@ -2547,7 +3132,10 @@ namespace System.Windows.Forms
                }
 
                public void Update() {
-                       XplatUI.UpdateWindow(window.Handle);
+                       needs_redraw = true;
+                       if (IsHandleCreated) {
+                               XplatUI.UpdateWindow(window.Handle);
+                       }
                }
                #endregion      // Public Instance Methods
 
@@ -2574,30 +3162,48 @@ namespace System.Windows.Forms
                                throw new ObjectDisposedException(Name);
                        }
 
-                       if (IsHandleCreated) {
+                       if (IsHandleCreated && !is_recreating) {
                                return;
                        }
 
-                       if (window==null) {
-                               window = new ControlNativeWindow(this);
-                               window.CreateHandle(CreateParams);
+                       window.CreateHandle(CreateParams);
 
-                               // Find out where the window manager placed us
-                               UpdateBounds();
-                               UpdateStyles();
-                       }
-
-                       if (window.Handle!=IntPtr.Zero) {
+                       if (window.Handle != IntPtr.Zero) {
                                if (!controls.Contains(window.Handle)) {
                                        controls.Add(this);
                                }
 
                                creator_thread = Thread.CurrentThread;
 
-                               XplatUI.SetWindowBackground(window.Handle, this.BackColor);
+                               XplatUI.EnableWindow(window.Handle, is_enabled);
+
+                               // Set our handle with our parent
+                               if ((parent != null) && (parent.IsHandleCreated)) {
+                                       XplatUI.SetParent(window.Handle, parent.Handle);
+                               }
+
+                               // Set our handle as parent for our children
+                               Control [] children;
+
+                               children = child_controls.GetAllControls ();
+                               for (int i = 0; i < children.Length; i++ ) {
+                                       if (children[i].IsHandleCreated) {
+                                               XplatUI.SetParent(children[i].Handle, window.Handle); 
+                                       }
+                               }
+
+                               UpdateStyles();
+                               XplatUI.SetAllowDrop (Handle, allow_drop);
+
+                               // Find out where the window manager placed us
+                               if ((CreateParams.Style & (int)WindowStyles.WS_CHILD) != 0) {
+                                       XplatUI.SetBorderStyle(window.Handle, (FormBorderStyle)border_style);
+                               }
+                               UpdateBounds();
 
                                OnHandleCreated(EventArgs.Empty);
                        }
+
                }
 
                [EditorBrowsable(EditorBrowsableState.Advanced)]
@@ -2608,10 +3214,6 @@ namespace System.Windows.Forms
                [EditorBrowsable(EditorBrowsableState.Advanced)]
                protected virtual void DestroyHandle() {
                        if (IsHandleCreated) {
-                               if (Handle != IntPtr.Zero) {
-                                       controls.Remove(Handle);
-                               }
-
                                if (window != null) {
                                        window.DestroyHandle();
                                }
@@ -2628,9 +3230,7 @@ namespace System.Windows.Forms
 
                [EditorBrowsable(EditorBrowsableState.Advanced)]
                protected virtual void InitLayout() {
-                       if (parent != null) {
-                               parent.PerformLayout(this, "parent");
-                       }
+                       UpdateDistances();
                }
 
                [EditorBrowsable(EditorBrowsableState.Advanced)]
@@ -2657,10 +3257,6 @@ namespace System.Windows.Forms
                }
 
                protected virtual bool IsInputChar (char charCode) {
-                       if (parent != null) {
-                               return parent.IsInputChar(charCode);
-                       }
-
                        return true;
                }
 
@@ -2706,20 +3302,22 @@ namespace System.Windows.Forms
                {
                        KeyEventArgs            key_event;
 
-                       PreProcessMessage(ref msg);
-
                        switch (msg.Msg) {
+                               case (int)Msg.WM_SYSKEYDOWN:
                                case (int)Msg.WM_KEYDOWN: {
                                        key_event = new KeyEventArgs ((Keys)msg.WParam.ToInt32 ());
                                        OnKeyDown (key_event);
                                        return key_event.Handled;
                                }
+
+                               case (int)Msg.WM_SYSKEYUP:
                                case (int)Msg.WM_KEYUP: {
                                        key_event = new KeyEventArgs ((Keys)msg.WParam.ToInt32 ());
                                        OnKeyUp (key_event);
                                        return key_event.Handled;
                                }
 
+                               case (int)Msg.WM_SYSCHAR:
                                case (int)Msg.WM_CHAR: {
                                        KeyPressEventArgs       key_press_event;
 
@@ -2781,21 +3379,17 @@ namespace System.Windows.Forms
 
                [EditorBrowsable(EditorBrowsableState.Advanced)]
                protected void RecreateHandle() {
-                       IEnumerator child = child_controls.GetEnumerator();
-
                        is_recreating=true;
 
                        if (IsHandleCreated) {
                                DestroyHandle();
-                               CreateHandle();
-
-                               // FIXME ZOrder?
-
-                               while (child.MoveNext()) {
-                                       ((Control)child.Current).RecreateHandle();
-                               }
+                               // WM_DESTROY will CreateHandle for us
                        } else {
-                               CreateHandle();
+                               if (!is_created) {
+                                       CreateControl();
+                               } else {
+                                       CreateHandle();
+                               }
                        }
 
                        is_recreating = false;
@@ -2896,7 +3490,6 @@ namespace System.Windows.Forms
 
                        location = new Point((int)(Left * dx), (int)(Top * dy));
                        size = this.ClientSize;
-                       
 
                        if (!GetStyle(ControlStyles.FixedWidth)) {
                                size.Width = (int)(size.Width * dx);
@@ -2906,12 +3499,12 @@ namespace System.Windows.Forms
                                size.Height = (int)(size.Height * dy);
                        }
 
-                       Location = location;
-                       ClientSize = size;
+                       SetBoundsCore(location.X, location.Y, size.Width, size.Height, BoundsSpecified.All);
 
                        /* Now scale our children */
-                       for (int i=0; i < child_controls.Count; i++) {
-                               child_controls[i].Scale(dx, dy);
+                       Control [] controls = child_controls.GetAllControls ();
+                       for (int i=0; i < controls.Length; i++) {
+                               controls[i].Scale(dx, dy);
                        }
 
                        ResumeLayout();
@@ -2931,6 +3524,8 @@ namespace System.Windows.Forms
                                return;
                        }
 
+                       // FIXME - this thing is doing the wrong stuff, needs to be similar to SelectNextControl
+
                        index = parent.child_controls.IndexOf(this);
                        result = false;
 
@@ -2963,7 +3558,7 @@ namespace System.Windows.Forms
                                y = Top;
                        }
 
-                       if ((specified & BoundsSpecified.Width)!= BoundsSpecified.Width) {
+                       if ((specified & BoundsSpecified.Width) != BoundsSpecified.Width) {
                                width = Width;
                        }
 
@@ -2974,7 +3569,10 @@ namespace System.Windows.Forms
                        if (IsHandleCreated) {
                                XplatUI.SetWindowPos(Handle, x, y, width, height);
                        }
+
                        UpdateBounds(x, y, width, height);
+
+                       UpdateDistances();
                }
 
                [EditorBrowsable(EditorBrowsableState.Advanced)]
@@ -2987,7 +3585,7 @@ namespace System.Windows.Forms
                        ClientRect = new Rectangle(0, 0, x, y);
                        cp = this.CreateParams;
 
-                       if (XplatUI.CalculateWindowRect(Handle, ref ClientRect, cp.Style, false, out WindowRect)==false) {
+                       if (XplatUI.CalculateWindowRect(ref ClientRect, cp.Style, cp.ExStyle, null, out WindowRect)==false) {
                                return;
                        }
 
@@ -3024,30 +3622,33 @@ namespace System.Windows.Forms
 
                protected virtual void SetVisibleCore(bool value) {
                        if (value!=is_visible) {
+                               if (value && !is_created) {
+                                       CreateControl();
+                               }
+
                                is_visible=value;
-                               XplatUI.SetVisible(Handle, value);
-                               // Explicitly move Toplevel windows to where we want them;
-                               // apparently moving unmapped toplevel windows doesn't work
-                               if (is_visible && (this is Form.FormParentWindow)) {
-                                       XplatUI.SetWindowPos(window.Handle, bounds.X, bounds.Y, bounds.Width, bounds.Height);
+
+                               if (IsHandleCreated) {
+                                       XplatUI.SetVisible(Handle, value);
+                                       // Explicitly move Toplevel windows to where we want them;
+                                       // apparently moving unmapped toplevel windows doesn't work
+                                       if (is_visible && (this is Form)) {
+                                               XplatUI.SetWindowPos(window.Handle, bounds.X, bounds.Y, bounds.Width, bounds.Height);
+                                       }
                                }
+
                                OnVisibleChanged(EventArgs.Empty);
-                               if (!is_visible) {
-                                       if (dc_mem != null) {
-                                               dc_mem.Dispose();
-                                               dc_mem = null;
-                                       }
 
-                                       if (bmp_mem != null) {
-                                               bmp_mem.Dispose();
-                                               bmp_mem = null;
+                               if (value == false && parent != null) {
+                                       Control container;
+
+                                       // Need to start at parent, GetContainerControl might return ourselves if we're a container
+                                       container = (Control)parent.GetContainerControl();
+                                       if (container != null) {
+                                               container.SelectNextControl(this, true, true, true, true);
                                        }
-                               } else {
-                                       this.CreateBuffers(bounds.Width, bounds.Height);
                                }
 
-                               // FIXME - deal with focus
-
                                if (parent != null) {
                                        parent.PerformLayout(this, "visible");
                                } else {
@@ -3069,19 +3670,30 @@ namespace System.Windows.Forms
                                CreateHandle();
                        }
 
-                       XplatUI.GetWindowPos(this.Handle, this is Form.FormParentWindow, out x, out y, out width, out height, out client_width, out client_height);
+                       XplatUI.GetWindowPos(this.Handle, this is Form, out x, out y, out width, out height, out client_width, out client_height);
+
                        UpdateBounds(x, y, width, height, client_width, client_height);
                }
 
                [EditorBrowsable(EditorBrowsableState.Advanced)]
                protected void UpdateBounds(int x, int y, int width, int height) {
+                       CreateParams    cp;
+                       Rectangle       rect;
+
+                       // Calculate client rectangle
+                       rect = new Rectangle(0, 0, 0, 0);
+                       cp = CreateParams;
+
+                       XplatUI.CalculateWindowRect(ref rect, cp.Style, cp.ExStyle, cp.menu, out rect);
+                       UpdateBounds(x, y, width, height, width - (rect.Right - rect.Left), height - (rect.Bottom - rect.Top));
+               }
+
+               [EditorBrowsable(EditorBrowsableState.Advanced)]
+               protected void UpdateBounds(int x, int y, int width, int height, int clientWidth, int clientHeight) {
                        // UpdateBounds only seems to set our sizes and fire events but not update the GUI window to match
                        bool    moved   = false;
                        bool    resized = false;
 
-                       int     client_x_diff = this.bounds.Width-this.client_size.Width;
-                       int     client_y_diff = this.bounds.Height-this.client_size.Height;
-
                        // Needed to generate required notifications
                        if ((this.bounds.X!=x) || (this.bounds.Y!=y)) {
                                moved=true;
@@ -3096,14 +3708,8 @@ namespace System.Windows.Forms
                        bounds.Width=width;
                        bounds.Height=height;
 
-                       // Update client rectangle as well
-                       if (this.layout_suspended==0) {
-                               prev_size.Width=client_size.Width;
-                               prev_size.Height=client_size.Height;
-                       }
-
-                       client_size.Width=width-client_x_diff;
-                       client_size.Height=height-client_y_diff;
+                       client_size.Width=clientWidth;
+                       client_size.Height=clientHeight;
 
                        if (moved) {
                                OnLocationChanged(EventArgs.Empty);
@@ -3114,312 +3720,389 @@ namespace System.Windows.Forms
                        }
                }
 
-               [EditorBrowsable(EditorBrowsableState.Advanced)]
-               protected void UpdateBounds(int x, int y, int width, int height, int clientWidth, int clientHeight) {
-                       UpdateBounds(x, y, width, height);
-
-                       this.client_size.Width=clientWidth;
-                       this.client_size.Height=clientHeight;
-               }
-
                [EditorBrowsable(EditorBrowsableState.Advanced)]
                protected void UpdateStyles() {
                        if (!IsHandleCreated) {
                                return;
                        }
 
-                       if ( !(this is Form) && !(this is Form.FormParentWindow)) {
-                               XplatUI.SetWindowStyle(window.Handle, CreateParams);
-                       } else {
-                               if (this is Form) {
-                                       XplatUI.SetWindowStyle(((Form)this).form_parent_window.window.Handle, ((Form)this).CreateFormParams);
-                               } else {
-                                       XplatUI.SetWindowStyle(((Form.FormParentWindow)this).window.Handle, ((Form.FormParentWindow)this).owner.CreateFormParams);
-                               }
-                       }
+                       XplatUI.SetWindowStyle(window.Handle, CreateParams);
+                       OnStyleChanged(EventArgs.Empty);
                }
 
+               [EditorBrowsable(EditorBrowsableState.Advanced)]
                protected void UpdateZOrder() {
-                       int     children;
-#if not
-                       Control ctl;
-
-                       if (parent == null) {
+                       Control [] controls;
+                       if (!IsHandleCreated) {
                                return;
                        }
 
-                       ctl = parent;
-
-                       children = ctl.child_controls.Count;
-                       for (int i = 1; i < children; i++ ) {
-                               XplatUI.SetZOrder(ctl.child_controls[i].window.Handle, ctl.child_controls[i-1].window.Handle, false, false); 
-                       }
-#else
-                       children = child_controls.Count;
-                       for (int i = 1; i < children; i++ ) {
-                               XplatUI.SetZOrder(child_controls[i].window.Handle, child_controls[i-1].window.Handle, false, false); 
+                       controls = child_controls.GetAllControls ();
+                       for (int i = 1; i < controls.Length; i++ ) {
+                               XplatUI.SetZOrder(controls[i].Handle, controls[i-1].Handle, false, false); 
                        }
-#endif
                }
 
                protected virtual void WndProc(ref Message m) {
 #if debug
-                       Console.WriteLine("Received message {0}", m);
+                       Console.WriteLine("Control {0} received message {1}", window.Handle == IntPtr.Zero ? this.Text : XplatUI.Window(window.Handle), (Msg)m.Msg);
 #endif
                        if ((this.control_style & ControlStyles.EnableNotifyMessage) != 0) {
                                OnNotifyMessage(m);
                        }
 
                        switch((Msg)m.Msg) {
-                       case Msg.WM_WINDOWPOSCHANGED: {
-                               if (Visible) {
-                                       UpdateBounds();
-                                       if (GetStyle(ControlStyles.ResizeRedraw)) {
-                                               Invalidate();
+                               case Msg.WM_DESTROY: {
+                                       OnHandleDestroyed(EventArgs.Empty);
+                                       window.InvalidateHandle();
+
+                                       if (ParentIsRecreating) {
+                                               RecreateHandle();
+                                       } else if (is_recreating) {
+                                               CreateHandle();
                                        }
+                                       return;
+                               }
+
+                               case Msg.WM_WINDOWPOSCHANGED: {
+                                       if (Visible) {
+                                               UpdateBounds();
+                                               if (GetStyle(ControlStyles.ResizeRedraw)) {
+                                                       Invalidate();
+                                               }
+                                       }
+                                       return;
                                }
-                               return;
-                       }
 
-                       case Msg.WM_PAINT: {                            
-                               PaintEventArgs  paint_event;
+                               // Nice description of what should happen when handling WM_PAINT
+                               // can be found here: http://pluralsight.com/wiki/default.aspx/Craig/FlickerFreeControlDrawing.html
+                               // and here http://msdn.microsoft.com/msdnmag/issues/06/03/WindowsFormsPerformance/
+                               case Msg.WM_PAINT: {
+                                       PaintEventArgs  paint_event;
 
-                               paint_event = XplatUI.PaintEventStart(Handle);
-                               OnPaint(paint_event);
-                               XplatUI.PaintEventEnd(Handle);
-                               DefWndProc(ref m);      
-                               return;
-                       }
-                               
-                       case Msg.WM_ERASEBKGND: {
-                               if (GetStyle (ControlStyles.UserPaint)) {
-                                       if (!GetStyle(ControlStyles.AllPaintingInWmPaint)) {
-                                               PaintEventArgs eraseEventArgs = new PaintEventArgs (m.WParam == IntPtr.Zero ? Graphics.FromHwnd (m.HWnd) :
-                                                                Graphics.FromHdc (m.WParam), new Rectangle (new Point (0,0),Size));
-                                               OnPaintBackground (eraseEventArgs);
+                                       paint_event = XplatUI.PaintEventStart(Handle, true);
+
+                                       if (!needs_redraw) {
+                                               // Just blit the previous image
+                                               paint_event.Graphics.DrawImage (ImageBuffer, paint_event.ClipRectangle, paint_event.ClipRectangle, GraphicsUnit.Pixel);
+                                               XplatUI.PaintEventEnd(Handle, true);
+                                               return;
                                        }
-                                       m.Result = (IntPtr)1;
-                               } else {
-                                       m.Result = IntPtr.Zero;
-                                       DefWndProc (ref m);     
-                               }                                       
-                                       
-                               return;
-                       }
 
-                       case Msg.WM_LBUTTONUP: {
-                               HandleClick(mouse_clicks);
-                               OnMouseUp (new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()) | MouseButtons.Left, 
-                                       mouse_clicks, 
-                                       LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
-                                       0));
-                               if (mouse_clicks > 1) {
-                                       mouse_clicks = 1;
+                                       Graphics dc = null;
+                                       if (ThemeEngine.Current.DoubleBufferingSupported)
+                                               if ((control_style & ControlStyles.DoubleBuffer) != 0) {
+                                                       dc = paint_event.SetGraphics (DeviceContext);
+                                               }
+
+                                       if (!GetStyle(ControlStyles.Opaque)) {
+                                               OnPaintBackground(paint_event);
+                                       }
+
+                                       // Button-derived controls choose to ignore their Opaque style, give them a chance to draw their background anyways
+                                       OnPaintBackgroundInternal(paint_event);
+
+                                       OnPaintInternal(paint_event);
+                                       if (!paint_event.Handled) {
+                                               OnPaint(paint_event);
+                                       }
+
+                                       if (ThemeEngine.Current.DoubleBufferingSupported)
+                                               if ((control_style & ControlStyles.DoubleBuffer) != 0) {
+                                                       dc.DrawImage (ImageBuffer, paint_event.ClipRectangle, paint_event.ClipRectangle, GraphicsUnit.Pixel);
+                                                       paint_event.SetGraphics (dc);
+                                                       needs_redraw = false;
+                                               }
+
+                                       XplatUI.PaintEventEnd(Handle, true);
+
+                                       return;
                                }
-                               return;
-                       }
-                               
-                       case Msg.WM_LBUTTONDOWN: {
-                               if (CanSelect && !is_selected) {
-                                       Select(this);
+                                       
+                               case Msg.WM_ERASEBKGND: {
+                                       // The DefWndProc will never have to handle this, we always paint the background in managed code
+                                       // In theory this code would look at ControlStyles.AllPaintingInWmPaint and and call OnPaintBackground
+                                       // here but it just makes things more complicated...
+                                       m.Result = (IntPtr)1;
+                                       return;
+                               }
+
+                               case Msg.WM_LBUTTONUP: {
+                                       MouseEventArgs me;
+
+                                       me = new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()) | MouseButtons.Left, 
+                                               mouse_clicks, 
+                                               LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
+                                               0);
+
+                                       HandleClick(mouse_clicks, me);
+                                       OnMouseUp (me);
+
+                                       if (InternalCapture) {
+                                               InternalCapture = false;
+                                       }
+
+                                       if (mouse_clicks > 1) {
+                                               mouse_clicks = 1;
+                                       }
+                                       return;
                                }
-                               OnMouseDown (new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()), 
-                                       mouse_clicks, LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
-                                       0));
                                        
-                               return;
-                       }
+                               case Msg.WM_LBUTTONDOWN: {
+                                       if (CanSelect && !is_selected) {
+                                               Select(this);
+                                       }
+                                       InternalCapture = true;
+                                       OnMouseDown (new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()), 
+                                               mouse_clicks, LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
+                                               0));
+                                               
+                                       return;
+                               }
 
-                       case Msg.WM_LBUTTONDBLCLK: {
-                               mouse_clicks++;
-                               OnMouseDown (new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()), 
-                                       mouse_clicks, LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
-                                       0));
+                               case Msg.WM_LBUTTONDBLCLK: {
+                                       InternalCapture = true;
+                                       mouse_clicks++;
+                                       OnMouseDown (new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()), 
+                                               mouse_clicks, LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
+                                               0));
 
-                               return;
-                       }
+                                       return;
+                               }
+
+                               case Msg.WM_MBUTTONUP: {
+                                       MouseEventArgs me;
 
-                       case Msg.WM_MBUTTONUP: {
-                               HandleClick(mouse_clicks);
-                               OnMouseUp (new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()) | MouseButtons.Middle, 
-                                       mouse_clicks, 
-                                       LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
-                                       0));
-                               if (mouse_clicks > 1) {
-                                       mouse_clicks = 1;
+                                       me = new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()) | MouseButtons.Middle, 
+                                               mouse_clicks, 
+                                               LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
+                                               0);
+
+                                       HandleClick(mouse_clicks, me);
+                                       OnMouseUp (me);
+                                       if (InternalCapture) {
+                                               InternalCapture = false;
+                                       }
+                                       if (mouse_clicks > 1) {
+                                               mouse_clicks = 1;
+                                       }
+                                       return;
                                }
-                               return;
-                       }
-                               
-                       case Msg.WM_MBUTTONDOWN: {                                      
-                               OnMouseDown (new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()), 
-                                       mouse_clicks, LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
-                                       0));
                                        
-                               return;
-                       }
+                               case Msg.WM_MBUTTONDOWN: {                                      
+                                       InternalCapture = true;
+                                       OnMouseDown (new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()), 
+                                               mouse_clicks, LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
+                                               0));
+                                               
+                                       return;
+                               }
 
-                       case Msg.WM_MBUTTONDBLCLK: {
-                               mouse_clicks++;
-                               OnMouseDown (new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()), 
-                                       mouse_clicks, LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
-                                       0));
-                               return;
-                       }
+                               case Msg.WM_MBUTTONDBLCLK: {
+                                       InternalCapture = true;
+                                       mouse_clicks++;
+                                       OnMouseDown (new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()), 
+                                               mouse_clicks, LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
+                                               0));
+                                       return;
+                               }
+
+                               case Msg.WM_RBUTTONUP: {
+                                       MouseEventArgs  me;
+                                       Point           pt;
+
+                                       pt = new Point(LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()));
+                                       pt = PointToScreen(pt);
+
+                                       XplatUI.SendMessage(m.HWnd, Msg.WM_CONTEXTMENU, m.HWnd, (IntPtr)(pt.X + (pt.Y << 16)));
 
-                       case Msg.WM_RBUTTONUP: {
-                               HandleClick(mouse_clicks);
-                               OnMouseUp (new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()) | MouseButtons.Right, 
-                                       mouse_clicks, 
-                                       LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
-                                       0));
-                               if (mouse_clicks > 1) {
-                                       mouse_clicks = 1;
+                                       me = new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()) | MouseButtons.Right, 
+                                               mouse_clicks, 
+                                               LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
+                                               0);
+
+                                       HandleClick(mouse_clicks, me);
+                                       OnMouseUp (me);
+
+                                       if (InternalCapture) {
+                                               InternalCapture = false;
+                                       }
+
+                                       if (mouse_clicks > 1) {
+                                               mouse_clicks = 1;
+                                       }
+                                       return;
+                               }
+                                       
+                               case Msg.WM_RBUTTONDOWN: {                                      
+                                       InternalCapture = true;
+                                       OnMouseDown (new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()), 
+                                               mouse_clicks, LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
+                                               0));
+                                       return;
                                }
-                               return;
-                       }
-                               
-                       case Msg.WM_RBUTTONDOWN: {                                      
-                               OnMouseDown (new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()), 
-                                       mouse_clicks, LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
-                                       0));
-                               return;
-                       }
 
-                       case Msg.WM_RBUTTONDBLCLK: {
-                               mouse_clicks++;
-                               OnMouseDown (new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()), 
-                                       mouse_clicks, LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
-                                       0));
-                               return;
-                       }
+                               case Msg.WM_RBUTTONDBLCLK: {
+                                       InternalCapture = true;
+                                       mouse_clicks++;
+                                       OnMouseDown (new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()), 
+                                               mouse_clicks, LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
+                                               0));
+                                       return;
+                               }
 
-                       case Msg.WM_MOUSEWHEEL: {                               
+                               case Msg.WM_CONTEXTMENU: {
+                                       if (context_menu != null) {
+                                               Point   pt;
 
-                               OnMouseWheel (new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()), 
-                                       mouse_clicks, LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
-                                       HighOrder(m.WParam.ToInt32())));
-                               return;
-                       }
+                                               pt = new Point(LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()));
+                                               context_menu.Show(this, PointToClient(pt));
+                                               return;
+                                       }
 
-                               
-                       case Msg.WM_MOUSEMOVE: {                                        
-                               OnMouseMove  (new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()), 
-                                       mouse_clicks, 
-                                       LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
-                                       0));
-                               return;
-                       }
+                                       DefWndProc(ref m);
+                                       return;
+                               }
 
-                       case Msg.WM_MOUSE_ENTER: {
-                               if (is_entered) {
+                               case Msg.WM_MOUSEWHEEL: {                               
+
+                                       OnMouseWheel (new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()), 
+                                               mouse_clicks, LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
+                                               HighOrder(m.WParam.ToInt32())));
                                        return;
                                }
-                               is_entered = true;
-                               OnMouseEnter(EventArgs.Empty);
-                               return;
-                       }
 
-                       case Msg.WM_MOUSE_LEAVE: {
-                               is_entered=false;
-                               OnMouseLeave(EventArgs.Empty);
-                               return;
-                       }
+                                       
+                               case Msg.WM_MOUSEMOVE: {                                        
+                                       OnMouseMove  (new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()), 
+                                               mouse_clicks, 
+                                               LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
+                                               0));
+                                       return;
+                               }
 
-                       case Msg.WM_MOUSEHOVER: {
-                               OnMouseHover(EventArgs.Empty);
-                               return;
-                       }
-                       
-                       case Msg.WM_KEYDOWN: {
-                               if (!ProcessKeyMessage(ref m)) {
-                                       DefWndProc (ref m);
+                               case Msg.WM_MOUSE_ENTER: {
+                                       if (is_entered) {
+                                               return;
+                                       }
+                                       is_entered = true;
+                                       OnMouseEnter(EventArgs.Empty);
+                                       return;
                                }
-                               return;
-                       }
 
-                       case Msg.WM_KEYUP: {
-                               if (!ProcessKeyMessage(ref m)) {
+                               case Msg.WM_MOUSE_LEAVE: {
+                                       is_entered=false;
+                                       OnMouseLeave(EventArgs.Empty);
+                                       return;
+                               }
+
+                               case Msg.WM_MOUSEHOVER: {
+                                       OnMouseHover(EventArgs.Empty);
+                                       return;
+                               }
+
+                               case Msg.WM_SYSKEYUP: {
+                                       if (ProcessKeyMessage(ref m)) {
+                                               m.Result = IntPtr.Zero;
+                                               return;
+                                       }
+
+                                       if ((m.WParam.ToInt32() & (int)Keys.KeyCode) == (int)Keys.Menu) {
+                                               Form    form;
+
+                                               form = FindForm();
+                                               if (form != null && form.ActiveMenu != null) {
+                                                       form.ActiveMenu.ProcessCmdKey(ref m, (Keys)m.WParam.ToInt32());
+                                               }
+                                       }
+
                                        DefWndProc (ref m);
+                                       return;
                                }
-                               return;
-                       }               
 
-                       case Msg.WM_CHAR: {
-                               if (!ProcessKeyMessage(ref m)) {
+                               case Msg.WM_SYSKEYDOWN:
+                               case Msg.WM_KEYDOWN:
+                               case Msg.WM_KEYUP:
+                               case Msg.WM_SYSCHAR:
+                               case Msg.WM_CHAR: {
+                                       if (ProcessKeyMessage(ref m)) {
+                                               m.Result = IntPtr.Zero;
+                                               return;
+                                       }
                                        DefWndProc (ref m);
+                                       return;
                                }
-                               return;
-                       }
 
-                       case Msg.WM_HELP: {
-                               Point   mouse_pos;
-                               if (m.LParam != IntPtr.Zero) {
-                                       HELPINFO        hi;
+                               case Msg.WM_HELP: {
+                                       Point   mouse_pos;
+                                       if (m.LParam != IntPtr.Zero) {
+                                               HELPINFO        hi;
 
-                                       hi = new HELPINFO();
+                                               hi = new HELPINFO();
 
-                                       hi = (HELPINFO) Marshal.PtrToStructure (m.LParam, typeof (HELPINFO));
-                                       mouse_pos = new Point(hi.MousePos.x, hi.MousePos.y);
-                               } else {
-                                       mouse_pos = Control.MousePosition;
+                                               hi = (HELPINFO) Marshal.PtrToStructure (m.LParam, typeof (HELPINFO));
+                                               mouse_pos = new Point(hi.MousePos.x, hi.MousePos.y);
+                                       } else {
+                                               mouse_pos = Control.MousePosition;
+                                       }
+                                       OnHelpRequested(new HelpEventArgs(mouse_pos));
+                                       m.Result = (IntPtr)1;
+                                       return;
                                }
-                               OnHelpRequested(new HelpEventArgs(mouse_pos));
-                               m.Result = (IntPtr)1;
-                               return;
-                       }
 
-                       case Msg.WM_KILLFOCUS: {
-                               OnLeave(EventArgs.Empty);
-                               if (CausesValidation) {
-                                       CancelEventArgs e;
-                                       e = new CancelEventArgs(false);
+                               case Msg.WM_KILLFOCUS: {
+                                       OnLeave(EventArgs.Empty);
+                                       if (CausesValidation) {
+                                               CancelEventArgs e;
+                                               e = new CancelEventArgs(false);
 
-                                       OnValidating(e);
+                                               OnValidating(e);
 
-                                       if (e.Cancel) {
-                                               Focus();
-                                               return;
+                                               if (e.Cancel) {
+                                                       Focus();
+                                                       return;
+                                               }
+
+                                               OnValidated(EventArgs.Empty);
                                        }
 
-                                       OnValidated(EventArgs.Empty);
+                                       this.has_focus = false;
+                                       this.is_selected = false;
+                                       OnLostFocus(EventArgs.Empty);
+                                       return;
                                }
 
-                               this.has_focus = false;
-                               this.is_selected = false;
-                               OnLostFocus(EventArgs.Empty);
-                               return;
-                       }
+                               case Msg.WM_SETFOCUS: {
+                                       OnEnter(EventArgs.Empty);
+                                       this.has_focus = true;
+                                       OnGotFocus(EventArgs.Empty);
+                                       return;
+                               }
+                                       
 
-                       case Msg.WM_SETFOCUS: {
-                               OnEnter(EventArgs.Empty);
-                               this.has_focus = true;
-                               OnGotFocus(EventArgs.Empty);
-                               return;
-                       }
-                               
+                               case Msg.WM_SYSCOLORCHANGE: {
+                                       ThemeEngine.Current.ResetDefaults();
+                                       OnSystemColorsChanged(EventArgs.Empty);
+                                       return;
+                               }
+                                       
 
-                       case Msg.WM_SYSCOLORCHANGE: {
-                               ThemeEngine.Current.ResetDefaults();
-                               OnSystemColorsChanged(EventArgs.Empty);
-                               return;
-                       }
-                               
+                               case Msg.WM_SETCURSOR: {
+                                       if ((cursor == null) || ((HitTest)(m.LParam.ToInt32() & 0xffff) != HitTest.HTCLIENT)) {
+                                               DefWndProc(ref m);
+                                               return;
+                                       }
+
+                                       XplatUI.SetCursor(window.Handle, cursor.handle);
+                                       m.Result = (IntPtr)1;
 
-                       case Msg.WM_SETCURSOR: {
-                               if (cursor == null) {
-                                       DefWndProc(ref m);
                                        return;
                                }
 
-                               XplatUI.SetCursor(window.Handle, cursor.handle);
-                               m.Result = (IntPtr)1;
-                               return;
-                       }
-
-                       default:
-                               DefWndProc(ref m);      
-                               return;
+                               default: {
+                                       DefWndProc(ref m);      
+                                       return;
+                               }
                        }
                }
                #endregion      // Public Instance Methods
@@ -3439,7 +4122,10 @@ namespace System.Windows.Forms
 
                [EditorBrowsable(EditorBrowsableState.Advanced)]
                protected virtual void OnBindingContextChanged(EventArgs e) {
-                       if (BindingContextChanged!=null) BindingContextChanged(this, e);
+                       CheckDataBindings ();
+                       if (BindingContextChanged!=null) {
+                               BindingContextChanged(this, e);
+                       }
                        for (int i=0; i<child_controls.Count; i++) child_controls[i].OnParentBindingContextChanged(e);
                }
 
@@ -3567,6 +4253,7 @@ namespace System.Windows.Forms
 
                [EditorBrowsable(EditorBrowsableState.Advanced)]
                protected virtual void OnInvalidated(InvalidateEventArgs e) {
+                       needs_redraw = true;
                        if (Invalidated!=null) Invalidated(this, e);
                }
 
@@ -3599,15 +4286,6 @@ namespace System.Windows.Forms
                protected virtual void OnLocationChanged(EventArgs e) {
                        OnMove(e);
                        if (LocationChanged!=null) LocationChanged(this, e);
-                       if (this is Form.FormParentWindow) {
-                               Form    form;
-
-                               form = ((Form.FormParentWindow)this).owner;
-
-                               if (form.LocationChanged != null) {
-                                       form.LocationChanged(form, e);
-                               }
-                       }
                }
 
                [EditorBrowsable(EditorBrowsableState.Advanced)]
@@ -3665,9 +4343,17 @@ namespace System.Windows.Forms
                        if (Paint!=null) Paint(this, e);
                }
 
+               internal virtual void OnPaintBackgroundInternal(PaintEventArgs e) {
+                       // Override me
+               }
+
+               internal virtual void OnPaintInternal(PaintEventArgs e) {
+                       // Override me
+               }
+
                [EditorBrowsable(EditorBrowsableState.Advanced)]
                protected virtual void OnPaintBackground(PaintEventArgs pevent) {
-                       // Override me!
+                       PaintControlBackground (pevent);
                }
 
                [EditorBrowsable(EditorBrowsableState.Advanced)]
@@ -3736,9 +4422,7 @@ namespace System.Windows.Forms
 
                [EditorBrowsable(EditorBrowsableState.Advanced)]
                protected virtual void OnParentVisibleChanged(EventArgs e) {
-                       if (is_visible!=Parent.is_visible) {
-                               is_visible=false;
-                               Invalidate();
+                       if (is_visible) {
                                OnVisibleChanged(e);
                        }
                }
@@ -3809,30 +4493,22 @@ namespace System.Windows.Forms
 
                [EditorBrowsable(EditorBrowsableState.Advanced)]
                protected virtual void OnVisibleChanged(EventArgs e) {
-                       if (!is_visible) {
-                               if (dc_mem!=null) {
-                                       dc_mem.Dispose ();
-                                       bmp_mem=null;
-                               }
-
-                               if (bmp_mem!=null) {
-                                       bmp_mem.Dispose();
-                                       bmp_mem=null;
-                               }
-                       } else {
+                       if ((parent != null) && !Created && Visible) {
                                if (!is_disposed) {
-                                       if (!this.IsHandleCreated) {
-                                               this.CreateHandle();
-                                       }
+                                       CreateControl();
                                        PerformLayout();
                                }
                        }
+
+                       needs_redraw = true;
                        
                        if (VisibleChanged!=null) VisibleChanged(this, e);
 
                        // We need to tell our kids
                        for (int i=0; i<child_controls.Count; i++) {
-                               child_controls[i].OnParentVisibleChanged(e);
+                               if (child_controls[i].Visible) {
+                                       child_controls[i].OnParentVisibleChanged(e);
+                               }
                        }
                }
                #endregion      // OnXXX methods
@@ -3854,6 +4530,7 @@ namespace System.Windows.Forms
                [Browsable(false)]
                public event ControlEventHandler        ControlRemoved;
 
+               [MWFDescription("Fired when the cursor for the control has been changed"), MWFCategory("PropertyChanged")]
                public event EventHandler               CursorChanged;
                public event EventHandler               DockChanged;
                public event EventHandler               DoubleClick;