2013-04-11 34 views
3

VB.NET 2010 - 我有一个RichTextbox,用户可以在其中手动输入数据或从其他源复制/粘贴。数据完成后,他点击,几个关键词突出显示。我的问题是,如果他从其他来源复制/粘贴,格式化也会被复制。有时候外部来源有一个白色的字体,我的文本框有一个白色的背景,所以看起来他没有粘贴,他一次又一次地做。捕获CTRL + V或粘贴到.NET中的文本框中

我在找的是一种拦截粘贴操作到文本框中的方法,这样我就可以将该文本粘贴为纯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的字体和前景色,选择所有文本,然后将字体和前景色分配给选择。

回答

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 

注:缺少任何错误检查。

+0

谢谢!我在大约一个小时前尝试过,但如果你快,那么放弃两者同时不会触发事件。我试图用我复制/粘贴的方式来完成这个任务,并且它在大约一半的时间捕获了它。 – sinDizzy 2013-04-11 21:43:32

+0

@sinDizzy我不能通过快速复制事件“不开火”。也许你有其他干扰。 – LarsTech 2013-04-11 21:46:14

+0

你说得对。我正在尝试的是KeyUp事件。让我用KeyDown试试这个,我会发布我的结果。 – sinDizzy 2013-04-11 22:13:31

相关问题