我收到了一些关于将命令按钮的标题用作状态变量的上一个问题 (How to gracefully exit from the middle of a nested subroutine when user cancels?) 的合理批评反馈。我这样做是因为它很高效,用很少的代码同时服务于两个或三个目的,但我理解它也可能导致问题,特别是在我最初提出它时有点草率的方式。
我觉得这值得自己讨论,所以这里有相同的想法清理了一下并修改为“正确”(这基本上意味着在一个地方定义字符串,这样你的代码就不会开始失败,因为你只是改变了命令按钮的文本)。我知道我的变量和控件命名约定很差(好吧,不存在),所以提前道歉。但我想继续关注标题作为状态变量的讨论。
所以我们开始:
' Global variables for this form
Dim DoTheThingCaption(1) As String
Dim UserCancel, FunctionCompleted As Boolean
Private Sub Form_Initialize()
' Define the possible captions (is there a #define equivalent for strings?)
DoTheThingCaption(0) = "Click to Start Doing the Thing"
DoTheThingCaption(1) = "Click to Stop Doing the Thing"
' Set the caption state when form initializes
DoTheThing.Caption = DoTheThingCaption(0)
End Sub
Private Sub DoTheThing_Click() ' Command Button
If DoTheThing.Caption = DoTheThingCaption(0) Then
UserCancel = False ' this is the first time we've entered this sub
Else ' We've re-entered this routine (user clicked on button again
' while this routine was already running), so we want to abort
UserCancel = True ' Set this so we'll see it when we exit this re-entry
DoTheThing.Enabled = False 'Prevent additional clicks
Exit Sub
End If
' Indicate that we're now Doing the Thing and how to cancel
DoTheThing.Caption = DoTheThingCaption(1)
For i = 0 To ReallyBigNumber
Call DoSomethingSomewhatTimeConsuming
If UserCancel = True Then Exit For ' Exit For Loop if requested
DoEvents ' Allows program to see GUI events
Next
' We've either finished or been canceled, either way
' we want to change caption back
DoTheThing.Caption = DoTheThingCaption(0)
If UserCancel = True Then GoTo Cleanup
'If we get to here we've finished successfully
FunctionCompleted = True
Exit Sub '******* We exit sub here if we didn't get canceled *******
Cleanup:
'We can only get to here if user canceled before function completed
FunctionCompleted = False
UserCancel = False ' clear this so we can reenter later
DoTheThing.Enabled = True 'Prevent additional clicks
End Sub '******* We exit sub here if we did get canceled *******
所以就是这样。这样做真的有那么糟糕吗?仅仅是风格问题吗?还有什么东西可以以更可取或可维护的方式为我提供这四件事吗?
我可以看到一个问题可能是代码和 GUI 之间的紧密耦合(以多种方式),所以我可以看到这对于大型项目(或至少是大型 GUI)如何成为一个大问题。这恰好是一个较小的项目,其中只有 2 或 3 个按钮可以接受这种“处理”。
最佳答案
这种技术的最大问题是它使用字符串作为 bool 值。根据定义, bool 变量只能有两种状态,而字符串可以有任意数量的状态。
现在,您已经通过依赖一组预定义字符串来定义命令按钮文本的允许值,在一定程度上减轻了这种固有的危险。这留下了一些较小的问题:
关于vb6 - 在 VB6 中使用按钮标题作为变量有什么不好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/596968/