简单的对话框,如带自定义按钮的 msgbox (vb)

Vol*_*ker 4 vb.net

例如,我想问用户“你想向右走还是向左走?”。
为了获得简单的代码,我使用 MSGBOX 并带有如下提示:

“你想往右走还是往左走”

按“YES 表示‘右’/NO 表示‘左’”

然后我处理按下的是/否/取消。这可行,但很丑陋,并且在某些情况下难以理解。

另外,在某些情况下,我有两个以上的选择 - 但这可能是另一个问题......

djv*_*djv 6

您可以动态创建一个

Public Module CustomMessageBox
    Private result As String
    Public Function Show(options As IEnumerable(Of String), Optional message As String = "", Optional title As String = "") As String
        result = "Cancel"
        Dim myForm As New Form With {.Text = title}
        Dim tlp As New TableLayoutPanel With {.ColumnCount = 1, .RowCount = 2}
        Dim flp As New FlowLayoutPanel()
        Dim l As New Label With {.Text = message}
        myForm.Controls.Add(tlp)
        tlp.Dock = DockStyle.Fill
        tlp.Controls.Add(l)
        l.Dock = DockStyle.Fill
        tlp.Controls.Add(flp)
        flp.Dock = DockStyle.Fill
        For Each o In options
            Dim b As New Button With {.Text = o}
            flp.Controls.Add(b)
            AddHandler b.Click,
                Sub(sender As Object, e As EventArgs)
                    result = DirectCast(sender, Button).Text
                    myForm.Close()
                End Sub
        Next
        myForm.FormBorderStyle = FormBorderStyle.FixedDialog
        myForm.Height = 100
        myForm.ShowDialog()
        Return result
    End Function
End Module
Run Code Online (Sandbox Code Playgroud)

您会看到您可以选择显示哪些按钮、消息和标题。

像这样使用它

Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim result = CustomMessageBox.Show(
            {"Right", "Left"},
            "Do you want to go right or left?",
            "Confirm Direction")
        MessageBox.Show(result)
    End Sub
End Class
Run Code Online (Sandbox Code Playgroud)

在我的示例中,提示是"Do you want to go right or left?",选项是"Right""Left"

返回字符串而不是 DialogResult,因为现在您的选项是无限的 (!)。尝试适合您的套装的尺寸。

在此输入图像描述

在此输入图像描述