2007-01-07 Jonathan Pobst <monkey@jpobst.com>
[mono.git] / mcs / class / Managed.Windows.Forms / System.Windows.Forms / Control.cs
index 63940bed07d698c35554a15b256105ae3a743dec..b32e216b53dda6b9816a5436080b0f2d4f09b358 100644 (file)
@@ -30,8 +30,6 @@
 //     John Sohn               jsohn@columbus.rr.com
 //
 
-// COMPLETE 
-
 #undef DebugRecreate
 #undef DebugFocus
 
@@ -93,7 +91,6 @@ namespace System.Windows.Forms
                Rectangle               client_rect; // rectangle with the client area (window excluding decorations)
                ControlStyles           control_style; // rather win32-specific, style bits for control
                ImeMode                 ime_mode;
-               bool                    layout_pending; // true if our parent needs to re-layout us
                object                  control_tag; // object that contains data about our control
                internal int                    mouse_clicks;           // Counter for mouse clicks
                Cursor                  cursor; // Cursor for the window
@@ -109,11 +106,17 @@ namespace System.Windows.Forms
                internal                BorderStyle             border_style;           // Border style of control
 
                // Layout
+               internal enum LayoutType {
+                       Anchor,
+                       Dock
+               }
                Layout.LayoutEngine layout_engine;
-               int                     layout_suspended;
-               internal AnchorStyles   anchor_style;           // anchoring requirements for our control
-               internal DockStyle              dock_style;             // docking requirements for our control (supercedes anchoring)
-               
+               int layout_suspended;
+               bool layout_pending; // true if our parent needs to re-layout us
+               internal AnchorStyles anchor_style; // anchoring requirements for our control
+               internal DockStyle dock_style; // docking requirements for our control
+               LayoutType layout_type;
+
                // Please leave the next 2 as internal until DefaultLayout (2.0) is rewritten
                internal int                    dist_right; // distance to the right border of the parent
                internal int                    dist_bottom; // distance to the bottom border of the parent
@@ -127,10 +130,8 @@ namespace System.Windows.Forms
                ContextMenu             context_menu; // Context menu associated with the control
 
                // double buffering
-               Graphics                backbuffer_dc;
-               object                  backbuffer;
-               Region                  invalid_region;
-
+               DoubleBuffer            backbuffer;
+               
                // to implement DeviceContext without depending on double buffering
                Bitmap bmp;
                Graphics bmp_g;
@@ -299,15 +300,104 @@ namespace System.Windows.Forms
                        #endregion      // ControlAccessibleObject Public Instance Methods
                }
 
+               private class DoubleBuffer : IDisposable
+               {
+                       public Region InvalidRegion;
+                       private Stack real_graphics;
+                       private object back_buffer;
+                       private Control parent;
+                       private bool pending_disposal;
+                       
+                       public DoubleBuffer (Control parent)
+                       {
+                               this.parent = parent;
+                               real_graphics = new Stack ();
+                               int width = parent.Width;
+                               int height = parent.Height;
+
+                               if (width < 1) width = 1;
+                               if (height < 1) height = 1;
+
+                               XplatUI.CreateOffscreenDrawable (parent.Handle, width, height, out back_buffer);
+                               Invalidate ();
+                       }
+                       
+                       public void Blit (PaintEventArgs pe)
+                       {
+                               Graphics buffered_graphics;
+                               buffered_graphics = XplatUI.GetOffscreenGraphics (back_buffer);
+                               XplatUI.BlitFromOffscreen (parent.Handle, pe.Graphics, back_buffer, buffered_graphics, pe.ClipRectangle);
+                               buffered_graphics.Dispose ();
+                       }
+                       
+                       public void Start (PaintEventArgs pe)
+                       {                               
+                               // We need to get the graphics for every paint.
+                               real_graphics.Push(pe.SetGraphics (XplatUI.GetOffscreenGraphics (back_buffer)));
+                       }
+
+                       public void End (PaintEventArgs pe)
+                       {
+                               Graphics buffered_graphics;
+                               buffered_graphics = pe.SetGraphics ((Graphics) real_graphics.Pop ());
+
+                               if (pending_disposal) 
+                                       Dispose ();
+                               else {
+                                       XplatUI.BlitFromOffscreen (parent.Handle, pe.Graphics, back_buffer, buffered_graphics, pe.ClipRectangle);
+                                       InvalidRegion.Exclude (pe.ClipRectangle);
+                               }
+                               buffered_graphics.Dispose ();
+                       }
+                       
+                       public void Invalidate ()
+                       {
+                               if (InvalidRegion != null)
+                                       InvalidRegion.Dispose ();
+                               InvalidRegion = new Region (parent.ClientRectangle);
+                       }
+                       
+                       public void Dispose ()
+                       {
+                               if (real_graphics.Count > 0) {
+                                       pending_disposal = true;
+                                       return;
+                               }
+                               
+                               XplatUI.DestroyOffscreenDrawable (back_buffer);
+
+                               if (InvalidRegion != null)
+                                       InvalidRegion.Dispose ();
+                               InvalidRegion = null;
+                               back_buffer = null;
+                               GC.SuppressFinalize (this);
+                       }
+
+                       #region IDisposable Members
+                       void IDisposable.Dispose ()
+                       {
+                               Dispose ();
+                       }
+                       #endregion
+                       
+                       ~DoubleBuffer ()
+                       {
+                               Dispose ();
+                       }
+               }
+
+               [ListBindable (false)]
 #if NET_2_0
                [ComVisible (false)]
