向当前添加文本主动控制使用按钮时,这些按钮不得窃取 ActiveControl 的焦点(否则它们将成为 ActiveControl)。
这样,您还可以避免所有这些FocusedTextbox = textBox
等等并删除该代码。
您只需要没有设置 Selectable 属性的按钮。您可以使用从 Button 派生的自定义控件并删除ControlStyles.Selectable在其构造函数中使用SetStyle method:
Public Class ButtonNoSel
Inherits Button
Public Sub New()
SetStyle(ControlStyles.Selectable, False)
End Sub
End Class
将您的按钮替换为这个按钮(或者,如果您已经在使用自定义控件,则只需设置样式)。
要用此自定义控件替换现有按钮:
- 将新的类对象添加到您的项目中,为其命名
ButtonNoSel
,将上面的所有代码复制到新类中以替换您在其中找到的两行代码。
- 构建项目。您可以找到
ButtonNoSel
现在就在您的工具箱中进行控制。用这个按钮替换您的按钮。
- Or, open up the Form's Designer file and replace (CTRL+H) all
System.Windows.Forms.Button()
related to the Virtual KeyBoard with ButtonNoSel
.
- 删除现有的事件处理程序,不再需要它们。
在托管这些按钮(表单或您正在使用的任何其他内容)的类的构造函数中添加相同的 Click 事件处理程序。
然后,您可以删除您现在拥有的所有这些事件处理程序,每个控件一个。所有事件只需要一个事件处理程序:
Public Sub New()
InitializeComponent()
For Each ctrl As Control In Me.Controls.OfType(Of ButtonNoSel)
AddHandler ctrl.Click, AddressOf KeyBoardButtons_Click
Next
End Sub
当然,您也不需要向任何其他控件添加事件处理程序,这就是所需的全部。
现在,您可以过滤您希望键盘使用的控件类型,例如,TextBoxBase控件(TextBox 和 RichTextBox)、DataGridView、NumericUpDown 等。
或者只过滤需要的特殊情况特别待遇(例如,月份日历)。
要添加与按下的按钮相对应的字符,您可以使用SendKeys.Send():它将在当前插入点插入新字符,因此您不需要任何其他代码来存储和重置插入符号/光标位置,就像设置控件的 Text 属性一样。
在此示例中,我正在检查是否ActiveControl
is a TextBoxBase
控制,然后只需发送单击的按钮保存的字符。
如果是DataGridView,先发送F2
进入编辑模式,然后发送字符。
您也可以只发送一个字符(因此不需要过滤器),但在这种情况下,您将替换而不是添加该单元格的现有值。
Private Sub KeyBoardButtons_Click(sender As Object, e As EventArgs)
Dim selectedButton = DirectCast(sender, Control)
Dim keysToSend = String.Empty
If TypeOf ActiveControl Is TextBoxBase Then
keysToSend = selectedButton.Text
ElseIf TypeOf ActiveControl Is DataGridView Then
Dim ctrl = DirectCast(ActiveControl, DataGridView)
If TypeOf ctrl.CurrentCell IsNot DataGridViewTextBoxCell Then Return
SendKeys.Send("{F2}")
keysToSend = selectedButton.Text
Else
' Whatever else
End If
If Not String.IsNullOrEmpty(keysToSend) Then
SendKeys.Send(keysToSend)
End If
End Sub
► 请注意{F2}
仅发送一次:当单元格进入编辑模式时,ActiveControl
is a DataGridViewTextBoxEditingControl
,因此是一个 TextBox 控件,由TextBoxBase
filter.
这就是它的工作原理(仅使用此处发布的代码):
![Virtual Keyboard SendKeys](https://i.stack.imgur.com/i1oKO.gif)