How to override copy and paste in richtextbox

元气小坏坏 提交于 2019-11-30 13:55:33
Edwin de Koning

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
}

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.

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

    }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!