2013-04-11 32 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

相關問題