我有一个最初是 VB6 应用程序的应用程序(.net framework 4,vb.net)。为了模仿旧选项卡控件行为的一部分,我正在实现允许您切换到另一个选项卡的加速键。示例 - 带有 5 个选项卡的 TabControl。- 选项卡 2 有一个带有文本框的标签 &Data(alt-d 加速键) - 用户选择了选项卡 1,然后按 alt-d,这会导致选项卡控件选择选项卡 2 并将焦点设置到相应的文本框。
我编写了一些代码来查找包含控件的选项卡(我通过覆盖 ProcessMnemonic 来执行此操作)并简单地查看选项卡(从选定的选项卡开始),如果找到匹配项,我选择选项卡然后允许系统通过调用“MyBase.ProcessMnemonic(charCode)”来处理助记符。
但我的问题是 Control.IsMnemonic 调用。由于您只传递控件的“文本”,因此任何在其文本属性中包含 & 的控件都可能导致它成为匹配项。
例如, myTextbox.Text = "here &friend" 将导致 Alt-F 将焦点设置在该框上。
我可以明确地检查控件类型是否是标签......但是我还需要组框和......还有什么?按钮我也应该允许助记符......
这是一些代码(注意我没有包括选项卡迭代,因为它似乎不相关);
Private Function IsMnemonicInThisContainer(charCode As Char, controlContainer As System.Windows.Forms.Control.ControlCollection) As Boolean
For Each ctrl As Control In controlContainer
If Control.IsMnemonic(charCode, ctrl.Text) Then
If ControlIsAlive(ctrl) Then
Return True
End If
ElseIf ctrl.HasChildren Then
If ControlIsAlive(ctrl) AndAlso IsMnemonicInThisContainer(charCode, ctrl.Controls) Then
Return True
End If
End If
Next
Return False
End Function
Private Function ControlIsAlive(ctrl As Control) As Boolean
' In a TABPAGE that is not selected, the controls all appear to be visible = FALSE,
' because they aren't actually "visible" - HOWEVER... the control itself may be expecting
' to be visible (once it's tab is shown)... so this call to GetStateMethodInfo which I grabbed from
' http://stackoverflow.com/questions/3351371/using-control-visible-returns-false-if-its-on-a-tab-page-that-is-not-selected
' is the solution I needed.
' Instead of walking the tree though I am going to "check containers" as I drop into them... if they are not enabled/visible
' then I'm not going to go any deeper
' Is control enabled and going to be shown? (calling ctrl.visible allows us to bypass the other call if we can!)
Return (ctrl.Enabled AndAlso (ctrl.Visible OrElse CBool(GetStateMethodInfo.Invoke(ctrl, New Object() {2}))))
End Function
我想我可以做类似...
如果 Typeof ctrl 是 Label orelse Typeof ctrl is groupbox (etc...)...
但是确定这一点的属性(或方法)会很棒。有任何想法吗?
谢谢!克里斯伍德拉夫