【发布时间】:2015-01-09 12:56:44
【问题描述】:
我正在编写一个小函数,它将在 KeyPress 事件之后但在 KeyPress 事件期间计算 TextBox 的内容。我知道,这听起来很奇怪。 :)
这样做的原因是因为我在工作中得到了一个项目,我要在其中修复当前程序中的任何错误。
目前在 KeyPress 事件中有一个 TextBox,它会触发 SQL Server 上的搜索。 这将搜索与 Chr(KeyAscii) 连接的 TextBox 的当前内容
这意味着如果您的 TextBox 包含 Hello 并且您的光标位于单词的末尾,它将正常工作,但如果您选择了 o 并按 a,它将搜索 Helloa 而不是 Hella。
为了更正,我想出了以下功能
Private Function TextAfterKeyPress(Ctrl As Control, KeyAscii As Integer) As String
Dim strUnSelLeft As String
Dim strUnSelRight As String
Dim strSel As String
Dim strMid As String
With Ctrl
strUnSelLeft = ""
strUnSelRight = ""
strMid = .Text
Select Case KeyAscii
Case 1 ' Ctrl + A
' No change to text
Case 3 ' Ctrl + C
' No change to text
Case 8 ' BackSpace
If .SelStart = 0 Then
' No change to text
Else
If .SelLength = 0 Then
strUnSelLeft = Left(.Text, .SelStart - 1)
strUnSelRight = Right(.Text, Len(.Text) - (.SelStart + .SelLength))
strMid = ""
Else
strUnSelLeft = Left(.Text, .SelStart)
strUnSelRight = Right(.Text, Len(.Text) - (.SelStart + .SelLength))
strMid = ""
End If
End If
Case 9 ' Tab
' No change to text
Case 13 ' Return
' No change to text
Case 22 ' Ctrl + V
strUnSelLeft = Left(.Text, .SelStart)
strUnSelRight = Right(.Text, Len(.Text) - (.SelStart + .SelLength))
strMid = Clipboard.GetText
Case 24 ' Ctrl + X
If .SelLength = 0 Then
' No change to text
Else
strUnSelLeft = Left(.Text, .SelStart)
strUnSelRight = Right(.Text, Len(.Text) - (.SelStart + .SelLength))
strMid = ""
End If
Case 26 ' Ctrl + Z
Case 27 ' Esc
' No Change to text
Case 137, 153, 160, 169, 188, 189, 190, 215, 247 ' Disallowed Chars
' No Change to text
Case 128 To 255 ' Allowed non standard Chars
strUnSelLeft = Left(.Text, .SelStart)
strUnSelRight = Right(.Text, Len(.Text) - (.SelStart + .SelLength))
strMid = Chr(KeyAscii)
Case 32 To 127 ' Standard Printable Chars
strUnSelLeft = Left(.Text, .SelStart)
strUnSelRight = Right(.Text, Len(.Text) - (.SelStart + .SelLength))
strMid = Chr(KeyAscii)
Case Else
End Select
TextAfterKeyPress = strUnSelLeft & strMid & strUnSelRight
End With
End Function
现在对于显示“Case 26”的部分,它将执行撤消操作,然后搜索将再次无法正常工作。
有什么方法可以找出当你按下 Ctrl + Z 时 TextBox 的内容是什么,但是在它发生的 KeyPress 期间? KeyPress 事件在 TextBox 的内容更改之前触发,因此我需要找出 Undo 缓冲区中的内容,以便运行正确的搜索。
谁能指出我正确的方向?
【问题讨论】: