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

时间:2017-11-08 21:38:14

标签: vb.net

我想问用户例如“你想要向右还是离开?” 为了获得简单的代码,我使用MSGBOX,提示符如下:

“你想要向右还是向左”

按'YES'表示'右'/ NO表示'左'“

然后我处理被按下的是/否/取消。这很有效,但有些难以理解。

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

2 个答案:

答案 0 :(得分:1)

  1. 您需要根据自己的需要创建自己的“自定义”msgbox表单,最好创建可重用的控件 - 通过自定义控件的构造函数传递“问题”字符串。
  2. 你需要一些“方法”让用户从你的自定义msgbox外面做出决定 - 一种方法就是使用https://www.example.com/path/ https://www.example.com/path/ Enum。
  3. 这是我刚才写的一个基本示例,用于演示,请参阅我在代码中添加的注释。

    使用2个表单创建一个新项目,Form1将是调用自定义msgbox的主窗体,Form2将是自定义msgbox:

    <强> Form1中:

    enter image description here

    <强>窗体2:

    enter image description here

    Form1的代码:

    DialogResult

    Form2的代码:

    Public Class Form1
        Private Sub btnOpenCustomMsgbox_Click(sender As Object, e As EventArgs) Handles btnOpenCustomMsgbox.Click
            Dim customMsgbox = New Form2("this is my custom msg, if you press yes i will do something if you press no i will do nothing")
            If customMsgbox.ShowDialog() = DialogResult.Yes Then
                ' do something
                MsgBox("I am doing some operation...")
            Else
                ' do nothing (its DialogResult.no)
                MsgBox("I am doing nothing...")
            End If
        End Sub
    End Class
    

    它可以更加复杂,但如果你探索这个例子,我希望你能理解这个概念。

答案 1 :(得分:1)

您可以动态创建一个

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

您会看到有关于存在哪些按钮,消息和标题的选项。

像这样使用

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

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

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

enter image description here

enter image description here