VB.NET 2010 - 我有一个RichTextbox,用户可以在其中手动输入数据或从其他来源复制/粘贴。数据完成后,他会点击并突出显示几个关键词。我的问题是,如果他从其他来源复制/粘贴,格式也会被复制。好吧,有时外部来源有白色字体,我的文本框有白色背景,所以看起来他没有粘贴,他一次又一次地做。
我正在寻找的是一种拦截粘贴操作到文本框的方法,这样我就可以将该文本粘贴为纯ASCII而无需格式化。
尝试使用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
这似乎有效,我的所有文本都被保留,并且全部是ASCII。我想如果我想更进一步,我也可以采用我的RichTextbox的字体和前景,选择所有文本,然后将字体和前景分配给选择。
答案 0 :(得分:6)
在大多数情况下,检查KeyDown事件应该足够好,并使用临时RichTextBox来修改传入文本:
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
注意:缺少任何错误检查。