在表单内部安装运行时按钮

时间:2015-01-12 18:49:25

标签: vb.net

我有5到20之间的多个按钮,每次根据用户设置加载表单时它都是可变的。无论表单的大小如何,我都试图在表单上放置所有这些按钮。按钮在运行时生成。我想第一个按钮是从顶部栏(任意大小)20点,其余按钮只是适合表格。这就是我现在所拥有的,但是我必须最大限度地利用表格来查看它们,并且当我扩展形状时,按钮之间的空间减小并且它们彼此重叠,而它们应该保持相对距离。有什么想法吗?

    Dim iButtonWidth, iButtonHeight, iVerticalSpace As Integer

    If UserButtons.Count > 0 Then
        iButtonHeight = Me.Size.Height - (Me.Size.Height * 0.85)
        iButtonWidth = Me.Size.Width - (Me.Size.Width * 0.5)
        iVerticalSpace = iButtonHeight / 3
        For Each btn In UserButtons
            btn.Size = New System.Drawing.Size(iButtonWidth, iButtonHeight)
            btn.Location = New Point(20, 20 + btn.TabIndex * iVerticalSpace * 3)
        Next
    End If

1 个答案:

答案 0 :(得分:1)

以下是使用TableLayoutPanel进行游戏的简单示例:

TableLayoutPanel with 5 Columns and a Variable number of Rows

Public Class Form1

    Private UserButtons As New List(Of Button)

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Static R As New Random

        Dim NumButtons As Integer = R.Next(5, 21) ' "a number of buttons between 5-20 and it's variable each time"
        UserButtons.Clear()
        For i As Integer = 1 To NumButtons
            Dim btn As New Button()
            btn.Text = i.ToString("00")
            btn.Dock = DockStyle.Fill ' Optional: See how you like it with this on vs. off
            UserButtons.Add(btn)
        Next

        DisplayButtons()
    End Sub

    Private Sub DisplayButtons()
        TableLayoutPanel1.SuspendLayout()
        TableLayoutPanel1.Controls.Clear()

        TableLayoutPanel1.ColumnStyles.Clear()
        TableLayoutPanel1.ColumnCount = 5 ' Fixed Number of Columns
        For i As Integer = 1 To TableLayoutPanel1.ColumnCount
            TableLayoutPanel1.ColumnStyles.Add(New ColumnStyle(SizeType.Percent, 911)) ' the size doesn't matter here, as long as they are all the same
        Next

        ' Variable Number of Rows:
        Dim RowsRequired As Integer = ((UserButtons.Count - 1) \ TableLayoutPanel1.ColumnCount) + 1 ' Integer Division
        TableLayoutPanel1.RowStyles.Clear()
        TableLayoutPanel1.RowCount = RowsRequired
        For i As Integer = 1 To TableLayoutPanel1.RowCount
            TableLayoutPanel1.RowStyles.Add(New RowStyle(SizeType.Percent, 911)) ' the size doesn't matter here, as long as they are all the same
        Next

        TableLayoutPanel1.Controls.AddRange(UserButtons.ToArray)
        TableLayoutPanel1.ResumeLayout()
    End Sub

End Class