Strip formattng from richtextbox

Xancholy

Well-known member
Joined
Aug 29, 2006
Messages
143
Programming Experience
Beginner
I need to strip all formatting from any text pasted into my richtextbox. The textbox should only allow any font/size I pre-determine but I want to retain the ability to highlight.

How can I achieve this ?
 
VB.NET:
Private Sub RichTextBox1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles RichTextBox1.KeyDown
    If e.Control AndAlso e.KeyCode = Keys.V _        
    OrElse e.Shift AndAlso e.KeyCode = Keys.I Then
        Me.RichTextBox1.SelectedText = Clipboard.GetText
        e.Handled = True
    End If
End Sub
 
Thank you. Using VB.NET2008Express, the editor does not seem to recognise ORELSE ANDALSO (syntax error)

Do I need to add a reference ?
 
There was a typo in code. OrElse and/or AndAlso is not a problem in VB2008 ;) Try again, I fixed the code in post. So you're not familiar with the If-Then statement also? hehehe :)
 
Thanks John. How can I amend your code to also strip text formatting when the clipboard matter is pasted into the richtextbox ?
 
Last edited by a moderator:
RTF editors normally put both formatted and plain text when copying to clipboard, so just calling Clipboard.GetText() should do it.
 
I copy some large font text including images from a Word document and paste it using your above code. When pasted it is large font text in the richtextbox.

Where do I use your Clipboard.GetText() suggestion in your code to strip out this formatting to retain a standard font/size in the richtextbox?
 
I copy some large font text including images from a Word document and paste it using your above code. When pasted it is large font text in the richtextbox.

Where do I use your Clipboard.GetText() suggestion in your code to strip out this formatting to retain a standard font/size in the richtextbox?
Please refer to thread Strip formattng from richtextbox
 
You can check if Clipboard.ContainsText().
 
So let me know if this your code amended is correct:

VB.NET:
    Private Sub RichTextBox1_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles RichTextBox1.KeyDown
        'aware of Paste or Insert
        If e.Control AndAlso e.KeyCode = Keys.V _
        OrElse e.Shift AndAlso e.KeyCode = Keys.I Then

            If Clipboard.ContainsImage OrElse Clipboard.ContainsFileDropList Then
                'some images are transferred as filedrops - strip image
                e.Handled = True 'stops here
            ElseIf Clipboard.ContainsText() Then 'strip formatting
                Me.RichTextBox1.SelectedText = Clipboard.GetText()
                e.Handled = True
            End If
        End If
    End Sub
 
Back
Top