Capture CTRL+V or paste in a textbox in .NET
In most cases, examining the KeyDown event should be good enough along with using a temporary RichTextBox to modify the incoming text:
Private Sub RichTextBox1_KeyDown(sender As Object, e As KeyEventArgs) _
Handles RichTextBox1.KeyDown
If e.Modifiers = Keys.Control AndAlso e.KeyCode = Keys.V Then
Using box As New RichTextBox
box.SelectAll()
box.SelectedRtf = Clipboard.GetText(TextDataFormat.Rtf)
box.SelectAll()
box.SelectionBackColor = Color.White
box.SelectionColor = Color.Black
RichTextBox1.SelectedRtf = box.SelectedRtf
End Using
e.Handled = True
End If
End Sub
Note: Missing any error checking.
sinDizzy
15 years developing with FORTRAN, VB6/VBA , .NET, Avenue, and HTML.
Updated on October 10, 2020Comments
-
sinDizzy over 3 years
VB.NET 2010 - I have a RichTextbox in which the user can manually enter data or copy/paste from another source. After the data is complete he hits go and a few key words are highlighted. My issue is that if he copy/pastes from another source the formatting also gets copied. Well sometimes the outside source has a white font and my textbox has a white background so it appears like he pasted nothing and he does it again and again.
What I'm looking for is a way to intercept the paste action into the textbox so that I can take that text and paste it as pure ASCII without formatting.
Edit after experimenting with KeyDown
Private Sub txtRch_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles txtRch.KeyDown If e.Modifiers = Keys.Control AndAlso e.KeyCode = Keys.V Then With txtRch Dim i As Integer = .SelectionStart 'cache the current position .Select(0, i) 'select text from start to current position Dim s As String = .SelectedText 'copy that text to a variable .Select(i, .TextLength) 'now select text from current position to end Dim t As String = .SelectedText 'copy that text to a variable Dim u As String = s & Clipboard.GetText(TextDataFormat.UnicodeText) & t 'now concatenate the first chunk, the new text, and the last chunk .Clear() 'clear the textbox .Text = u 'paste the new text back into textbox .SelectionStart = i 'put cursor back to cached position End With 'the event has been handled manually e.Handled = True End If End Sub
This seems to work and all my text gets retained and its all ASCII. I think if I wanted to take a step further I could also take the font and forecolor of my RichTextbox, select all text, and then assign the font and forecolor to the selection.