+               public class ControlCollection : Layout.ArrangedElementCollection, IList, ICollection, ICloneable, IEnumerable {
 #else
                [DesignerSerializer("System.Windows.Forms.Design.ControlCollectionCodeDomSerializer, " + Consts.AssemblySystem_Design, "System.ComponentModel.Design.Serialization.CodeDomSerializer, " + Consts.AssemblySystem_Design)]
-#endif
-               [ListBindable(false)]
                public class ControlCollection : IList, ICollection, ICloneable, IEnumerable {
+#endif
                        #region ControlCollection Local Variables
+#if !NET_2_0
                        ArrayList list;
+#endif
                        ArrayList impl_list;
                        Control[] all_controls;
                        Control owner;
@@ -316,7 +406,9 @@ namespace System.Windows.Forms
                        #region ControlCollection Public Constructor
                        public ControlCollection(Control owner) {
                                this.owner=owner;
+#if !NET_2_0
                                this.list=new ArrayList();
+#endif
                        }
                        #endregion
 
@@ -326,9 +418,11 @@ namespace System.Windows.Forms
                        }
 
 
+#if !NET_2_0
                        public int Count {
                                get { return list.Count; }
                        }
+#endif
 
 #if NET_2_0
                        bool IList.IsReadOnly
@@ -341,6 +435,22 @@ namespace System.Windows.Forms
                                }
                        }
 
+#if NET_2_0
+                       public Control Owner { get { return this.owner; } }
+                       
+                       public virtual Control this[string key] {
+                               get { 
+                                       int index = IndexOfKey (key);
+                                       
+                                       if (index >= 0)
+                                               return this[index];
+                                               
+                                       return null;
+                               }
+                       }
+                       
+                       new
+#endif
                        public virtual Control this[int index] {
                                get {
                                        if (index < 0 || index >= list.Count) {
@@ -348,10 +458,12 @@ namespace System.Windows.Forms
                                        }
                                        return (Control)list[index];
                                }
+                               
+                               
                        }
                        #endregion // ControlCollection Public Instance Properties
                        
-                       #region ControlCollection Private Instance Methods
+                       #region ControlCollection Instance Methods
                        public virtual void Add (Control value)
                        {
                                if (value == null)
@@ -450,6 +562,9 @@ namespace System.Windows.Forms
                                }
                        }
 
+#if NET_2_0
+                       new
+#endif
                        public virtual void Clear ()
                        {
                                all_controls = null;
@@ -502,17 +617,24 @@ namespace System.Windows.Forms
                                return Contains (value) || ImplicitContains (value);
                        }
 
+#if NET_2_0
+                       public virtual bool ContainsKey (string key)
+                       {
+                               return IndexOfKey (key) >= 0;
+                       }
+#endif
+
                        void ICollection.CopyTo (Array array, int index)
                        {
                                CopyTo (array, index);
                        }
 
-                       internal void CopyTo (Array array, int index)
+#if !NET_2_0
+                       public void CopyTo (Array array, int index)
                        {
                                list.CopyTo(array, index);
                        }
 
-#if !NET_2_0
                        public override bool Equals (object other)
                        {
                                if (other is ControlCollection && (((ControlCollection)other).owner==this.owner)) {
@@ -523,6 +645,27 @@ namespace System.Windows.Forms
                        }
 #endif
 
+#if NET_2_0
+                       // LAMESPEC: MSDN says AE, MS implementation throws ANE
+                       public Control[] Find (string key, bool searchAllChildren)
+                       {
+                               if (string.IsNullOrEmpty (key))
+                                       throw new ArgumentNullException ("key");
+                                       
+                               ArrayList al = new ArrayList ();
+                               
+                               foreach (Control c in list) {
+                                       if (c.Name.Equals (key, StringComparison.CurrentCultureIgnoreCase))
+                                               al.Add (c);
+                                               
+                                       if (searchAllChildren)
+                                               al.AddRange (c.Controls.Find (key, true));
+                               }
+                               
+                               return (Control[])al.ToArray (typeof (Control));
+                       }
+#endif
+
                        public int GetChildIndex(Control child) {
                                return GetChildIndex(child, false);
                        }
@@ -544,7 +687,7 @@ namespace System.Windows.Forms
                        }
 
 #if NET_2_0
-                       public virtual IEnumerator
+                       public override IEnumerator
 #else
                        public IEnumerator
 #endif
