【问题标题】:Wanting to allow only 2 of the same form to be opened VB6想要只允许打开 2 个相同的表单 VB6
【发布时间】:2014-02-07 00:02:40
【问题描述】:

到目前为止,我有一些代码允许用户点击 F1,它加载相同属性的新表单,然后隐藏他们第一个打开的表单,点击 F2,允许用户关闭新打开的表单并显示他们首先打开的那个。我想要一个限制,如果用户在打开 2 个相同表单的情况下按 F1,则只允许打开一个额外的表单,然后出现一个消息框,告诉他们先关闭第二个表单,否则允许打开它。

这是我目前所拥有的。

 Private Sub Form_Load()

 End Sub

 Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)

    Select Case KeyCode

        Case vbKeyF1
        'hides the current form
            Me.Hide
        'loads a new form with the same properties
            Dim f As New Form1
            Load f
        'shows this new form
            f.Show
        'says that the second form is open
            fOpen = True

        Case vbKeyF2
        'closes the second form
            Unload Me
        'says that the second form is closed
            fOpen = False
        'shows the first form you were on
            Form1.Show

    End Select
End Sub

Private Sub Form_QueryUnload(cancel As Integer, unloadmode As Integer)

   'if your hitting "X" on second form then just close form2
   If fOpen = False Then
   Form1.Show
   Else
   'if your hitting "X" on main form close everything
   Unload Me
   End If

End Sub

如果 fOpen = true 则不允许用户按 F1?不太确定,但我很接近。

【问题讨论】:

    标签: forms vb6 multiple-forms


    【解决方案1】:

    如果我的 VB6 有点偏离,请原谅我,但您需要枚举 Forms 集合以检查您的表单是否已经打开...

    Dim frm As Form
    For Each frm In Forms
        If frm.Name = "myForm" Then frm.Show()
    Next frm
    

    this

    -- 编辑--

    就在我考虑的时候,要调整您的代码,您可以使用数字迭代...

    Dim f As Integer
    Dim t As Integer
    t = Forms.Count - 1
    For f = 0 To t
        If Forms(f).Name = "myForm" Then Forms(f).Show()
    Next frm
    

    -- 编辑 2--

    只是对此的进一步说明。您可能还想引入一个计数器,以便您可以检查是否有两个字段,如您的原始帖子中...

    Dim frm As Form
    Dim c As Integer
    For Each frm In Forms
        If frm.Name = "myForm" Then 
            c = c + 1
            If c = 2 Then 
                frm.Show()
                Exit For 'Speed up the search if there are lots of forms
            End If
        End if
    Next frm
    

    【讨论】:

    • 您的第一个版本可能是两者中效率更高,外观最流畅的版本。
    • 其实不是。其背后的原因是必须在后台创建然后销毁枚举器,而第二种方法直接引用现有集合。 (编辑:虽然是的 - 第一种方式更具可读性)
    • 我可以看到您的逻辑,但请记住,访问 VB.Forms(n) 不是通过数组,而是通过方法调用。我们不知道 Forms 对象的实现。如果它本质上是一个动态数组,那么每个索引的访问时间将是相同的。如果它像 VB.Collection 一样,它是一个链表,访问时间与 n 成线性关系。无论如何,我决定对其进行测试。我创建了一个具有不同数量表格的测试工具,遍历集合并设置标题。总而言之,两种方法所用时间的差异小于测试变化。
    • 不幸的是我没有VB6,否则我会做一个速度测试,但看到差异会很有趣。 :o)
    • @MarkBertenshaw:VB6 集合在通过索引/键访问时是 O(1)。它们很可能是用哈希映射实现的,并且在通过索引/键查找时非常高效。在索引/键未命中时,是错误处理(填充Err 对象)减慢了它们的速度,而不是内部实现。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-25
    • 2020-08-11
    • 2021-12-03
    • 1970-01-01
    • 1970-01-01
    • 2018-12-26
    • 2019-06-29
    相关资源
    最近更新 更多