开发者

Moving .NET controls at runtime

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
 开发者_如何学Go   Me.Height += ((CInt(uxMenuStrip.Visible) * 2 - 1) * uxMenuStrip.Height)
End Sub


Add a new Handler with Control and change location in address

 Public Sub ChngPostion(ByVal sender As System.Object, ByVal e As System.EventArgs)
      For Each cntrl As Control In Me.Controls
         If cntrl.Name = sender.Name Then
             cntrl.Location = New System.Drawing.Point(sender.Location.X,sender.Location.Y)
         End If
      Next
 End Sub


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