@@ -588,6 +731,20 @@ namespace System.Windows.Forms
                                return list.IndexOf(control);
                        }
 
+#if NET_2_0
+                       public virtual int IndexOfKey (string key)
+                       {
+                               if (string.IsNullOrEmpty (key))
+                                       return -1;
+                                       
+                               for (int i = 0; i < list.Count; i++)
+                                       if (((Control)list[i]).Name.Equals (key, StringComparison.CurrentCultureIgnoreCase))
+                                               return i;
+                                               
+                               return -1;
+                       }
+#endif
+
                        public virtual void Remove(Control value)
                        {
                                if (value == null)
@@ -616,6 +773,9 @@ namespace System.Windows.Forms
                                owner.UpdateChildrenZOrder ();
                        }
 
+#if NET_2_0
+                       new
+#endif
                        public void RemoveAt(int index)
                        {
                                if (index < 0 || index >= list.Count) {
@@ -625,6 +785,14 @@ namespace System.Windows.Forms
                        }
 
 #if NET_2_0
+                       public virtual void RemoveByKey (string key)
+                       {
+                               int index = IndexOfKey (key);
+                               
+                               if (index >= 0)
+                                       RemoveAt (index);
+                       }       
+               
                        public virtual void
 #else
                        public void
@@ -761,6 +929,7 @@ namespace System.Windows.Forms
                #region Public Constructors
                public Control()
                {
+                       layout_type = LayoutType.Anchor;
                        anchor_style = AnchorStyles.Top | AnchorStyles.Left;
 
                        is_created = false;
@@ -785,9 +954,6 @@ namespace System.Windows.Forms
                        tab_stop = true;
                        ime_mode = ImeMode.Inherit;
 
-                       layout_engine = this.LayoutEngine;
-                       if (layout_engine == null)
-                               layout_engine = new Layout.DefaultLayout ();
 #if NET_2_0
                        backgroundimage_layout = ImageLayout.Tile;
                        use_compatible_text_rendering = Application.use_compatible_text_rendering;
@@ -814,7 +980,8 @@ 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(ref client_rect, CreateParams.Style, CreateParams.ExStyle, null, out bounds);
+                       bounds.Size = SizeFromClientSize (client_size);
+                       
                        if ((CreateParams.Style & (int)WindowStyles.WS_CHILD) == 0) {
                                bounds.X=-1;
                                bounds.Y=-1;
@@ -866,10 +1033,6 @@ namespace System.Windows.Forms
                                        bmp_g = null;
                                }
                                
-                               if (invalid_region!=null) {
-                                       invalid_region.Dispose();
-                                       invalid_region=null;
-                               }
                                if (this.InvokeRequired) {
                                        if (Application.MessageLoop) {
                                                this.BeginInvokeInternal(new MethodInvoker(DestroyHandle), null, true);
@@ -895,6 +1058,14 @@ namespace System.Windows.Forms
                #endregion      // Public Constructors
 
                #region Internal Properties
+               internal bool VisibleInternal {
+                       get { return is_visible; }
+               }
+
+               internal LayoutType ControlLayoutType {
+                       get { return layout_type; }
+               }
+
                internal BorderStyle InternalBorderStyle {
                        get {
                                return border_style;
@@ -908,8 +1079,9 @@ namespace System.Windows.Forms
                                        border_style = value;
 
                                        if (IsHandleCreated) {
-                                               XplatUI.SetBorderStyle(window.Handle, (FormBorderStyle)border_style);
-                                               Refresh();
+                                               XplatUI.SetBorderStyle (window.Handle, (FormBorderStyle)border_style);
+                                               RecreateHandle ();
+                                               Refresh ();
                                        }
                                }
                        }
@@ -1007,39 +1179,23 @@ namespace System.Windows.Forms
 
                private void InvalidateBackBuffer ()
                {
-                       if (invalid_region != null)
-                               invalid_region.Dispose();
-                       invalid_region = new Region (ClientRectangle);
+                       if (backbuffer != null)
+                               backbuffer.Invalidate ();
                }
 
-               private void CreateBackBuffer ()
+               private DoubleBuffer GetBackBuffer ()
                {
-                       if (backbuffer != null)
-                               return;
-
-                       int width = Width;
-                       int height = Height;
-
-                       if (width < 1) width = 1;
-                       if (height < 1) height = 1;
-
-                       XplatUI.CreateOffscreenDrawable (Handle, width, height, out backbuffer, out backbuffer_dc);
-                       InvalidateBackBuffer ();
+                       if (backbuffer == null)
+                               backbuffer = new DoubleBuffer (this);
+                       return backbuffer;
                }
 
                private void DisposeBackBuffer ()
                {
-                       if (backbuffer == null)
-                               return;
-
-                       XplatUI.DestroyOffscreenDrawable (backbuffer, backbuffer_dc);
-                       backbuffer = null;
-                       backbuffer_dc = null;
-
-
-                       if (invalid_region != null)
-                               invalid_region.Dispose ();
-                       invalid_region = null;
+                       if (backbuffer != null) {
+                               backbuffer.Dispose ();
+                               backbuffer = null;
+                       }
                }
 
                internal static void SetChildColor(Control parent) {
@@ -1061,7 +1217,7 @@ namespace System.Windows.Forms
                        }
 
                        container = GetContainerControl();
-                       if (container != null) {
+                       if (container != null && (Control)container != control) {
                                container.ActiveControl = control;
                        }
                        if (control.IsHandleCreated) {
@@ -1541,7 +1697,7 @@ namespace System.Windows.Forms
                                OnRightToLeftChanged(EventArgs.Empty);
                        }
 
-                       if ((new_parent != null) && new_parent.Created && !Created) {
+                       if ((new_parent != null) && new_parent.Created && is_visible && !Created) {
                                CreateControl();
                        }
 
@@ -1558,6 +1714,19 @@ namespace System.Windows.Forms
                                        dist_bottom = parent.ClientSize.Height - bounds.Y - bounds.Height;
                        }
                }
+               
+               private bool UseDoubleBuffering {
+                       get {
+                               if (!ThemeEngine.Current.DoubleBufferingSupported)
+                                       return false;
+
+#if NET_2_0
+                               if (DoubleBuffered)
+                                       return true;
+#endif
+                               return (control_style & ControlStyles.DoubleBuffer) != 0;
+                       }
+               }
                #endregion      // Private & Internal Methods
 
                #region Public Static Properties
@@ -1707,11 +1876,14 @@ namespace System.Windows.Forms
                        }
 
                        set {
+                               layout_type = LayoutType.Anchor;
+
                                anchor_style=value;
 
-                               if (parent != null) {
-                                       parent.PerformLayout(this, "Parent");
-                               }
+                               UpdateDistances ();
+
+                               if (parent != null)
+                                       parent.PerformLayout(this, "Anchor");
                        }
                }
 
@@ -1727,12 +1899,12 @@ namespace System.Windows.Forms
                [DefaultValue (false)]
                [MonoTODO("This method currently does nothing")]
                public virtual bool AutoSize {
-                       get {
-                               //Console.Error.WriteLine("Unimplemented: Control::get_AutoSize()");
-                               return auto_size;
-                       }
+                       get { return auto_size; }
                        set {
-                               auto_size = value;
+                               if (this.auto_size != value) {
+                                       auto_size = value;
+                                       OnAutoSizeChanged (EventArgs.Empty);
+                               }
                        }
                }
                
@@ -1755,7 +1927,10 @@ namespace System.Windows.Forms
                                return minimum_size;
                        }
                        set {
-                               minimum_size = value;
+                               if (minimum_size != value) {
+                                       minimum_size = value;
+                                       PerformLayout ();
+                               }
                        }
                }
 #endif // NET_2_0
