2006-05-10 Peter Dennis Bartok <pbartok@novell.com>
[mono.git] / mcs / class / Managed.Windows.Forms / System.Windows.Forms / Control.cs
index 186cbb0c074568ffdfd780a58f693bba54b0185f..a23b86308881afcbfde200ab39205cadbcc11071 100644 (file)
@@ -17,7 +17,7 @@
 // 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-2005 Novell, Inc.
+// Copyright (c) 2004-2006 Novell, Inc.
 //
 // Authors:
 //     Peter Bartok            pbartok@novell.com
@@ -39,6 +39,7 @@ using System.ComponentModel.Design.Serialization;
 using System.Collections;
 using System.Diagnostics;
 using System.Drawing;
+using System.Drawing.Drawing2D;
 using System.Reflection;
 using System.Runtime.InteropServices;
 using System.Security;
@@ -63,7 +64,7 @@ namespace System.Windows.Forms
                internal string                 name;                   // for object naming
 
                // State
-               private bool                    create_handled;         // true if OnCreateControl has been sent
+               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?
@@ -119,6 +120,12 @@ namespace System.Windows.Forms
 
                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
 
                #region Private Classes
@@ -141,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) {
@@ -154,10 +164,6 @@ namespace System.Windows.Forms
                #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;
@@ -256,7 +262,7 @@ namespace System.Windows.Forms
                public class ControlCollection : IList, ICollection, ICloneable, IEnumerable {
                        #region ControlCollection Local Variables
                        private ArrayList       list;
-                       private ArrayList       impl_list;
+                       internal ArrayList      impl_list;
                        private Control []      all_controls;
                        internal Control        owner;
                        #endregion      // ControlCollection Local Variables
@@ -275,7 +281,7 @@ namespace System.Windows.Forms
                                }
                        }
 
-                       public virtual bool IsReadOnly {
+                       public bool IsReadOnly {
                                get {
                                        return list.IsReadOnly;
                                }
@@ -297,8 +303,10 @@ namespace System.Windows.Forms
                                if (value == null)
                                        return;
                                
-                                if (Contains (value))
+                                if (Contains (value)) {
+                                       owner.PerformLayout();
                                         return;
+                               }
 
                                if (value.tab_index == -1) {
                                        int     end;
@@ -316,10 +324,19 @@ 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));
                        }
                        
@@ -335,8 +352,12 @@ namespace System.Windows.Forms
                                        impl_list = new ArrayList ();
                                all_controls = null;
                                impl_list.Add (control);
-                               control.Parent = owner;
+
+                               control.ChangeParent (owner);
+                               control.InitLayout ();
                                owner.UpdateZOrder ();
+                               owner.PerformLayout (control, "Parent");
+                               owner.OnControlAdded (new ControlEventArgs (control));
                        }
 
                        public virtual void AddRange (Control[] controls)
@@ -371,13 +392,12 @@ namespace System.Windows.Forms
 
                        public virtual void Clear ()
                        {
-                               owner.SuspendLayout();
                                all_controls = null;
-                               for (int i = 0; i < list.Count; i++) {
-                                       owner.OnControlRemoved(new ControlEventArgs((Control)list[i]));
+
+                               // MS sends remove events in reverse order
+                               while (list.Count > 0) {
+                                       RemoveAt(list.Count - 1);
                                }
-                               list.Clear();
-                               owner.ResumeLayout();
                        }
 
                        internal virtual void ClearImplicit ()
@@ -422,7 +442,7 @@ namespace System.Windows.Forms
                                return Contains (value) || ImplicitContains (value);
                        }
 
-                       public virtual void CopyTo (Array array, int index)
+                       public void CopyTo (Array array, int index)
                        {
                                list.CopyTo(array, index);
                        }
@@ -467,9 +487,11 @@ namespace System.Windows.Forms
 
                                if (impl_list == null)
                                        return (Control []) list.ToArray (typeof (Control));
+                               
                                Control [] res = new Control [list.Count + impl_list.Count];
-                               list.CopyTo (res);
-                               impl_list.CopyTo (res, list.Count);
+                               impl_list.CopyTo (res);
+                               list.CopyTo (res, impl_list.Count);
+
                                return res;
                        }
 
@@ -484,9 +506,12 @@ 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.parent = null;
+
+                               value.ChangeParent(null);
+
                                owner.UpdateZOrder();
                        }
 
