Matt D Matt D - 1 year ago 55 Question

Paste Intercept event failure

I want to intercept a paste event for a FIRST NAME textbox so that if the user pastes "Joe Smith, PhD", they will get "Joe" in the FIRST NAME textbox, and they will see "Smith, PhD" in the LAST NAME textbox. Instead, what I get is "Joe Smith,PhDJoe" in FIRST NAME textbox, and "Smith, PhD" in LAST NAME textbox. I added a messagebox as a breakpoint for me and if I uncomment that line, the msgbox displays and then the sub works perfectly. So, is this a timing issue (Windows 10/VS2015 if that matters)?

There are many posts on how to intercept paste events, and my code below is based on that. What am I doing wrong?

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

Answer Source

One thing you could to is declare firstword as a Form level variable

Private firstWord As String

and then assign it in TBfname_KeyDown

firstWord = words(0)

Then in the KeyUp event re-assign TBfname.Text

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