@@ -1820,6 +1995,7 @@ namespace System.Windows.Forms
                                if (value != backgroundimage_layout) {
                                        backgroundimage_layout = value;
                                        Invalidate ();
+                                       OnBackgroundImageLayoutChanged (EventArgs.Empty);
                                }
                                
                        }
@@ -1975,6 +2151,9 @@ namespace System.Windows.Forms
 
                        set {
                                this.SetClientSizeCore(value.Width, value.Height);
+#if NET_2_0
+                               this.OnClientSizeChanged (EventArgs.Empty);
+#endif
                        }
                }
 
@@ -1988,10 +2167,10 @@ namespace System.Windows.Forms
                        }
                }
 
-        internal bool ContainerSelected {
-            get { return container_selected; }
-            set { container_selected = value; }
-        }
+               internal bool ContainerSelected {
+                       get { return container_selected; }
+                       set { container_selected = value; }
+               }
 
                [EditorBrowsable(EditorBrowsableState.Advanced)]
                [Browsable(false)]
@@ -2153,6 +2332,8 @@ namespace System.Windows.Forms
                        }
 
                        set {
+                               layout_type = LayoutType.Dock;
+
                                if (dock_style == value) {
                                        return;
                                }
@@ -2172,7 +2353,7 @@ namespace System.Windows.Forms
                                }
 
                                if (parent != null) {
-                                       parent.PerformLayout(this, "Parent");
+                                       parent.PerformLayout(this, "Dock");
                                }
 
                                OnDockChanged(EventArgs.Empty);
@@ -2182,11 +2363,18 @@ namespace System.Windows.Forms
 #if NET_2_0
                protected virtual bool DoubleBuffered {
                        get {
-                               return (control_style & ControlStyles.DoubleBuffer) != 0;
+                               return (control_style & ControlStyles.OptimizedDoubleBuffer) != 0;
                        }
 
                        set {
-                               SetStyle (ControlStyles.DoubleBuffer, value);
+                               if (value == DoubleBuffered)
+                                       return;
+                               if (value) {
+                                       SetStyle (ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);
+                               } else {
+                                       SetStyle (ControlStyles.OptimizedDoubleBuffer, false);
+                               }
+                               
                        }
                }
 #endif