@@ -494,9 +519,11 @@ namespace System.Windows.Forms
                        {
                                if (impl_list != null) {
                                        all_controls = null;
+                                       owner.PerformLayout (control, "Parent");
+                                       owner.OnControlRemoved (new ControlEventArgs (control));
                                        impl_list.Remove (control);
                                }
-                               control.Parent = null;
+                               control.ChangeParent (null);
                                owner.UpdateZOrder ();
                        }
 
@@ -519,14 +546,13 @@ namespace System.Windows.Forms
                                        return;
                                }
 
-                               RemoveAt(old_index);
+                               list.RemoveAt(old_index);
 
                                if (newIndex>list.Count) {
                                        list.Add(child);
                                } else {
                                        list.Insert(newIndex, child);
                                }
-                               child.parent = owner;
                                owner.UpdateZOrder();
                        }
                        #endregion // ControlCollection Private Instance Methods
@@ -555,12 +581,6 @@ namespace System.Windows.Forms
                                }
                        }
 
-                       bool IList.IsReadOnly {
-                               get {
-                                       return list.IsReadOnly;
-                               }
-                       }
-
                        bool ICollection.IsSynchronized {
                                get {
                                        return list.IsSynchronized;
@@ -619,12 +639,6 @@ namespace System.Windows.Forms
                                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?
@@ -636,11 +650,10 @@ namespace System.Windows.Forms
                
                #region Public Constructors
                public Control() {                      
-                       creator_thread = Thread.CurrentThread;
 
                        anchor_style = AnchorStyles.Top | AnchorStyles.Left;
 
-                       create_handled = false;
+                       is_created = false;
                        is_visible = true;
                        is_captured = false;
                        is_disposed = false;
@@ -662,6 +675,11 @@ namespace System.Windows.Forms
                        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.UserPaint | ControlStyles.AllPaintingInWmPaint | 
                                        ControlStyles.Selectable | ControlStyles.StandardClick | 
                                        ControlStyles.StandardDoubleClick;
@@ -675,7 +693,7 @@ namespace System.Windows.Forms
                        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, CreateParams.ExStyle, null, 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;
@@ -713,7 +731,6 @@ namespace System.Windows.Forms
                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;
@@ -725,12 +742,16 @@ namespace System.Windows.Forms
                        }
 
                        if (this.InvokeRequired) {
-                               this.Invoke(new MethodInvoker(DestroyHandle));
-                               this.Invoke(new RemoveDelegate(controls.Remove), new object[] {this});
+                               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
 
@@ -757,25 +778,28 @@ namespace System.Windows.Forms
                #endregion      // Internal Properties
 
                #region Private & Internal Methods
-               internal IAsyncResult BeginInvokeInternal (Delegate method, object [] args) {
+               internal IAsyncResult BeginInvokeInternal (Delegate method, object [] args, bool disposing) {
                        AsyncMethodResult       result;
                        AsyncMethodData         data;
-                       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);
+                       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 ()) {
@@ -804,6 +828,29 @@ namespace System.Windows.Forms
                        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) {
@@ -913,6 +960,26 @@ namespace System.Windows.Forms
                // 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);
+                               }
+                       }
+
                        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;
@@ -923,7 +990,7 @@ namespace System.Windows.Forms
 
                void DrawBackgroundImage (Graphics g)
                {
-                       using (TextureBrush b = new TextureBrush (background_image)) {
+                       using (TextureBrush b = new TextureBrush (background_image, WrapMode.Tile)) {
                                g.FillRectangle (b, ClientRectangle);
                        }
                }
@@ -1108,16 +1175,18 @@ 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
                                }
                        }
                }
@@ -1132,6 +1201,79 @@ namespace System.Windows.Forms
                                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
@@ -1175,10 +1317,12 @@ namespace System.Windows.Forms
                [MonoTODO]
                public static bool CheckForIllegalCrossThreadCalls 
                {
-                       set {
-                       }
                        get {
-                               return false;
+                               return verify_thread_handle;
+                       }
+
+                       set {
+                               verify_thread_handle = value;
                        }
                }
 #endif
@@ -1212,6 +1356,7 @@ namespace System.Windows.Forms
 
                [Localizable(true)]
                [DefaultValue(null)]
