粘贴拦截事件失败
问题描述:
我想拦截FIRST NAME文本框的粘贴事件,以便如果用户粘贴“Joe Smith,PhD”,他们将在FIRST NAME文本框中获得“Joe”,并且他们将看到“Smith ,博士“在最后的名称文本框中。相反,我得到的是“第一名”文本框中的“Joe Smith,PhDJoe”和最后一个名称文本框中的“Smith,PhD”。我为我添加了一个消息框作为断点,如果我取消注释该行,msgbox显示,然后该子工作完美。那么,这是一个计时问题(Windows 10/VS2015如果重要)?粘贴拦截事件失败
关于如何拦截粘贴事件有很多帖子,下面的代码是基于此。我究竟做错了什么?
Public Class test
Private Sub TBfname_PASTE(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TBFname.KeyDown
Dim Pasting As String = Clipboard.GetText()
If e.Modifiers = Keys.Control AndAlso e.KeyCode = Keys.V Then
Dim SplitWhere As Int64 = 0
Dim words = Pasting.Split(" "c)
Dim firstWord = words(0)
If Pasting.Contains(" ") Then
SplitWhere = Pasting.IndexOf(" ")
Dim LN As String = ""
Dim long2 As Int64 = Pasting.Length - SplitWhere - 1
If long2 > 0 Then
LN = Pasting.Substring(SplitWhere + 1, long2)
TBLname.Text = LN
End If
' MsgBox(Pasting & " vs " & TBFname.Text)
TBFname.Text = firstWord
End If
e.Handled = True
End If
End Sub
End Class
答
有一件事你可能要在KeyUp
事件TBfname_KeyDown
firstWord = words(0)
声明firstword
为Form
级可变
Private firstWord As String
,然后分配给它,然后重新分配TBfname.Text
Private Sub TBfname_KeyUp(sender As Object, e As KeyEventArgs) Handles TBfname.KeyUp
TBfname.Text = firstWord
End Sub
这个工程,所以我都设置了,但我感到困惑为什么我的代码附加而不是替换文字。 –
@Matt - 不知道数据为什么附加。出于某种原因,“TextChanged”事件似乎正在做这件事。如果您在原始版本中将'Application.DoEvents()'放在'TBfname.Text = firstWord'之前,它就可以工作。 –