@@ -2208,14 +2396,15 @@ namespace System.Windows.Forms
                        }
 
                        set {
+                               if (this.is_enabled != value) {
+                                       bool old_value = is_enabled;
 
-                               bool old_value = is_enabled;
-
-                               is_enabled = value;
-                               if (old_value != value && !value && this.has_focus)
-                                       SelectNextControl(this, true, true, true, true);
+                                       is_enabled = value;
+                                       if (old_value != value && !value && this.has_focus)
+                                               SelectNextControl(this, true, true, true, true);
 
-                               OnEnabledChanged (EventArgs.Empty);
+                                       OnEnabledChanged (EventArgs.Empty);
+                               }
                        }
                }
 
@@ -2254,6 +2443,7 @@ namespace System.Windows.Forms
                                font = value;
                                Invalidate();
                                OnFontChanged (EventArgs.Empty);
+                               PerformLayout ();
                        }
                }
 
@@ -2401,8 +2591,12 @@ namespace System.Windows.Forms
                public virtual
 #endif
                Layout.LayoutEngine LayoutEngine {
-                       get { return new Layout.DefaultLayout (); }
-               } 
+                       get {
+                               if (layout_engine == null)
+                                       layout_engine = new Layout.DefaultLayout ();
+                               return layout_engine;
+                       }
+               }
 
                [EditorBrowsable(EditorBrowsableState.Always)]
                [Browsable(false)]
@@ -2433,7 +2627,12 @@ namespace System.Windows.Forms
                [Localizable (true)]
                public Padding Margin {
                        get { return this.margin; }
-                       set { this.margin = value; }
+                       set { 
+                               if (this.margin != value) {
+                                       this.margin = value; 
+                                       OnMarginChanged (EventArgs.Empty);
+                               }
+                       }
                }
 #endif
 
@@ -2456,8 +2655,11 @@ namespace System.Windows.Forms
                        }
 
                        set {
-                               padding = value;
-                               OnPaddingChanged (EventArgs.Empty);
+                               if (padding != value) {
+                                       padding = value;
+                                       OnPaddingChanged (EventArgs.Empty);
+                                       PerformLayout ();
+                               }
                        }
                }
 #endif
@@ -2535,10 +2737,15 @@ namespace System.Windows.Forms
                        }
 
                        set {
-                               if (value != null && IsHandleCreated) {
-                                       XplatUI.SetClipRegion(Handle, value);
+                               if (clip_region != value) {
+                                       if (value != null && IsHandleCreated)
+                                               XplatUI.SetClipRegion(Handle, value);
+
+                                       clip_region = value;
+#if NET_2_0
+                                       OnRegionChanged (EventArgs.Empty);
+#endif
                                }
-                               clip_region = value;
                        }
                }
 
@@ -2569,6 +2776,7 @@ namespace System.Windows.Forms
                                if (value != right_to_left) {
                                        right_to_left = value;
                                        OnRightToLeftChanged(EventArgs.Empty);
+                                       PerformLayout ();
                                }
                        }
                }
@@ -2835,6 +3043,10 @@ namespace System.Windows.Forms
                        }
                }
 