+               [MWFCategory("Accessibility")]
                public string AccessibleDescription {
                        get {
                                return AccessibilityObject.description;
@@ -1224,6 +1369,7 @@ namespace System.Windows.Forms
 
                [Localizable(true)]
                [DefaultValue(null)]
+               [MWFCategory("Accessibility")]
                public string AccessibleName {
                        get {
                                return AccessibilityObject.Name;
@@ -1247,6 +1393,7 @@ namespace System.Windows.Forms
                }
 
                [DefaultValue(false)]
+               [MWFCategory("Behavior")]
                public virtual bool AllowDrop {
                        get {
                                return allow_drop;
@@ -1256,14 +1403,17 @@ namespace System.Windows.Forms
                                if (allow_drop == value)
                                        return;
                                allow_drop = value;
-                               UpdateStyles();
-                               XplatUI.SetAllowDrop (Handle, 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;
@@ -1278,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;
                                }
@@ -1291,6 +1460,10 @@ namespace System.Windows.Forms
                        }
 
                        set {
+                               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);
@@ -1300,6 +1473,7 @@ namespace System.Windows.Forms
 
                [Localizable(true)]
                [DefaultValue(null)]
+               [MWFCategory("Appearance")]
                public virtual Image BackgroundImage {
                        get {
                                return background_image;
@@ -1360,7 +1534,7 @@ namespace System.Windows.Forms
                [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
                public bool CanFocus {
                        get {
-                               if (Visible && is_enabled && GetStyle(ControlStyles.Selectable)) {
+                               if (IsHandleCreated && Visible && Enabled) {
                                        return true;
                                }
                                return false;
@@ -1374,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;
@@ -1390,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)]
@@ -1412,6 +1596,7 @@ namespace System.Windows.Forms
                }
 
                [DefaultValue(true)]
+               [MWFCategory("Focus")]
                public bool CausesValidation {
                        get {
                                return this.causes_validation;
@@ -1484,6 +1669,7 @@ namespace System.Windows.Forms
                }
 
                [DefaultValue(null)]
+               [MWFCategory("Behavior")]
                public virtual ContextMenu ContextMenu {
                        get {
                                return context_menu;
@@ -1510,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) {
@@ -1537,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);
+                                                                       }
                                                                }
                                                        }
                                                }
@@ -1561,6 +1748,7 @@ namespace System.Windows.Forms
                [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
                [ParenthesizePropertyName(true)]
                [RefreshProperties(RefreshProperties.All)]
+               [MWFCategory("Data")]
                public ControlBindingsCollection DataBindings {
                        get {
                                if (data_bindings == null)
@@ -1590,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;
@@ -1612,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 {
@@ -1622,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);                             
@@ -1640,6 +1847,7 @@ namespace System.Windows.Forms
                [DispId(-512)]
                [AmbientValue(null)]
                [Localizable(true)]
+               [MWFCategory("Appearance")]
                public virtual Font Font {
                        get {
                                if (font != null) {
@@ -1653,6 +1861,7 @@ namespace System.Windows.Forms
                                return DefaultFont;
                        }
 
+                       [param:MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(Font))]
                        set {
                                if (font != null && font.Equals (value)) {
                                        return;
@@ -1665,6 +1874,7 @@ namespace System.Windows.Forms
                }
 
                [DispId(-513)]
+               [MWFCategory("Appearance")]
                public virtual Color ForeColor {
                        get {
                                if (foreground_color.IsEmpty) {
@@ -1690,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();
                                }
@@ -1724,6 +1941,7 @@ namespace System.Windows.Forms
 
                [AmbientValue(ImeMode.Inherit)]
                [Localizable(true)]
+               [MWFCategory("Behavior")]
                public ImeMode ImeMode {
                        get {
                                 if (ime_mode == DefaultImeMode) {
@@ -1749,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;
@@ -1783,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;
                                }
 
@@ -1805,6 +2023,7 @@ namespace System.Windows.Forms
                }
 
                [Localizable(true)]
+               [MWFCategory("Layout")]
                public Point Location {
                        get {
                                return new Point(bounds.X, bounds.Y);
@@ -1818,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)]
@@ -1844,19 +2076,7 @@ namespace System.Windows.Forms
                                                return;
                                        }
 
-                                       parent=value;
-
-                                       if (!parent.Controls.AllContains (this)) {
-                                                Console.WriteLine ("Adding child:  " + this);
-                                               parent.Controls.Add(this);
-                                       }
-
-                                       if (IsHandleCreated) {
-                                               XplatUI.SetParent(Handle, value.Handle);
-                                       }
-
-                                       OnParentChanged(EventArgs.Empty);
-                                       InitLayout();
+                                       value.Controls.Add(this);
                                }
                        }
                }
@@ -1933,6 +2153,7 @@ namespace System.Windows.Forms
 
                [AmbientValue(RightToLeft.Inherit)]
                [Localizable(true)]
+               [MWFCategory("Appearance")]
                public virtual RightToLeft RightToLeft {
                        get {
                                if (right_to_left == RightToLeft.Inherit) {
@@ -1960,10 +2181,19 @@ 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 {
                                return new Size(Width, Height);
@@ -1976,6 +2206,7 @@ namespace System.Windows.Forms
 
                [Localizable(true)]
                [MergableProperty(false)]
+               [MWFCategory("Behavior")]
                public int TabIndex {
                        get {
                                if (tab_index != -1) {
@@ -1994,6 +2225,7 @@ namespace System.Windows.Forms
 
                [DispId(-516)]
                [DefaultValue(true)]
+               [MWFCategory("Behavior")]
                public bool TabStop {
                        get {
                                return tab_stop;
@@ -2011,6 +2243,7 @@ namespace System.Windows.Forms
                [Bindable(true)]
                [TypeConverter(typeof(StringConverter))]
                [DefaultValue(null)]
+               [MWFCategory("Data")]
                public object Tag {
                        get {
                                return control_tag;
@@ -2024,6 +2257,7 @@ 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
@@ -2074,6 +2308,7 @@ namespace System.Windows.Forms
                }
 
                [Localizable(true)]
+               [MWFCategory("Behavior")]
                public bool Visible {
                        get {
                                if (!is_visible) {
@@ -2164,10 +2399,10 @@ namespace System.Windows.Forms
                                create_params.Param = 0;
 
                                if (allow_drop) {
-                                       create_params.ExStyle |= (int)WindowStyles.WS_EX_ACCEPTFILES;
+                                       create_params.ExStyle |= (int)WindowExStyles.WS_EX_ACCEPTFILES;
                                }
 
-                               if (parent!=null) {
+                               if ((parent!=null) && (parent.IsHandleCreated)) {
                                        create_params.Parent = parent.Handle;
                                }
 
@@ -2177,12 +2412,16 @@ 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) WindowStyles.WS_EX_CLIENTEDGE;
+                                       create_params.ExStyle |= (int) WindowExStyles.WS_EX_CLIENTEDGE;
                                        break;
                                }
 
@@ -2198,7 +2437,7 @@ namespace System.Windows.Forms
 
                protected virtual Size DefaultSize {
                        get {
-                               return new Size(100, 23);
+                               return new Size(0, 0);
                        }
                }
 
@@ -2265,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()) {
@@ -2273,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) {
@@ -2312,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() {
@@ -2325,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();
                        }
@@ -2345,25 +2601,35 @@ namespace System.Windows.Forms
                }
 
                public void CreateControl() {
+                       if (is_created) {
+                               return;
+                       }
 
                        if (!IsHandleCreated) {
                                CreateHandle();
                        }
 
-                       if (!create_handled) {
-                               create_handled = true;
-                               OnCreateControl();
+                       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();
                }
 
                public Graphics CreateGraphics() {
                        if (!IsHandleCreated) {
-                               this.CreateControl();
+                               this.CreateHandle();
                        }
                        return Graphics.FromHwnd(this.window.Handle);
                }
@@ -2392,11 +2658,10 @@ namespace System.Windows.Forms
                }
 
                public bool Focus() {
-                       if (IsHandleCreated && !has_focus) {
-                               has_focus = true;
+                       if (CanFocus && IsHandleCreated && !has_focus) {
                                XplatUI.SetFocus(window.Handle);
                        }
-                       return true;
+                       return has_focus;
                }
 
                public Control GetChildAtPoint(Point pt) {
@@ -2480,18 +2745,18 @@ 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) {
@@ -2503,6 +2768,19 @@ namespace System.Windows.Forms
                        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);
@@ -2528,12 +2806,17 @@ namespace System.Windows.Forms
                                AnchorStyles    anchor;
                                Rectangle       space;
 
-                               space=this.DisplayRectangle;
+                               space= DisplayRectangle;
 
                                // Deal with docking; go through in reverse, MS docs say that lowest Z-order is closest to edge
                                Control [] controls = child_controls.GetAllControls ();
                                for (int i = controls.Length - 1; i >= 0; i--) {
                                        child = controls [i];
+
+                                       if (!child.Visible) {
+                                               continue;
+                                       }
+
                                        switch (child.Dock) {
                                                case DockStyle.None: {
                                                        // Do nothing
@@ -2571,14 +2854,14 @@ namespace System.Windows.Forms
                                for (int i = controls.Length - 1; i >= 0; i--) {
                                        child=controls[i];
 
-                                       if (child.Dock == DockStyle.Fill) {
+                                       if (child.Visible && (child.Dock == DockStyle.Fill)) {
                                                child.SetBounds(space.Left, space.Top, space.Width, space.Height);
                                                space.Width=0;
                                                space.Height=0;
                                        }
                                }
 
-                               space=this.DisplayRectangle;
+                               space=DisplayRectangle;
 
                                for (int i=0; i < controls.Length; i++) {
                                        int left;
@@ -2587,6 +2870,12 @@ namespace System.Windows.Forms
                                        int 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;
@@ -2594,37 +2883,32 @@ namespace System.Windows.Forms
                                        width = child.Width;
                                        height = child.Height;
 
-                                       // If the control is docked we don't need to do anything
-                                       if (child.Dock != DockStyle.None) {
-                                               continue;
-                                       }
-
                                        if ((anchor & AnchorStyles.Left) !=0 ) {
                                                if ((anchor & AnchorStyles.Right) != 0) {
-                                                       width = client_size.Width - child.dist_right - left;
+                                                       width = space.Width - child.dist_right - left;
                                                } else {
                                                        ; // Left anchored only, nothing to be done
                                                }
                                        } else if ((anchor & AnchorStyles.Right) != 0) {
-                                               left = client_size.Width - child.dist_right - width;
+                                               left = space.Width - child.dist_right - width;
                                        } else {
                                                // 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 + (client_size.Width - (child.dist_left + width + child.dist_right)) / 2;
+                                               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 = client_size.Height - child.dist_bottom - top;
+                                                       height = space.Height - child.dist_bottom - top;
                                                } else {
                                                        ; // Top anchored only, nothing to be done
                                                }
                                        } else if ((anchor & AnchorStyles.Bottom) != 0) {
-                                               top = client_size.Height - child.dist_bottom - height;
+                                               top = space.Height - child.dist_bottom - height;
                                        } else {
                                                // top += diff_height/2 will introduce rounding errors (diff_height removed from after r51780)
                                                // This calculates from scratch every time:
-                                               top = child.dist_top + (client_size.Height - (child.dist_top + height + child.dist_bottom)) / 2;
+                                               top = child.dist_top + (space.Height - (child.dist_top + height + child.dist_bottom)) / 2;
                                        }
                                        
                                        // Sanity
@@ -2684,11 +2968,11 @@ namespace System.Windows.Forms
                                return true;
                        } else if (msg.Msg == (int)Msg.WM_CHAR) {
                                if (IsInputChar((char)msg.WParam)) {
-                                       return true;
+                                       return false;
                                }
                        } else if (msg.Msg == (int)Msg.WM_SYSCHAR) {
                                if (IsInputChar((char)msg.WParam)) {
-                                       return true;
+                                       return false;
                                }
                                return ProcessDialogChar((char)msg.WParam);
                        }
@@ -2705,7 +2989,6 @@ namespace System.Windows.Forms
 
                public virtual void Refresh() {                 
                        if (IsHandleCreated == true) {
-
                                Invalidate();
                                XplatUI.UpdateWindow(window.Handle);
 
@@ -2723,14 +3006,13 @@ namespace System.Windows.Forms
                }
 
                [EditorBrowsable(EditorBrowsableState.Never)]
-               [MonoTODO]
                public void ResetBindings() {
-                       // Do something
+                       data_bindings.Clear();
                }
 
                [EditorBrowsable(EditorBrowsableState.Never)]
                public virtual void ResetCursor() {
-                       cursor = null;
+                       Cursor = null;
                }
 
                [EditorBrowsable(EditorBrowsableState.Never)]
@@ -2762,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();
+                               }
                        }
                }
 
@@ -2815,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();
                        }
@@ -2830,7 +3120,7 @@ namespace System.Windows.Forms
                }
 
                public void Show() {
-                       if (!IsHandleCreated) {
+                       if (!is_created) {
                                this.CreateControl();
                        }
 
@@ -2872,28 +3162,48 @@ namespace System.Windows.Forms
                                throw new ObjectDisposedException(Name);
                        }
 
-                       if (IsHandleCreated) {
+                       if (IsHandleCreated && !is_recreating) {
                                return;
                        }
 
                        window.CreateHandle(CreateParams);
 
-                       if (window.Handle!=IntPtr.Zero) {
+                       if (window.Handle != IntPtr.Zero) {
                                if (!controls.Contains(window.Handle)) {
                                        controls.Add(this);
                                }
 
                                creator_thread = Thread.CurrentThread;
 
+                               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);
                        }
 
-                       // Find out where the window manager placed us
-                       UpdateStyles();
-                       if ((CreateParams.Style & (int)WindowStyles.WS_CHILD) != 0) {
-                               XplatUI.SetBorderStyle(window.Handle, (FormBorderStyle)border_style);
-                       }
-                       UpdateBounds();
                }
 
                [EditorBrowsable(EditorBrowsableState.Advanced)]
@@ -2904,18 +3214,9 @@ namespace System.Windows.Forms
                [EditorBrowsable(EditorBrowsableState.Advanced)]
                protected virtual void DestroyHandle() {
                        if (IsHandleCreated) {
-                               // Destroy our children before we destroy ourselves, to prevent them from
-                               // being implictly (without us knowing) destroyed
-                               Control [] controls = child_controls.GetAllControls ();
-                               for (int i=0; i < controls.Length; i++) {
-                                       controls[i].DestroyHandle();
-                               }
-
-
                                if (window != null) {
                                        window.DestroyHandle();
                                }
-                               OnHandleDestroyed(EventArgs.Empty);
                        }
                }
 
@@ -2929,12 +3230,7 @@ namespace System.Windows.Forms
 
                [EditorBrowsable(EditorBrowsableState.Advanced)]
                protected virtual void InitLayout() {
-                       dist_left = bounds.X;
-                       dist_top = bounds.Y;
-                       if (parent != null) {
-                               dist_right = parent.ClientSize.Width - bounds.X - bounds.Width;
-                               dist_bottom = parent.ClientSize.Height - bounds.Y - bounds.Height;
-                       }
+                       UpdateDistances();
                }
 
                [EditorBrowsable(EditorBrowsableState.Advanced)]
@@ -2961,11 +3257,7 @@ namespace System.Windows.Forms
                }
 
                protected virtual bool IsInputChar (char charCode) {
-                       if (parent != null) {
-                               return parent.IsInputChar(charCode);
-                       }
-
-                       return false;
+                       return true;
                }
 
                protected virtual bool IsInputKey (Keys keyData) {
@@ -3049,7 +3341,7 @@ namespace System.Windows.Forms
                                }
                        }
 
-                       return false;
+                       return ProcessKeyEventArgs(ref msg);
                }
 
                protected virtual bool ProcessKeyPreview(ref Message msg) {
@@ -3087,21 +3379,17 @@ namespace System.Windows.Forms
 
                [EditorBrowsable(EditorBrowsableState.Advanced)]
                protected void RecreateHandle() {
-                       IEnumerator child = child_controls.GetAllEnumerator();
-
                        is_recreating=true;
 
                        if (IsHandleCreated) {
                                DestroyHandle();
-                               CreateHandle();
-
-                               // FIXME ZOrder?
-
-                               while (child.MoveNext()) {
-                                       ((Control)child.Current).RecreateHandle();
-                               }
+                               // WM_DESTROY will CreateHandle for us
                        } else {
-                               CreateControl();
+                               if (!is_created) {
+                                       CreateControl();
+                               } else {
+                                       CreateHandle();
+                               }
                        }
 
                        is_recreating = false;
@@ -3202,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);
@@ -3212,8 +3499,7 @@ 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 */
                        Control [] controls = child_controls.GetAllControls ();
@@ -3286,11 +3572,7 @@ namespace System.Windows.Forms
 
                        UpdateBounds(x, y, width, height);
 
-                       // 
-                       Control [] controls = child_controls.GetAllControls ();
-                       for (int i = controls.Length - 1; i >= 0; i--) {
-                               controls[i].InitLayout();
-                       }
+                       UpdateDistances();
                }
 
                [EditorBrowsable(EditorBrowsableState.Advanced)]
@@ -3303,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, cp.ExStyle, null, out WindowRect)==false) {
+                       if (XplatUI.CalculateWindowRect(ref ClientRect, cp.Style, cp.ExStyle, null, out WindowRect)==false) {
                                return;
                        }
 
@@ -3317,7 +3599,6 @@ namespace System.Windows.Forms
                        } else {
                                control_style &= ~flag;
                        }
-                       OnStyleChanged(EventArgs.Empty);
                }
 
                protected void SetTopLevel(bool value) {
@@ -3341,6 +3622,10 @@ namespace System.Windows.Forms
 
                protected virtual void SetVisibleCore(bool value) {
                        if (value!=is_visible) {
+                               if (value && !is_created) {
+                                       CreateControl();
+                               }
+
                                is_visible=value;
 
                                if (IsHandleCreated) {
@@ -3354,21 +3639,6 @@ namespace System.Windows.Forms
 
                                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;
-                                       }
-                               } else {
-                                       this.CreateBuffers(bounds.Width, bounds.Height);
-                                       CreateControl();
-                               }
-
                                if (value == false && parent != null) {
                                        Control container;
 
@@ -3407,13 +3677,23 @@ namespace System.Windows.Forms
 
                [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;
@@ -3428,9 +3708,8 @@ namespace System.Windows.Forms
                        bounds.Width=width;
                        bounds.Height=height;
 
-                       // Update client rectangle as well
-                       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);
@@ -3441,14 +3720,6 @@ 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) {
@@ -3456,25 +3727,12 @@ namespace System.Windows.Forms
                        }
 
                        XplatUI.SetWindowStyle(window.Handle, CreateParams);
+                       OnStyleChanged(EventArgs.Empty);
                }
 
                [EditorBrowsable(EditorBrowsableState.Advanced)]
                protected void UpdateZOrder() {
                        Control [] controls;
-#if not
-                       Control ctl;
-
-                       if (parent == null) {
-                               return;
-                       }
-
-                       ctl = parent;
-
-                       controls = ctl.child_controls.GetAllControls ();
-                       for (int i = 1; i < controls.Length; i++ ) {
-                               XplatUI.SetZOrder(controls[i].window.Handle, controls[i-1].window.Handle, false, false); 
-                       }
-#else
                        if (!IsHandleCreated) {
                                return;
                        }
@@ -3483,18 +3741,29 @@ namespace System.Windows.Forms
                        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("Control received message {0}", (Msg)m.Msg);
+                       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_DESTROY: {
+                                       OnHandleDestroyed(EventArgs.Empty);
+                                       window.InvalidateHandle();
+
+                                       if (ParentIsRecreating) {
+                                               RecreateHandle();
+                                       } else if (is_recreating) {
+                                               CreateHandle();
+                                       }
+                                       return;
+                               }
+
                                case Msg.WM_WINDOWPOSCHANGED: {
                                        if (Visible) {
                                                UpdateBounds();
@@ -3505,7 +3774,10 @@ namespace System.Windows.Forms
                                        return;
                                }
 
-                               case Msg.WM_PAINT: {                            
+                               // 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, true);
@@ -3518,21 +3790,30 @@ namespace System.Windows.Forms
                                        }
 
                                        Graphics dc = null;
-                                       if ((control_style & ControlStyles.DoubleBuffer) != 0) {
-                                               dc = paint_event.SetGraphics (DeviceContext);
+                                       if (ThemeEngine.Current.DoubleBufferingSupported)
+                                               if ((control_style & ControlStyles.DoubleBuffer) != 0) {
+                                                       dc = paint_event.SetGraphics (DeviceContext);
+                                               }
+
+                                       if (!GetStyle(ControlStyles.Opaque)) {
+                                               OnPaintBackground(paint_event);
                                        }
 
-                                       OnPaintBackground(paint_event);
-                                       // Leave out for now, our controls can do Paint += ... as well
-                                       //OnPaintInternal(paint_event);
-                                       OnPaint(paint_event);
+                                       // Button-derived controls choose to ignore their Opaque style, give them a chance to draw their background anyways
+                                       OnPaintBackgroundInternal(paint_event);
 
-                                       if ((control_style & ControlStyles.DoubleBuffer) != 0) {
-                                               dc.DrawImage (ImageBuffer, paint_event.ClipRectangle, paint_event.ClipRectangle, GraphicsUnit.Pixel);
-                                               paint_event.SetGraphics (dc);
-                                               needs_redraw = false;
+                                       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;
@@ -3540,16 +3821,27 @@ namespace System.Windows.Forms
                                        
                                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: {
-                                       OnMouseUp (new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()) | MouseButtons.Left, 
+                                       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);
+                                               0);
+
+                                       HandleClick(mouse_clicks, me);
+                                       OnMouseUp (me);
+
+                                       if (InternalCapture) {
+                                               InternalCapture = false;
+                                       }
+
                                        if (mouse_clicks > 1) {
                                                mouse_clicks = 1;
                                        }
@@ -3560,6 +3852,7 @@ namespace System.Windows.Forms
                                        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));
@@ -3568,6 +3861,7 @@ namespace System.Windows.Forms
                                }
 
                                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 ()), 
@@ -3577,11 +3871,18 @@ namespace System.Windows.Forms
                                }
 
                                case Msg.WM_MBUTTONUP: {
-                                       HandleClick(mouse_clicks);
-                                       OnMouseUp (new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()) | MouseButtons.Middle, 
+                                       MouseEventArgs me;
+
+                                       me = new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()) | MouseButtons.Middle, 
                                                mouse_clicks, 
                                                LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
-                                               0));
+                                               0);
+
+                                       HandleClick(mouse_clicks, me);
+                                       OnMouseUp (me);
+                                       if (InternalCapture) {
+                                               InternalCapture = false;
+                                       }
                                        if (mouse_clicks > 1) {
                                                mouse_clicks = 1;
                                        }
@@ -3589,6 +3890,7 @@ namespace System.Windows.Forms
                                }
                                        
                                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));
@@ -3597,6 +3899,7 @@ namespace System.Windows.Forms
                                }
 
                                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 ()), 
@@ -3605,15 +3908,26 @@ namespace System.Windows.Forms
                                }
 
                                case Msg.WM_RBUTTONUP: {
-                                       if (context_menu != null) {
-                                               context_menu.Show(this, new Point(LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ())));
-                                       }
+                                       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)));
 
-                                       HandleClick(mouse_clicks);
-                                       OnMouseUp (new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()) | MouseButtons.Right, 
+                                       me = new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()) | MouseButtons.Right, 
                                                mouse_clicks, 
                                                LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()), 
