2007-03-21 Jonathan Pobst <monkey@jpobst.com>
[mono.git] / mcs / class / Managed.Windows.Forms / System.Windows.Forms / Control.cs
index e5569a31f9ede29a604c48ef455f8f7940dcdc8e..a2766d204e8e517a21714a9400d3c70550c09636 100644 (file)
@@ -69,6 +69,7 @@ namespace System.Windows.Forms
                Rectangle               explicit_bounds; // explicitly set bounds
                internal object                 creator_thread;         // thread that created the control
                internal                ControlNativeWindow     window;                 // object for native window handle
+               private                 IWindowTarget window_target;
                string                  name; // for object naming
 
                // State
@@ -127,6 +128,7 @@ namespace System.Windows.Forms
                BindingContext          binding_context;
                RightToLeft             right_to_left; // drawing direction for control
                ContextMenu             context_menu; // Context menu associated with the control
+               internal bool           use_compatible_text_rendering;
 
                // double buffering
                DoubleBuffer            backbuffer;
@@ -138,7 +140,6 @@ namespace System.Windows.Forms
                ControlBindingsCollection data_bindings;
 
 #if NET_2_0
-               internal bool use_compatible_text_rendering;
                static bool verify_thread_handle;
                Padding padding;
                ImageLayout backgroundimage_layout;
@@ -166,6 +167,11 @@ namespace System.Windows.Forms
                                }
                        }
 
+                       protected override void OnHandleChange()
+                       {
+                               this.owner.WindowTarget.OnHandleChange(this.owner.Handle);
+                       }
+
                        static internal Control ControlFromHandle(IntPtr hWnd) {
                                ControlNativeWindow     window;
 
@@ -193,7 +199,26 @@ namespace System.Windows.Forms
                        }
 
                        protected override void WndProc(ref Message m) {
-                               owner.WndProc(ref m);
+                               owner.WindowTarget.OnMessage(ref m);
+                       }
+               }
+
+               private class ControlWindowTarget : IWindowTarget
+               {
+                       private Control control;
+
+                       public ControlWindowTarget(Control control)
+                       {
+                               this.control = control;
+                       }
+
+                       public void OnHandleChange(IntPtr newHandle) 
+                       {
+                       }
+
+                       public void OnMessage(ref Message m) 
+                       {
+                               control.WndProc(ref m);
                        }
                }
                #endregion