+#if NET_2_0
+               protected virtual Cursor DefaultCursor { get { return Cursors.Default; } }
+#endif
+
                protected virtual ImeMode DefaultImeMode {
                        get {
                                return ImeMode.Inherit;
@@ -2845,6 +3057,10 @@ namespace System.Windows.Forms
                protected virtual Padding DefaultMargin {
                        get { return new Padding (3); }
                }
+               
+               protected virtual Size DefaultMaximumSize { get { return new Size (); } }
+               protected virtual Size DefaultMinimumSize { get { return new Size (); } }
+               protected virtual Padding DefaultPadding { get { return new Padding (); } }
 #endif
 
                protected virtual Size DefaultSize {
@@ -2980,7 +3196,8 @@ namespace System.Windows.Forms
                        return false;
                }
 
-               public void CreateControl() {
+               public void CreateControl ()
+               {
                        if (is_disposed) {
                                throw new ObjectDisposedException(GetType().FullName.ToString());
                        }
@@ -2998,7 +3215,8 @@ namespace System.Windows.Forms
 
                        Control [] controls = child_controls.GetAllControls ();
                        for (int i=0; i<controls.Length; i++) {
-                               controls [i].CreateControl ();
+                               if (controls [i].is_visible)
+                                       controls [i].CreateControl ();
                        }
 
                        UpdateChildrenZOrder();
@@ -3123,14 +3341,17 @@ namespace System.Windows.Forms
                        if (!IsHandleCreated)
                                return;
 
-                       NotifyInvalidate(rc);
+                       if  (rc.Width > 0 && rc.Height > 0) {
 
-                       XplatUI.Invalidate(Handle, rc, false);
+                               NotifyInvalidate(rc);
 
-                       if (invalidateChildren) {
-                               Control [] controls = child_controls.GetAllControls ();
-                               for (int i=0; i<controls.Length; i++)
-                                       controls [i].Invalidate ();
+                               XplatUI.Invalidate(Handle, rc, false);
+
+                               if (invalidateChildren) {
+                                       Control [] controls = child_controls.GetAllControls ();
+                                       for (int i=0; i<controls.Length; i++)
+                                               controls [i].Invalidate ();
+                               }
                        }
                        OnInvalidated(new InvalidateEventArgs(rc));
                }
@@ -3203,9 +3424,6 @@ namespace System.Windows.Forms
 
                        // Perform all Dock and Anchor calculations
                        try {
-                               layout_engine.Layout(this, levent);
-
-                               // Let everyone know
                                OnLayout(levent);
                        }
 
@@ -3271,7 +3489,7 @@ namespace System.Windows.Forms
                        return new Rectangle(PointToScreen(r.Location), r.Size);
                }
 
-               public virtual void Refresh() {                 
+               public virtual void Refresh() {
                        if (IsHandleCreated) {
                                Invalidate();
                                XplatUI.UpdateWindow(window.Handle);
@@ -3362,17 +3580,17 @@ namespace System.Windows.Forms
 #endif
 
                public void Select() {
-            if (this is ContainerControl)
-                ContainerSelected = true;
-            else {
-                Control c = this.Parent;
-                while (c != null) {
-                    c.ContainerSelected = false;
-                    c = c.Parent;
-                }
-            }
+                       if (this is ContainerControl)
+                               ContainerSelected = true;
+                       else {
+                               Control c = this.Parent;
+                               while (c != null) {
+                                       c.ContainerSelected = false;
+                                       c = c.Parent;
+                               }
+                       }
                        Select(false, false);   
-        }
+               }
 
 #if DebugFocus
                private void printTree(Control c, string t) {
@@ -3446,7 +3664,8 @@ namespace System.Windows.Forms
                        }
                }
 
-               public void Show() {
+               public void Show ()
+               {
                        if (!is_created) {
                                this.CreateControl();
                        }
@@ -3876,8 +4095,9 @@ namespace System.Windows.Forms
                        IContainerControl       container;
                        
                        container = GetContainerControl();
-                       if (container != null)
-                               container.ActiveControl = this;
+                       if (container != null && (Control)container != this)
+                if (!this.Parent.ContainerSelected)
+                                   container.ActiveControl = this;
                }
 
                [EditorBrowsable(EditorBrowsableState.Advanced)]
@@ -3903,19 +4123,10 @@ namespace System.Windows.Forms
 
                [EditorBrowsable(EditorBrowsableState.Advanced)]
                protected virtual void SetClientSizeCore(int x, int y) {
-                       // Calculate the actual window size from the client size (it usually stays the same or grows)
-                       Rectangle       ClientRect;
-                       Rectangle       WindowRect;
-                       CreateParams    cp;
-
-                       ClientRect = new Rectangle(0, 0, x, y);
-                       cp = this.CreateParams;
-
-                       if (XplatUI.CalculateWindowRect(ref ClientRect, cp.Style, cp.ExStyle, null, out WindowRect)==false) {
-                               return;
-                       }
-
-                       SetBounds(bounds.X, bounds.Y, WindowRect.Width, WindowRect.Height, BoundsSpecified.Size);
+                       Size NewSize = SizeFromClientSize (new Size (x, y));
+                       
+                       if (NewSize != Size.Empty)
+                               SetBounds (bounds.X, bounds.Y, NewSize.Width, NewSize.Height, BoundsSpecified.Size);
                }
 
                [EditorBrowsable(EditorBrowsableState.Advanced)]
@@ -3929,7 +4140,7 @@ namespace System.Windows.Forms
 
                protected void SetTopLevel(bool value) {
                        if ((GetTopLevel() != value) && (parent != null)) {
-                               throw new Exception();
+                               throw new ArgumentException ("Cannot change toplevel style of a parented control.");
                        }
 
                        if (this is Form) {
@@ -3939,7 +4150,7 @@ namespace System.Windows.Forms
                                        }
                                } else {
                                        if (Visible) {
-                                               Visible = false;
+                                               Visible = false;
                                        }
                                }
                        }
@@ -3948,7 +4159,7 @@ namespace System.Windows.Forms
 
                protected virtual void SetVisibleCore(bool value) {
                        if (value!=is_visible) {
-                               if (value && (window.Handle == IntPtr.Zero) || !is_created) {
+                               if (value && ((window.Handle == IntPtr.Zero) || !is_created)) {
                                        CreateControl();
                                }
 
@@ -3978,11 +4189,32 @@ namespace System.Windows.Forms
                                if (parent != null) {
                                        parent.PerformLayout(this, "visible");
                                } else {
-                                       PerformLayout(this, "visible");
+                                       if (is_visible)
+                                               PerformLayout(this, "visible");
                                }
                        }
                }
-       
+
+#if NET_2_0
+               protected 
+#else
+               internal
+#endif
+               virtual Size SizeFromClientSize (Size clientSize)
+               {
+                       Rectangle ClientRect;
+                       Rectangle WindowRect;
+                       CreateParams cp;
+
+                       ClientRect = new Rectangle (0, 0, clientSize.Width, clientSize.Height);
+                       cp = this.CreateParams;
+
+                       if (XplatUI.CalculateWindowRect (ref ClientRect, cp.Style, cp.ExStyle, null, out WindowRect))
+                               return new Size (WindowRect.Width, WindowRect.Height);
+                               
+                       return Size.Empty;
+               }
+
                [EditorBrowsable(EditorBrowsableState.Advanced)]
                protected void UpdateBounds() {
                        int     x;
@@ -4046,6 +4278,9 @@ namespace System.Windows.Forms
 
                        if (resized) {
                                OnSizeChanged(EventArgs.Empty);
+#if NET_2_0
+                               OnClientSizeChanged (EventArgs.Empty);
+#endif
                        }
                }
 
@@ -4157,27 +4392,18 @@ namespace System.Windows.Forms
                                if (paint_event == null) {
                                        return;
                                }
-
-                               if (invalid_region != null && !invalid_region.IsVisible (paint_event.ClipRectangle)) {
-
-                                       // Just blit the previous image
-                                       XplatUI.BlitFromOffscreen (Handle, paint_event.Graphics, backbuffer, backbuffer_dc, paint_event.ClipRectangle);
-                                       XplatUI.PaintEventEnd (Handle, true);
-                                       return;
-                               }
-
-                               Graphics dc = null;
-                               Graphics back_dc = null;
-                               object back = null;
-                               if (ThemeEngine.Current.DoubleBufferingSupported) {
-                                       if ((control_style & ControlStyles.DoubleBuffer) != 0) {
-                                               CreateBackBuffer ();
-                                               back = backbuffer;
-                                               back_dc = backbuffer_dc;
-                                               dc = paint_event.SetGraphics (back_dc);
+                               DoubleBuffer current_buffer = null;
+                               if (UseDoubleBuffering) {
+                                       current_buffer = GetBackBuffer ();
+                                       if (!current_buffer.InvalidRegion.IsVisible (paint_event.ClipRectangle)) {
+                                               // Just blit the previous image
+                                               current_buffer.Blit (paint_event);
+                                               XplatUI.PaintEventEnd (Handle, true);
+                                               return;
                                        }
+                                       current_buffer.Start (paint_event);
                                }
-
+                               
                                if (!GetStyle(ControlStyles.Opaque)) {
                                        OnPaintBackground(paint_event);
                                }
@@ -4190,15 +4416,10 @@ namespace System.Windows.Forms
                                        OnPaint(paint_event);
                                }
 
-                               if (ThemeEngine.Current.DoubleBufferingSupported)
-                                       if ((control_style & ControlStyles.DoubleBuffer) != 0) {
-                                               XplatUI.BlitFromOffscreen (Handle, dc, back, back_dc, paint_event.ClipRectangle);
-                                               paint_event.SetGraphics (dc);
-                                               invalid_region.Exclude (paint_event.ClipRectangle);
+                               if (current_buffer != null) {
+                                       current_buffer.End (paint_event);
+                               }
 
-                                               if (back != backbuffer)
-                                                       XplatUI.DestroyOffscreenDrawable (back, back_dc);
-                                       }
 
                                XplatUI.PaintEventEnd(Handle, true);
 
@@ -4465,11 +4686,11 @@ namespace System.Windows.Forms
                        }
 
                        case Msg.WM_SETFOCUS: {
-                               if (!has_focus) {
-                                       this.has_focus = true;
+                               if (!has_focus) {                
                     if (this.Parent != null && this.Parent.ContainerSelected)
                         return;
-                                   OnGotFocusInternal (EventArgs.Empty);
+                    this.has_focus = true;
+                    OnGotFocusInternal (EventArgs.Empty);
                                }
                                return;
                        }
@@ -4500,7 +4721,16 @@ namespace System.Windows.Forms
                #endregion      // Public Instance Methods
 
                #region OnXXX methods
-               [EditorBrowsable(EditorBrowsableState.Advanced)]
+#if NET_2_0
+               protected virtual void OnAutoSizeChanged (EventArgs e)
+               {
+                       EventHandler eh = (EventHandler)(Events[AutoSizeChangedEvent]);
+                       if (eh != null)
+                               eh (this, e);
+               }
+#endif
+
+               [EditorBrowsable (EditorBrowsableState.Advanced)]
                protected virtual void OnBackColorChanged(EventArgs e) {
                        EventHandler eh = (EventHandler)(Events [BackColorChangedEvent]);
                        if (eh != null)
@@ -4516,6 +4746,16 @@ namespace System.Windows.Forms
                        for (int i=0; i<child_controls.Count; i++) child_controls[i].OnParentBackgroundImageChanged(e);
                }
 
+#if NET_2_0
+               [EditorBrowsable (EditorBrowsableState.Advanced)]
+               protected virtual void OnBackgroundImageLayoutChanged (EventArgs e)
+               {
+                       EventHandler eh = (EventHandler)(Events[BackgroundImageLayoutChangedEvent]);
+                       if (eh != null)
+                               eh (this, e);
+               }
+#endif
+
                [EditorBrowsable(EditorBrowsableState.Advanced)]
                protected virtual void OnBindingContextChanged(EventArgs e) {
                        CheckDataBindings ();
@@ -4546,6 +4786,16 @@ namespace System.Windows.Forms
                                eh (this, e);
                }
 
+#if NET_2_0
+               [EditorBrowsable (EditorBrowsableState.Advanced)]
+               protected virtual void OnClientSizeChanged (EventArgs e)
+               {
+                       EventHandler eh = (EventHandler)(Events[ClientSizeChangedEvent]);
+                       if (eh != null)
+                               eh (this, e);
+               }
+#endif
+
                [EditorBrowsable(EditorBrowsableState.Advanced)]
                protected virtual void OnContextMenuChanged(EventArgs e) {
                        EventHandler eh = (EventHandler)(Events [ContextMenuChangedEvent]);
@@ -4723,27 +4973,22 @@ namespace System.Windows.Forms
 
                [EditorBrowsable(EditorBrowsableState.Advanced)]
                protected virtual void OnInvalidated(InvalidateEventArgs e) {
-                       if (ThemeEngine.Current.DoubleBufferingSupported)
-                               if ((control_style & ControlStyles.DoubleBuffer) != 0) {
-                                       // should this block be here?  seems like it
-                                       // would be more at home in
-                                       // NotifyInvalidated..
-                                       if (e.InvalidRect == ClientRectangle) {
-                                               InvalidateBackBuffer ();
-                                       }
-                                       else {
-                                               // we need this Inflate call here so
-                                               // that the border of the rectangle is
-                                               // considered Visible (the
-                                               // invalid_region.IsVisible call) in
-                                               // the WM_PAINT handling below.
-                                               Rectangle r = Rectangle.Inflate(e.InvalidRect, 1,1);
-                                               if (invalid_region == null)
-                                                       invalid_region = new Region (r);
-                                               else
-                                                       invalid_region.Union (r);
-                                       }
+                       if (UseDoubleBuffering) {
+                               // should this block be here?  seems like it
+                               // would be more at home in
+                               // NotifyInvalidated..
+                               if (e.InvalidRect == ClientRectangle) {
+                                       InvalidateBackBuffer ();
+                               } else if (backbuffer != null){
+                                       // we need this Inflate call here so
+                                       // that the border of the rectangle is
+                                       // considered Visible (the
+                                       // invalid_region.IsVisible call) in
+                                       // the WM_PAINT handling below.
+                                       Rectangle r = Rectangle.Inflate(e.InvalidRect, 1,1);
+                                       backbuffer.InvalidRegion.Union (r);
                                }
+                       }
 
                        InvalidateEventHandler eh = (InvalidateEventHandler)(Events [InvalidatedEvent]);
                        if (eh != null)
@@ -4776,6 +5021,8 @@ namespace System.Windows.Forms
                        LayoutEventHandler eh = (LayoutEventHandler)(Events [LayoutEvent]);
                        if (eh != null)
                                eh (this, levent);
+
+                       LayoutEngine.Layout (this, levent);
                }
 
                [EditorBrowsable(EditorBrowsableState.Advanced)]
@@ -4801,6 +5048,13 @@ namespace System.Windows.Forms
                }
 
 #if NET_2_0
+               protected virtual void OnMarginChanged (EventArgs e)
+               {
+                       EventHandler eh = (EventHandler)(Events[MarginChangedEvent]);
+                       if (eh != null)
+                               eh (this, e);
+               }
+
                [EditorBrowsable (EditorBrowsableState.Advanced)]
                protected virtual void OnMouseCaptureChanged (EventArgs e)
                {
@@ -5001,17 +5255,23 @@ namespace System.Windows.Forms
                                eh (this, e);
                }
 
+#if NET_2_0
+               [EditorBrowsable (EditorBrowsableState.Advanced)]
+               protected virtual void OnRegionChanged (EventArgs e)
+               {
+                       EventHandler eh = (EventHandler)(Events[RegionChangedEvent]);
+                       if (eh != null)
+                               eh (this, e);
+               }
+#endif
+
                [EditorBrowsable(EditorBrowsableState.Advanced)]
                protected virtual void OnResize(EventArgs e) {
+                       PerformLayout(this, "Bounds");
+
                        EventHandler eh = (EventHandler)(Events [ResizeEvent]);
                        if (eh != null)
                                eh (this, e);
-
-                       PerformLayout(this, "bounds");
-
-                       if (parent != null) {
-                               parent.PerformLayout();
-                       }
                }
 
                [EditorBrowsable(EditorBrowsableState.Advanced)]