-                                               0));
+                                               0);
+
+                                       HandleClick(mouse_clicks, me);
+                                       OnMouseUp (me);
+
+                                       if (InternalCapture) {
+                                               InternalCapture = false;
+                                       }
+
                                        if (mouse_clicks > 1) {
                                                mouse_clicks = 1;
                                        }
@@ -3621,6 +3935,7 @@ namespace System.Windows.Forms
                                }
                                        
                                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));
@@ -3628,6 +3943,7 @@ namespace System.Windows.Forms
                                }
 
                                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 ()), 
@@ -3635,6 +3951,19 @@ namespace System.Windows.Forms
                                        return;
                                }
 
+                               case Msg.WM_CONTEXTMENU: {
+                                       if (context_menu != null) {
+                                               Point   pt;
+
+                                               pt = new Point(LowOrder ((int) m.LParam.ToInt32 ()), HighOrder ((int) m.LParam.ToInt32 ()));
+                                               context_menu.Show(this, PointToClient(pt));
+                                               return;
+                                       }
+
+                                       DefWndProc(ref m);
+                                       return;
+                               }
+
                                case Msg.WM_MOUSEWHEEL: {                               
 
                                        OnMouseWheel (new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()), 
@@ -3672,24 +4001,34 @@ namespace System.Windows.Forms
                                        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;
+                               }
+
                                case Msg.WM_SYSKEYDOWN:
                                case Msg.WM_KEYDOWN:
-                               case Msg.WM_SYSKEYUP:
                                case Msg.WM_KEYUP:
                                case Msg.WM_SYSCHAR:
                                case Msg.WM_CHAR: {
-                                       if (PreProcessMessage(ref m)) {
-                                               return;
-                                       }
-
                                        if (ProcessKeyMessage(ref m)) {
+                                               m.Result = IntPtr.Zero;
                                                return;
                                        }
-
-                                       if (ProcessKeyEventArgs(ref m)) {
-                                               return;
-                                       }
-
                                        DefWndProc (ref m);
                                        return;
                                }
@@ -3749,7 +4088,7 @@ namespace System.Windows.Forms
                                        
 
                                case Msg.WM_SETCURSOR: {
-                                       if (cursor == null) {
+                                       if ((cursor == null) || ((HitTest)(m.LParam.ToInt32() & 0xffff) != HitTest.HTCLIENT)) {
                                                DefWndProc(ref m);
                                                return;
                                        }
@@ -4004,6 +4343,10 @@ 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
                }
@@ -4150,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 ();
-                                       dc_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.CreateControl();
-                                       }
+                                       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