Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override copy and paste in richtextbox

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.

like image 962
raym0nd Avatar asked Aug 30 '11 13:08

raym0nd


3 Answers

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
}
like image 162
Edwin de Koning Avatar answered Nov 19 '22 02:11

Edwin de Koning


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.

like image 4
Lufa Avatar answered Nov 19 '22 02:11

Lufa


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)
    {

    }
like image 2
raym0nd Avatar answered Nov 19 '22 04:11

raym0nd