在vb.net 2010中锚定表单

时间:2014-01-09 00:06:59

标签: winforms anchor vb.net-2010

我的问题是如何将子mdi锚定到其父级mdi,以便每次用户扩展或最小化子窗体自动跟随的父窗体时。我已经尝试在表单中使用resize函数,但它没有帮助 谢谢所有的帮助是适当的

2 个答案:

答案 0 :(得分:0)

见下文 - 我写的快速版本,似乎可以处理大多数锚定方案。您可能需要稍微修改一下这段代码。但这应该让你开始:

Imports System.ComponentModel

Public Class MDIChildForm
  Dim p_eMyAnchor As AnchorStyles
  Dim p_mdiParent As Form

  Dim p_iOldHeight, p_iOldWidth As Integer

  <DefaultValue(AnchorStyles.Left Or AnchorStyles.Top)>
  Public Property MyAnchor As AnchorStyles
    Get
      Return p_eMyAnchor
    End Get
    Set(value As AnchorStyles)
      p_eMyAnchor = value
      chkAnchorTop.Checked = (p_eMyAnchor And AnchorStyles.Top)
      chkAnchorLeft.Checked = (p_eMyAnchor And AnchorStyles.Left)
      chkAnchorRight.Checked = (p_eMyAnchor And AnchorStyles.Right)
      chkAnchorBottom.Checked = (p_eMyAnchor And AnchorStyles.Bottom)
    End Set
  End Property

  Sub New()
    ' This call is required by the designer.
    InitializeComponent()

    ' Add any initialization after the InitializeComponent() call.
    p_eMyAnchor = AnchorStyles.Left Or AnchorStyles.Top
  End Sub

  Public Sub ShowAsMDIChild(mdiParent As Form)
    p_mdiParent = mdiParent
    Me.MdiParent = mdiParent
    AddHandler mdiParent.ResizeBegin, AddressOf MDIParentForm_ResizeBegin
    AddHandler mdiParent.ResizeEnd, AddressOf MDIParentForm_ResizeEnd
    Me.Show()
  End Sub

  Private Sub MDIParentForm_ResizeBegin(sender As Object, e As EventArgs)
    Dim frm As Form = DirectCast(sender, Form)
    p_iOldWidth = frm.Width
    p_iOldHeight = frm.Height
  End Sub

  Private Sub MDIParentForm_ResizeEnd(sender As Object, e As EventArgs)
    Dim parentForm As Form = DirectCast(sender, Form)

    'handling for horizontal anchoring
    Dim deltaWidth As Integer = parentForm.Width - p_iOldWidth
    Dim fAnchorLeft As Boolean = p_eMyAnchor And AnchorStyles.Left
    Dim fAnchorRight As Boolean = p_eMyAnchor And AnchorStyles.Right

    Select Case fAnchorLeft
      Case True : If fAnchorRight Then Me.Width += deltaWidth
      Case False
        Dim coef As Single = If(fAnchorRight, 1, 0.5)
        Me.Left += deltaWidth * coef
    End Select

    'handling for vertical anchoring
    Dim deltaHeight As Integer = parentForm.Height - p_iOldHeight
    Dim fAnchorTop As Boolean = p_eMyAnchor And AnchorStyles.Top
    Dim fAnchorBottom As Boolean = p_eMyAnchor And AnchorStyles.Bottom

    Select Case fAnchorTop
      Case True : If fAnchorBottom Then Me.Height += deltaHeight
      Case False
        Dim coef As Single = If(fAnchorBottom, 1, 0.5)
        Me.Top += deltaHeight * coef
    End Select
  End Sub

End Class

对于水平锚定,使用以下规则:

  • left - 没有任何反应(默认行为)
  • 左右 - 将宽度展开为父窗体宽度增量
  • 右 - 向左移动父窗体宽度增量
  • 没有锚点 - 向左移动半父格式宽度增量。

同样的原则适用于垂直锚固,分别适用于顶部和底部。

您可以使用here (Mediafire)获取整个项目。

答案 1 :(得分:0)

试试这个:

Me.Anchor = AnchorStyles.Bottom
Me.Anchor = AnchorStyles.Left
Me.Anchor = AnchorStyles.Right
Me.Anchor = AnchorStyles.Top