我正在编写一个小函数,它将在KeyPress事件之后但在KeyPress事件期间计算TextBox的内容。我知道,这听起来很奇怪。 :)
之所以这样,是因为我在工作中得到了一个项目,我将修复当前程序中的任何错误。
目前有一个TextBox,它在KeyPress事件中触发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
现在,对于说明"案例26和#34;的部分,它将执行撤消操作,然后搜索无法再次正常工作。
当你按下Ctrl + Z时,有没有办法找出TextBox的内容,但是在它发生的KeyPress期间? KeyPress事件在TextBox内容发生变化之前触发,因此我需要找出Undo缓冲区中的内容,以便我可以运行正确的搜索。
有人能指出我正确的方向吗?
答案 0 :(得分:0)
我曾经使用过textbox API ..而且我认为你不能因为它的限制而处理它的UNDO缓冲区..但你可以做的是手动发送UNDO然后阅读文本框内容。
Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
Private Const EM_UNDO = &HC7
,
Case 26
KeyAscii = 0
SendMessage .hwnd, EM_UNDO, ByVal 0, ByVal 0
strMid = .Text
如果您只需要阅读文本而不是更改它,您可以发送另一个UNDO消息以将文本转换为其先前的内容。