@@ -201,13 +226,16 @@ namespace System.Windows.Forms
                #region Public Classes
                [ComVisible(true)]
                public class ControlAccessibleObject : AccessibleObject {
-                       Control owner;
+                       IntPtr handle;
 
                        #region ControlAccessibleObject Constructors
                        public ControlAccessibleObject(Control ownerControl)
                                : base (ownerControl)
                        {
-                               this.owner = ownerControl;
+                               if (ownerControl == null)
+                                       throw new ArgumentNullException ("owner");
+
+                               handle = ownerControl.Handle;
                        }
                        #endregion      // ControlAccessibleObject Constructors
 
@@ -226,7 +254,7 @@ namespace System.Windows.Forms
 
                        public IntPtr Handle {
                                get {
-                                       return owner.Handle;
+                                       return handle;
                                }
 
                                set {
@@ -258,7 +286,7 @@ namespace System.Windows.Forms
 
                        public Control Owner {
                                get {
-                                       return owner;
+                                       return base.owner;
                                }
                        }
 
@@ -281,14 +309,13 @@ namespace System.Windows.Forms
                                return base.GetHelpTopic (out FileName);
                        }
 
-                       [MonoTODO("Implement this and tie it into Control.AccessibilityNotifyClients")]
+                       [MonoTODO ("Implement this")]
                        public void NotifyClients(AccessibleEvents accEvent) {
                                throw new NotImplementedException();
                        }
 
-                       [MonoTODO("Implement this and tie it into Control.AccessibilityNotifyClients")]
+                       [MonoTODO ("Implement this")]
                        public void NotifyClients(AccessibleEvents accEvent, int childID) {
-                               throw new NotImplementedException();
                        }
 
                        public override string ToString() {
@@ -458,13 +485,19 @@ namespace System.Windows.Forms
                                if (value == null)
                                        return;
 
-                               bool owner_permits_toplevels = (owner is MdiClient) || (owner is Form && ((Form)owner).IsMdiContainer);
-                               bool child_is_toplevel = ((Control)value).GetTopLevel();
-                               bool child_is_mdichild = (value is Form && ((Form)value).IsMdiChild);
+                               Form form_value = value as Form;
+                               Form form_owner = owner as Form;
+                               bool owner_permits_toplevels = (owner is MdiClient) || (form_owner != null && form_owner.IsMdiContainer);
+                               bool child_is_toplevel = value.GetTopLevel();
+                               bool child_is_mdichild = form_value != null && form_value.IsMdiChild;
 
                                if (child_is_toplevel && !(owner_permits_toplevels && child_is_mdichild))
                                        throw new ArgumentException("Cannot add a top level control to a control.", "value");
                                
+                               if (child_is_mdichild && form_value.MdiParent != null && form_value.MdiParent != owner && form_value.MdiParent != owner.Parent) {
+                                       throw new ArgumentException ("Form cannot be added to the Controls collection that has a valid MDI parent.", "value");
+                               }
+                               
                                if (Contains (value)) {
                                        owner.PerformLayout();
                                        return;
@@ -497,7 +530,8 @@ namespace System.Windows.Forms
 
                                value.InitLayout();
 
-                               owner.UpdateChildrenZOrder();
+                               if (owner.Visible)
+                                       owner.UpdateChildrenZOrder();
                                owner.PerformLayout(value, "Parent");
                                owner.OnControlAdded(new ControlEventArgs(value));
                        }
@@ -511,17 +545,27 @@ namespace System.Windows.Forms
                                if (impl_list == null)
                                        impl_list = new ArrayList ();
 
-                               if (AllContains (control))
+                               if (AllContains (control)) {
+                                       owner.PerformLayout ();
                                        return;
+                               }
+
+                               if (control.parent != null) {
+                                       control.parent.Controls.Remove(control);
+                               }
 
                                all_controls = null;
                                impl_list.Add (control);
 
                                control.ChangeParent (owner);
                                control.InitLayout ();
-                               owner.UpdateChildrenZOrder ();
-                               owner.PerformLayout (control, "Parent");
-                               owner.OnControlAdded (new ControlEventArgs (control));
+                               if (owner.Visible)
+                                       owner.UpdateChildrenZOrder ();
+                               
+                               // If we are adding a new control that isn't
+                               // visible, don't trigger a layout
+                               if (control.VisibleInternal)
+                                       owner.PerformLayout (control, "Parent");
                        }
 #if NET_2_0
                        [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
@@ -911,7 +955,8 @@ namespace System.Windows.Forms
                #endregion      // ControlCollection Class
                
                #region Public Constructors
-               public Control() {
+               public Control ()
+               {
                        layout_type = LayoutType.Anchor;
                        anchor_style = AnchorStyles.Top | AnchorStyles.Left;
 
@@ -936,6 +981,7 @@ namespace System.Windows.Forms
                        dist_bottom = 0;
                        tab_stop = true;
                        ime_mode = ImeMode.Inherit;
+                       use_compatible_text_rendering = true;
 
 #if NET_2_0
                        backgroundimage_layout = ImageLayout.Tile;
@@ -958,20 +1004,23 @@ namespace System.Windows.Forms
                        text = string.Empty;
                        name = string.Empty;
 
+                       window_target = new ControlWindowTarget(this);
                        window = new ControlNativeWindow(this);
                        child_controls = CreateControlsInstance();
                        client_size = new Size(DefaultSize.Width, DefaultSize.Height);
                        client_rect = new Rectangle(0, 0, DefaultSize.Width, DefaultSize.Height);
-                       bounds.Size = SizeFromClientSize (client_size);
+                       bounds.Size = InternalSizeFromClientSize (client_size);
                        explicit_bounds = bounds;
                }
 
-               public Control(Control parent, string text) : this() {
+               public Control (Control parent, string text) : this()
+               {
                        Text=text;
                        Parent=parent;
                }
 
-               public Control(Control parent, string text, int left, int top, int width, int height) : this() {
+               public Control (Control parent, string text, int left, int top, int width, int height) : this()
+               {
                        Parent=parent;
                        bounds.X=left;
                        bounds.Y=top;
@@ -981,11 +1030,13 @@ namespace System.Windows.Forms
                        Text=text;
                }
 
-               public Control(string text) : this() {
+               public Control (string text) : this()
+               {
                        Text=text;
                }
 
-               public Control(string text, int left, int top, int width, int height) : this() {
+               public Control (string text, int left, int top, int width, int height) : this()
+               {
                        bounds.X=left;
                        bounds.Y=top;
                        bounds.Width=width;
@@ -996,7 +1047,8 @@ namespace System.Windows.Forms
 
                private delegate void RemoveDelegate(object c);
 
-               protected override void Dispose(bool disposing) {
+               protected override void Dispose (bool disposing)
+               {
                        if (!is_disposed && disposing) {
                                Capture = false;
 
@@ -1012,8 +1064,8 @@ namespace System.Windows.Forms
                                }
                                
                                if (this.InvokeRequired) {
-                                       if (Application.MessageLoop) {
-                                               this.BeginInvokeInternal(new MethodInvoker(DestroyHandle), null, true);
+                                       if (Application.MessageLoop && IsHandleCreated) {
+                                               this.BeginInvokeInternal(new MethodInvoker(DestroyHandle), null);
                                        }
                                } else {
                                        DestroyHandle();
@@ -1036,6 +1088,26 @@ namespace System.Windows.Forms
                #endregion      // Public Constructors
 
                #region Internal Properties
+               // Control is currently selected, like Focused, except maintains state
+               // when Form loses focus
+               internal bool InternalSelected {
+                       get {
+                               IContainerControl container;
+                       
+                               container = GetContainerControl();
+                               
+                               if (container != null && container.ActiveControl == this)
+                                       return true;
+                                       
+                               return false;
+                       }
+               }
+               
+               // Mouse is currently within the control's bounds
+               internal bool Entered {
+                       get { return this.is_entered; }
+               }
+
                internal bool VisibleInternal {
                        get { return is_visible; }
                }
@@ -1064,6 +1136,9 @@ namespace System.Windows.Forms
                                }
                        }
                }
+               
+               internal Size InternalClientSize { set { this.client_size = value; } }
+               internal virtual bool ActivateOnShow { get { return true; } }
                #endregion      // Internal Properties
 
                #region Private & Internal Methods
@@ -1090,24 +1165,18 @@ namespace System.Windows.Forms
                }
 #endif
 
-               internal IAsyncResult BeginInvokeInternal (Delegate method, object [] args, bool disposing) {
+               internal IAsyncResult BeginInvokeInternal (Delegate method, object [] args) {
+                       return BeginInvokeInternal (method, args, FindControlToInvokeOn ());
+               }
+
+               internal IAsyncResult BeginInvokeInternal (Delegate method, object [] args, Control control) {
                        AsyncMethodResult       result;
                        AsyncMethodData         data;
 
-                       if (!disposing) {
-                               Control 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.Handle = window.Handle;
+                       data.Handle = control.Handle;
                        data.Method = method;
                        data.Args = args;
                        data.Result = result;
@@ -1152,6 +1221,21 @@ namespace System.Windows.Forms
                                return bmp_g;
                        }
                }
+               
+               private Control FindControlToInvokeOn ()
+               {
+                       Control p = this;
+                       do {
+                               if (p.IsHandleCreated)
+                                       break;
+                               p = p.parent;
+                       } while (p != null);
+
+                       if (p == null || !p.IsHandleCreated)
+                               throw new InvalidOperationException ("Cannot call Invoke or BeginInvoke on a control until the window handle is created");
+                       
+                       return p;
+               }
 
                private void InvalidateBackBuffer () {
                        if (backbuffer != null)
@@ -1572,6 +1656,7 @@ namespace System.Windows.Forms
                                        OnClick(EventArgs.Empty);
 #else
                                        OnDoubleClick(me);
+                                       OnMouseDoubleClick (me);
                                } else {
                                        OnClick(me);
                                        OnMouseClick (me);
@@ -1622,7 +1707,7 @@ namespace System.Windows.Forms
                                XplatUI.SetParent(Handle,
                                                  (new_parent == null || !new_parent.IsHandleCreated) ? IntPtr.Zero : new_parent.Handle);
                                if (this is Form ) {
-                                       XplatUI.SetWindowStyle (Handle, CreateParams);
+                                       ((Form) this).ChangingParent (new_parent);
                                }
                        }
 
@@ -1664,11 +1749,27 @@ namespace System.Windows.Forms
                        }
                }
 
+               // Sometimes we need to do this calculation without it being virtual (constructor)
+               internal Size InternalSizeFromClientSize (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;
+               }
+
                private void UpdateDistances() {
                        if (parent != null) {
-                               if (bounds.Width > 0)
+                               if (bounds.Width >= 0)
                                        dist_right = parent.ClientSize.Width - bounds.X - bounds.Width;
-                               if (bounds.Height > 0)
+                               if (bounds.Height >= 0)
                                        dist_bottom = parent.ClientSize.Height - bounds.Y - bounds.Height;
                        }
                }
@@ -1760,11 +1861,15 @@ namespace System.Windows.Forms
                [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
                public string AccessibleDefaultActionDescription {
                        get {
-                               return AccessibilityObject.default_action;
+                               if (accessibility_object != null)
+                                       return accessibility_object.default_action;
+                               else
+                                       return null;
                        }
 
                        set {
-                               AccessibilityObject.default_action=value;
+                               if (accessibility_object != null)
+                                       accessibility_object.default_action = value;
                        }
                }
 
@@ -1773,11 +1878,15 @@ namespace System.Windows.Forms
                [MWFCategory("Accessibility")]
                public string AccessibleDescription {
                        get {
-                               return AccessibilityObject.description;
+                               if (accessibility_object != null)
+                                       return accessibility_object.description;
+                               else
+                                       return null;
                        }
 
                        set {
-                               AccessibilityObject.description=value;
+                               if (accessibility_object != null)
+                                       accessibility_object.description = value;
                        }
                }
 
@@ -1786,11 +1895,15 @@ namespace System.Windows.Forms
                [MWFCategory("Accessibility")]
                public string AccessibleName {
                        get {
-                               return AccessibilityObject.Name;
+                               if (accessibility_object != null)
+                                       return accessibility_object.Name;
+                               else
+                                       return null;
                        }
 
                        set {
-                               AccessibilityObject.Name=value;
+                               if (accessibility_object != null)
+                                       accessibility_object.Name = value;
                        }
                }
 
@@ -1798,11 +1911,15 @@ namespace System.Windows.Forms
                [MWFDescription("Role of the control"), MWFCategory("Accessibility")]
                public AccessibleRole AccessibleRole {
                        get {
-                               return AccessibilityObject.role;
+                               if (accessibility_object != null)
+                                       return accessibility_object.role;
+                               else
+                                       return AccessibleRole.Default;
                        }
 
                        set {
-                               AccessibilityObject.role=value;
+                               if (accessibility_object != null)
+                                       accessibility_object.role = value;
                        }
                }
 
@@ -2066,9 +2183,10 @@ namespace System.Windows.Forms
                                if (value != is_captured) {
                                        if (value) {
                                                is_captured = true;
-                                               XplatUI.GrabWindow(this.Handle, IntPtr.Zero);
+                                               XplatUI.GrabWindow(Handle, IntPtr.Zero);
                                        } else {
-                                               XplatUI.UngrabWindow(this.Handle);
+                                               if (IsHandleCreated)
+                                                       XplatUI.UngrabWindow(Handle);
                                                is_captured = false;
                                        }
                                }
@@ -2536,13 +2654,14 @@ namespace System.Windows.Forms
                [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
                public bool IsHandleCreated {
                        get {
-                               if ((window != null) && (window.Handle != IntPtr.Zero)) {
-                                       Hwnd hwnd = Hwnd.ObjectFromHandle (window.Handle);
-                                       if (hwnd != null && !hwnd.zombie)
-                                               return true;
-                               }
+                               if (window == null || window.Handle == IntPtr.Zero)
+                                       return false;
 
-                               return false;
+                               Hwnd hwnd = Hwnd.ObjectFromHandle (window.Handle);
+                               if (hwnd != null && hwnd.zombie)
+                                       return false;
+
+                               return true;
                        }
                }
 
@@ -2669,6 +2788,9 @@ namespace System.Windows.Forms
                                // set. 
                                if (attrs != null && attrs.Length > 0)
                                        a = (AssemblyProductAttribute) attrs [0];
+                               if (a == null) {
+                                       return GetType ().Namespace;
+                               }
                                return a.Product;
                        }
                }
@@ -2924,13 +3046,8 @@ namespace System.Windows.Forms
                [Browsable(false)]
                [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
                public IWindowTarget WindowTarget {
-                       get {
-                               return null;
-                       }
-
-                       set {
-                               ;       // MS Internal
-                       }
+                       get { return window_target; }
+                       set { window_target = value; }
                }
                #endregion      // Public Instance Properties
 
@@ -2976,7 +3093,7 @@ namespace System.Windows.Forms
 
 
                                create_params.ClassName = XplatUI.DefaultClassName;
-                               create_params.ClassStyle = 0;
+                               create_params.ClassStyle = (int)(XplatUIWin32.ClassStyle.CS_OWNDC | XplatUIWin32.ClassStyle.CS_DBLCLKS);
                                create_params.ExStyle = 0;
                                create_params.Param = 0;
 
@@ -3137,7 +3254,7 @@ namespace System.Windows.Forms
                        object [] prms = null;
                        if (method is EventHandler)
                                prms = new object [] { this, EventArgs.Empty };
-                       return BeginInvokeInternal(method, prms, false);
+                       return BeginInvokeInternal(method, prms);
                }
 
                [EditorBrowsable(EditorBrowsableState.Advanced)]
@@ -3147,14 +3264,14 @@ namespace System.Windows.Forms
                public IAsyncResult BeginInvoke (Delegate method, object[] args)
 #endif
                {
-                       return BeginInvokeInternal (method, args, false);
+                       return BeginInvokeInternal (method, args);
                }
 
                public void BringToFront() {
                        if (parent != null) {
                                parent.child_controls.SetChildIndex(this, 0);
-                               parent.Refresh();
-                       } else {
+                       }
+                       else if (IsHandleCreated) {
                                XplatUI.SetZOrder(Handle, IntPtr.Zero, false, false);
                        }
                }
@@ -3177,27 +3294,23 @@ namespace System.Windows.Forms
                                return;
                        }
 
+                       if (!is_visible) {
+                               return;
+                       }
+                       
                        if (!IsHandleCreated) {
                                CreateHandle();
                        }
 
                        if (!is_created) {
                                is_created = true;
-                       }
-
-                       Control [] controls = child_controls.GetAllControls ();
-                       for (int i=0; i<controls.Length; i++) {
-                               if (controls [i].is_visible)
-                                       controls [i].CreateControl ();
-                       }
 
-                       UpdateChildrenZOrder();
+                               if (binding_context == null) {  // seem to be sent whenever it's null?
+                                       OnBindingContextChanged(EventArgs.Empty);
+                               }
 
-                       if (binding_context == null) {  // seem to be sent whenever it's null?
-                               OnBindingContextChanged(EventArgs.Empty);
+                               OnCreateControl();
                        }
-
-                       OnCreateControl();
                }
 
                public Graphics CreateGraphics() {
@@ -3208,7 +3321,10 @@ namespace System.Windows.Forms
                }
 
                public DragDropEffects DoDragDrop(object data, DragDropEffects allowedEffects) {
-                       return XplatUI.StartDrag(this.window.Handle, data, allowedEffects);
+                       if (IsHandleCreated)
+                               return XplatUI.StartDrag(Handle, data, allowedEffects);
+                       else
+                               return DragDropEffects.None;
                }
 
                [EditorBrowsable(EditorBrowsableState.Advanced)]
@@ -3233,7 +3349,11 @@ namespace System.Windows.Forms
                [EditorBrowsable (EditorBrowsableState.Advanced)]
 #endif
                public bool Focus() {
-                       if (CanFocus && IsHandleCreated && !has_focus && !is_focusing) {
+                       return FocusInternal (false);
+               }
+
+               internal virtual bool FocusInternal (bool skip_check) {
+                       if (skip_check || (CanFocus && IsHandleCreated && !has_focus && !is_focusing)) {
                                is_focusing = true;
                                Select(this);
                                is_focusing = false;
@@ -3241,13 +3361,11 @@ namespace System.Windows.Forms
                        return has_focus;
                }
 
-               internal void FocusInternal () {
-                       is_focusing = true;
-                       Select(this);
-                       is_focusing = false;
-               }
-
                public Control GetChildAtPoint(Point pt) {
+                       // MS's version causes the handle to be created.  The stack trace shows that get_Handle is called here, but
+                       // we'll just call CreateHandle instead.
+                       CreateHandle ();
+                       
                        // Microsoft's version of this function doesn't seem to work, so I can't check
                        // if we only consider children or also grandchildren, etc.
                        // I'm gonna say 'children only'
@@ -3365,26 +3483,18 @@ namespace System.Windows.Forms
 
                        return Invoke(method, prms);
                }
-
+#if NET_2_0
+               public object Invoke (Delegate method, params object [] args) {
+#else
                public object Invoke (Delegate method, object[] args) {
+#endif
+                       Control control = FindControlToInvokeOn ();
+                       
                        if (!this.InvokeRequired) {
                                return method.DynamicInvoke(args);
                        }
 
-                       IAsyncResult result = BeginInvoke (method, args);
-                       return EndInvoke(result);
-               }
-
-               internal object InvokeInternal (Delegate method, bool disposing) {
-                       return InvokeInternal(method, null, disposing);
-               }
-
-               internal object InvokeInternal (Delegate method, object[] args, bool disposing) {
-                       if (!this.InvokeRequired) {
-                               return method.DynamicInvoke(args);
-                       }
-
-                       IAsyncResult result = BeginInvokeInternal (method, args, disposing);
+                       IAsyncResult result = BeginInvokeInternal (method, args, control);
                        return EndInvoke(result);
                }
 
@@ -3481,7 +3591,7 @@ namespace System.Windows.Forms
                }
 
                public virtual void Refresh() {
-                       if (IsHandleCreated) {
+                       if (IsHandleCreated && Visible) {
                                Invalidate();
                                XplatUI.UpdateWindow(window.Handle);
 
@@ -3500,7 +3610,8 @@ namespace System.Windows.Forms
 
                [EditorBrowsable(EditorBrowsableState.Never)]
                public void ResetBindings() {
-                       data_bindings.Clear();
+                       if (data_bindings != null)
+                               data_bindings.Clear();
                }
 
                [EditorBrowsable(EditorBrowsableState.Never)]
@@ -3577,8 +3688,8 @@ namespace System.Windows.Forms
 #if DebugFocus
                private void printTree(Control c, string t) {
                        foreach(Control i in c.child_controls) {
-                               Console.WriteLine("{2}{0}.TabIndex={1}", i, i.tab_index, t);
-                               printTree(i, t+"\t");
+                               Console.WriteLine ("{2}{0}.TabIndex={1}", i, i.tab_index, t);
+                               printTree (i, t+"\t");
                        }
                }
 #endif
@@ -3641,17 +3752,12 @@ namespace System.Windows.Forms
                        }
 
                        SetBoundsCore(x, y, width, height, specified);
-                       if (parent != null) {
+                       if (parent != null)
                                parent.PerformLayout(this, "Bounds");
-                       }
                }
 
                public void Show () {
-                       if (!is_created) {
-                               this.CreateControl();
-                       }
-
-                       this.Visible=true;
+                       this.Visible = true;
                }
 
                public void SuspendLayout() {
@@ -3667,13 +3773,29 @@ namespace System.Windows.Forms
 
                #region Protected Instance Methods
                [EditorBrowsable(EditorBrowsableState.Advanced)]
-               [MonoTODO("Implement this and tie it into Control.ControlAccessibleObject.NotifyClients")]
                protected void AccessibilityNotifyClients(AccessibleEvents accEvent, int childID) {
-                       throw new NotImplementedException();
+                       // turns out this method causes handle
+                       // creation in 1.1.  at first I thought this
+                       // would be accomplished just by using
+                       // get_AccessibilityObject, which would route
+                       // through CreateAccessibilityInstance, which
+                       // calls CreateControl.  This isn't the case,
+                       // though (as overriding
+                       // CreateAccessibilityInstance and adding a
+                       // CWL shows nothing.  So we fudge it and put
+                       // a CreateHandle here.
+
+#if ONLY_1_1
+                       CreateHandle ();
+#endif
+
+                       if (accessibility_object != null && accessibility_object is ControlAccessibleObject)
+                               ((ControlAccessibleObject)accessibility_object).NotifyClients (accEvent, childID);
                }
 
                [EditorBrowsable(EditorBrowsableState.Advanced)]
                protected virtual AccessibleObject CreateAccessibilityInstance() {
+                       CreateControl ();
                        return new Control.ControlAccessibleObject(this);
                }
 
@@ -3692,16 +3814,16 @@ namespace System.Windows.Forms
                                return;
                        }
 
-                       window.CreateHandle(CreateParams);
+                       CreateParams create_params = CreateParams;
+                       window.CreateHandle(create_params);
 
                        if (window.Handle != IntPtr.Zero) {
                                creator_thread = Thread.CurrentThread;
 
                                XplatUI.EnableWindow(window.Handle, is_enabled);
-                               XplatUI.SetVisible(window.Handle, is_visible, true);
 
                                if (clip_region != null) {
-                                       XplatUI.SetClipRegion(Handle, clip_region);
+                                       XplatUI.SetClipRegion(window.Handle, clip_region);
                                }
 
                                // Set our handle with our parent
@@ -3709,25 +3831,14 @@ namespace System.Windows.Forms
                                        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].RecreatingHandle)
-                                               XplatUI.SetParent(children[i].Handle, window.Handle); 
-                               }
-
                                UpdateStyles();
-                               XplatUI.SetAllowDrop (Handle, allow_drop);
+                               XplatUI.SetAllowDrop (window.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);
                        }
                }
 
@@ -3748,7 +3859,8 @@ namespace System.Windows.Forms
 #if NET_2_0
                protected virtual AccessibleObject GetAccessibilityObjectById (int objectId)
                {
-                       throw new NotImplementedException ();
+                       // XXX need to implement this.
+                       return null;
                }
 #endif
 
@@ -3789,6 +3901,9 @@ namespace System.Windows.Forms
                }
 
                protected virtual bool IsInputChar (char charCode) {
+                       // XXX on MS.NET this method causes the handle to be created..
+                       CreateHandle ();
+
                        return true;
                }
 
@@ -3921,6 +4036,9 @@ namespace System.Windows.Forms
 
                [EditorBrowsable(EditorBrowsableState.Advanced)]
                protected void RecreateHandle() {
+                       if (!IsHandleCreated)
+                               return;
+
 #if DebugRecreate
                        Console.WriteLine("Recreating control {0}", XplatUI.Window(window.Handle));
 #endif
@@ -4101,7 +4219,7 @@ namespace System.Windows.Forms
 
                [EditorBrowsable(EditorBrowsableState.Advanced)]
                protected virtual void SetClientSizeCore(int x, int y) {
-                       Size NewSize = SizeFromClientSize (new Size (x, y));
+                       Size NewSize = InternalSizeFromClientSize (new Size (x, y));
                        
                        if (NewSize != Size.Empty)
                                SetBounds (bounds.X, bounds.Y, NewSize.Width, NewSize.Height, BoundsSpecified.Size);
@@ -4122,53 +4240,34 @@ namespace System.Windows.Forms
                        }
 
                        if (this is Form) {
-                               if (value == true) {
-                                       if (!Visible) {
-                                               Visible = true;
-                                       }
-                               } else {
-                                       if (Visible) {
-                                               Visible = false;
-                                       }
+                               if (IsHandleCreated && value != Visible) {
+                                       Visible = value;
                                }
+                       } else {
+                               // XXX MS.NET causes handle to be created here
+                               CreateHandle ();
                        }
                        is_toplevel = value;
                }
 
                protected virtual void SetVisibleCore(bool value) {
-                       if (value!=is_visible) {
-                               is_visible=value;
+                       if (value != is_visible) {
+                               is_visible = value;
                                
-                               if (value && ((window.Handle == IntPtr.Zero) || !is_created)) {
+                               if (is_visible && ((window.Handle == IntPtr.Zero) || !is_created)) {
                                        CreateControl();
                                }
 
                                if (IsHandleCreated) {
-                                       XplatUI.SetVisible(Handle, value, true);
+                                       XplatUI.SetVisible(Handle, is_visible, true);
                                        // Explicitly move Toplevel windows to where we want them;
                                        // apparently moving unmapped toplevel windows doesn't work
                                        if (is_visible && (this is Form)) {
                                                XplatUI.SetWindowPos(window.Handle, bounds.X, bounds.Y, bounds.Width, bounds.Height);
                                        }
                                }
-
-                               OnVisibleChanged(EventArgs.Empty);
-
-                               if (value == false && parent != null && Focused) {
-                                       Control container;
-
-                                       // Need to start at parent, GetContainerControl might return ourselves if we're a container
-                                       container = (Control)parent.GetContainerControl();
-                                       if (container != null) {
-                                               container.SelectNextControl(this, true, true, true, true);
-                                       }
-                               }
-
-                               if (parent != null) {
-                                       parent.PerformLayout(this, "visible");
-                               } else {
-                                       if (is_visible)
-                                               PerformLayout(this, "visible");
+                               else {
+                                       OnVisibleChanged(EventArgs.Empty);
                                }
                        }
                }
@@ -4180,21 +4279,14 @@ namespace System.Windows.Forms
                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;
+                       return InternalSizeFromClientSize (clientSize);
                }
 
                [EditorBrowsable(EditorBrowsableState.Advanced)]
                protected void UpdateBounds() {
+                       if (!IsHandleCreated)
+                               return;
+
                        int     x;
                        int     y;
                        int     width;
@@ -4202,10 +4294,6 @@ namespace System.Windows.Forms
                        int     client_width;
                        int     client_height;
 
-                       if (!IsHandleCreated) {
-                               CreateHandle();
-                       }
-
                        XplatUI.GetWindowPos(this.Handle, this is Form, out x, out y, out width, out height, out client_width, out client_height);
 
                        UpdateBounds(x, y, width, height, client_width, client_height);
@@ -4300,16 +4388,43 @@ namespace System.Windows.Forms
                        return IntPtr.Zero;
                }
 
-               private void UpdateChildrenZOrder() {
+               // internal because we need to call it from ScrollableControl.OnVisibleChanged
+               internal void UpdateChildrenZOrder() {
                        Control [] controls;
 
                        if (!IsHandleCreated) {
                                return;
                        }
 
+                       // XXX This code is severely broken.  It leaks
+                       // the "zero_sized" abstraction out of the X11
+                       // backend and into Control.cs.  It'll work on
+                       // windows simply by virtue of windows never
+                       // setting that field to true.
+                       //
+                       // basically what we need to guard against is
+                       // calling XplatUI.SetZOrder on an hwnd that
+                       // corresponds to an unmapped X window.
                        controls = child_controls.GetAllControls ();
-                       for (int i = 1; i < controls.Length; i++ ) {
-                               XplatUI.SetZOrder(controls[i].Handle, controls[i-1].Handle, false, false);
+
+                       ArrayList children_to_order = new ArrayList ();
+
+                       for (int i = 0; i < controls.Length; i ++) {
+                               if (!controls[i].IsHandleCreated || !controls[i].VisibleInternal)
+                                       continue;
+
+                               Hwnd hwnd = Hwnd.ObjectFromHandle (controls[i].Handle);
+                               if (hwnd.zero_sized)
+                                       continue;
+
+                               children_to_order.Add (controls[i]);
+                       }
+
+                       for (int i = 1; i < children_to_order.Count; i ++) {
+                               Control upper = (Control)children_to_order[i-1];
+                               Control lower = (Control)children_to_order[i];
+
+                               XplatUI.SetZOrder(lower.Handle, upper.Handle, false, false);
                        }
                }
 
@@ -4416,12 +4531,22 @@ namespace System.Windows.Forms
                                        return;
                                }
 
+                               case Msg.WM_SHOWWINDOW: {
+                                       WmShowWindow (ref m);
+                                       return;
+                               }
+
+                               case Msg.WM_CREATE: {
+                                       WmCreate (ref m);
+                                       return;
+                               }
+
                                case Msg.WM_MOUSE_ENTER: {
                                        WmMouseEnter (ref m);
                                        return;
                                }
 
-                               case Msg.WM_MOUSE_LEAVE: {
+                               case Msg.WM_MOUSELEAVE: {
                                        WmMouseLeave (ref m);
                                        return;
                                }
@@ -4487,17 +4612,17 @@ namespace System.Windows.Forms
                private void WmDestroy (ref Message m) {
                        OnHandleDestroyed(EventArgs.Empty);
 #if DebugRecreate
-                               IntPtr handle = window.Handle;
+                       IntPtr handle = window.Handle;
 #endif
                        window.InvalidateHandle();
 
                        if (is_recreating) {
 #if DebugRecreate
-                                       Console.WriteLine ("Creating handle for {0:X}", handle.ToInt32());
+                               Console.WriteLine ("Creating handle for {0:X}", handle.ToInt32());
 #endif
                                CreateHandle();
 #if DebugRecreate
-                                       Console.WriteLine (" + new handle = {0:X}", Handle.ToInt32());
+                               Console.WriteLine (" + new handle = {0:X}", Handle.ToInt32());
 #endif
                                is_recreating = false;
                        }
@@ -4521,33 +4646,35 @@ namespace System.Windows.Forms
                private void WmPaint (ref Message m) {
                        PaintEventArgs  paint_event;
 
-                       paint_event = XplatUI.PaintEventStart(Handle, true);
+                       IntPtr handle = Handle;
+
+                       paint_event = XplatUI.PaintEventStart (handle, true);
 
-                       if (paint_event == null) {
+                       if (paint_event == null)
                                return;
-                       }
+
                        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);
+                                       XplatUI.PaintEventEnd (handle, true);
                                        return;
                                }
                                current_buffer.Start (paint_event);
                        }
                                
                        if (!GetStyle(ControlStyles.Opaque)) {
-                               OnPaintBackground(paint_event);
+                               OnPaintBackground (paint_event);
                        }
 
                        // Button-derived controls choose to ignore their Opaque style, give them a chance to draw their background anyways
-                       OnPaintBackgroundInternal(paint_event);
+                       OnPaintBackgroundInternal (paint_event);
 
                        OnPaintInternal(paint_event);
                        if (!paint_event.Handled) {
-                               OnPaint(paint_event);
+                               OnPaint (paint_event);
                        }
 
                        if (current_buffer != null) {
@@ -4555,8 +4682,7 @@ namespace System.Windows.Forms
                        }
 
 
-                       XplatUI.PaintEventEnd(Handle, true);
-
+                       XplatUI.PaintEventEnd (handle, true);
                }
 
                private void WmEraseBackground (ref Message m) {
@@ -4714,6 +4840,10 @@ namespace System.Windows.Forms
                        DefWndProc(ref m);
                }
 
+               private void WmCreate (ref Message m) {
+                       OnHandleCreated(EventArgs.Empty);
+               }
+
                private void WmMouseWheel (ref Message m) {
                        DefWndProc(ref m);
                        OnMouseWheel (new MouseEventArgs (FromParamToMouseButtons ((int) m.WParam.ToInt32()), 
@@ -4746,6 +4876,34 @@ namespace System.Windows.Forms
                        OnMouseHover(EventArgs.Empty);
                }
 
+               private void WmShowWindow (ref Message m) {
+                       if (m.WParam.ToInt32() != 0) {
+                               CreateControl ();
+                               /* if we're being shown, make sure our child controls all have their handles created */
+                               Control [] controls = child_controls.GetAllControls ();
+                               for (int i=0; i<controls.Length; i++) {
+                                       if (controls [i].is_visible) {
+                                               controls [i].CreateControl ();
+                                               XplatUI.SetParent(controls[i].Handle, window.Handle); 
+                                       }
+                               }
+                       }
+                       else {
+                               if (parent != null && Focused) {
+                                       Control container;
+
+                                       // Need to start at parent, GetContainerControl might return ourselves if we're a container
+                                       container = (Control)parent.GetContainerControl();
+                                       if (container != null) {
+                                               container.SelectNextControl(this, true, true, true, true);
+                                       }
+                               }
+                       }
+
+                       if (is_toplevel || (this is Form && ((Form) this).IsMdiChild)) /* XXX make sure this works for mdi forms */
+                               OnVisibleChanged(EventArgs.Empty);
+               }
+
                private void WmSysKeyUp (ref Message m) {
                        if (ProcessKeyMessage(ref m)) {
                                m.Result = IntPtr.Zero;
@@ -5438,13 +5596,6 @@ namespace System.Windows.Forms
 
                [EditorBrowsable(EditorBrowsableState.Advanced)]
                protected virtual void OnVisibleChanged(EventArgs e) {
-                       if ((parent != null) && !Created && Visible) {
-                               if (!is_disposed) {
-                                       CreateControl();
-                                       PerformLayout();
-                               }
-                       }
-
                        EventHandler eh = (EventHandler)(Events [VisibleChangedEvent]);
                        if (eh != null)
                                eh (this, e);