粘贴拦截事件失败

时间:2016-08-04 14:36:54

标签: vb.net visual-studio-2015 paste

我想拦截FIRST NAME文本框的粘贴事件,这样如果用户粘贴了#34; Joe Smith,PhD",他们就会得到" Joe"在FIRST NAME文本框中,他们将看到" Smith,PhD"在最后一个名称文本框中。相反,我得到的是#34; Joe Smith,PhDJoe"在FIRST NAME文本框中," 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 

1 个答案:

答案 0 :(得分:0)

您可以做的一件事是将firstword声明为Form级变量

Private firstWord As String

然后在TBfname_KeyDown

中分配
firstWord = words(0)

然后在KeyUp事件中重新分配TBfname.Text

Private Sub TBfname_KeyUp(sender As Object, e As KeyEventArgs) Handles TBfname.KeyUp
    TBfname.Text = firstWord
End Sub