7

How can I override the copy/paste functions in a Richtextbox C# application. Including ctrl-c/ctrl-v and right click copy/paste.

It's WPF richtextBox.

LarsTech
  • 80,625
  • 14
  • 153
  • 225
raym0nd
  • 3,172
  • 7
  • 36
  • 73
  • for Windows Forms: http://stackoverflow.com/questions/5618162/detecting-if-paste-event-occurred-inside-a-rich-text-box for WPF see here: http://stackoverflow.com/questions/3061475/paste-event-in-a-wpf-textbox – Davide Piras Aug 30 '11 at 13:27
  • @Davide, the WPF link adds a handler, but it doesnt override it. – raym0nd Aug 30 '11 at 13:49

3 Answers3

18

To override the command functions:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData) 
{
  if (keyData == (Keys.Control | Keys.C))
  {
    //your implementation
    return true;
  } 
  else if (keyData == (Keys.Control | Keys.V))
  {
    //your implementation
    return true;
  } 
  else 
  {
    return base.ProcessCmdKey(ref msg, keyData);
  }
}

And right-clicking is not supported in a Winforms RichTextBox

--EDIT--

Realized too late this was a WPF question. To do this in WPF you will need to attach a custom Copy and Paste handler:

DataObject.AddPastingHandler(myRichTextBox, MyPasteCommand);
DataObject.AddCopyingHandler(myRichTextBox, MyCopyCommand);

private void MyPasteCommand(object sender, DataObjectEventArgs e)
{
    //do stuff
}

private void MyCopyCommand(object sender, DataObjectEventArgs e)
{
    //do stuff
}
LarsTech
  • 80,625
  • 14
  • 153
  • 225
Edwin de Koning
  • 14,209
  • 7
  • 56
  • 74
  • Do you know how to do that in WPF ? – raym0nd Aug 30 '11 at 13:50
  • @EdiwnThe WPF stuff you have, adds a handler but doesnt override the main cop/paste ones, they are still being called – raym0nd Aug 30 '11 at 14:03
  • 3
    @raym0nd: You could add 'e.CancelCommand();' to prevent the default copy/pasting... – Edwin de Koning Aug 30 '11 at 14:23
  • @EdwindeKoning For Windows Forms, this approach might work for CTRL+V, but not SHIFT+INSERT, which is also a standard paste key-combination. Of course, using your example, it'd be easier to extend the solution to support this. – CJBS Mar 12 '14 at 00:08
4

What about Cut while using Copy and Paste Handlers? When you have your custom implementation of OnCopy and you handle it by

e.Handled = true;
e.CancelCommand();

OnCopy is also called when doing Cut - I can't find the way to find out whether method was called to perform copy or cut.

Lufa
  • 51
  • 4
2

I used this:
//doc.Editor is the RichtextBox

 DataObject.AddPastingHandler(doc.Editor, new DataObjectPastingEventHandler(OnPaste));
 DataObject.AddCopyingHandler(doc.Editor, new DataObjectCopyingEventHandler(OnCopy));



    private void OnPaste(object sender, DataObjectPastingEventArgs e)
    { 

    }
    private void OnCopy(object sender, DataObjectCopyingEventArgs e)
    {

    }
raym0nd
  • 3,172
  • 7
  • 36
  • 73