views:

127

answers:

2

I am attempting to move all controls on a form down or up by the height of a menubar depending on whether it is visible or not. I have code which I think ought to work well for this, however it seems that Me.Controls is empty at runtime, so my for each loop is never entered. Could someone please offer a suggestion as to how I can move the controls?

Private Sub uxMenuStrip_VisibleChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles uxMenuStrip.VisibleChanged
    For Each control As Control In Me.Controls
        If control.Name <> "uxMenuStrip" Then
            Dim temp As AnchorStyles = control.Anchor
            control.Anchor = AnchorStyles.None
            control.Top -= ((CInt(uxMenuStrip.Visible) * 2 - 1) * uxMenuStrip.Height)
            control.Anchor = temp
        End If
    Next
    Me.Height += ((CInt(uxMenuStrip.Visible) * 2 - 1) * uxMenuStrip.Height)
End Sub
+1  A: 

Try this:

Private Sub uxMenuStrip_VisibleChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles uxMenuStrip.VisibleChanged
    Dim menu As Control = sender
    Dim dh As Integer = IIf(menu.Visible, 1, -1) * menu.Height
    For Each control As Control In Controls
        If control.Parent Is Me And Not control Is menu Then
            control.Top += dh
        End If
    Next
    Height += dh
End Sub

Update: Anyway, i strongly recomment using container, in case with MenuStrip - ToolStripContainer.

max
+1 for `IIf()`. I missed the ternary operator when I started doing VB.
Caleb Thompson
+1  A: 

As Michael Todd points out, Me.Controls can't be empty. Also, this might not work as well as you're thinking. Controls on WinForms apps are hierarchical. The only way to do this 100% cleanly is to make the move code recursive. IE, perform the same operation on every control in each control's controls collection. (Now I'm sounding like Dr. Seuss...) If your form is simple, this wouldn't be an issue, obviously.

At the end of the day, though, you'll probably be better off just putting everything on the form inside a Panel and just moving the Panel control explicitly by name. It would make what you're trying to do more clear.

Tim Coker
+1, use a Panel. Move the panel.
Hans Passant
Ended up using the panel and a `IIF()`
Caleb Thompson