这是我的代码:
void CutAction(object sender, EventArgs e)
{
richTextBox2.Cut();
}
void CopyAction(object sender, EventArgs e)
{
Clipboard.SetData(DataFormats.Rtf, richTextBox2.SelectedRtf);
Clipboard.Clear();
}
void PasteAction(object sender, EventArgs e)
{
if (Clipboard.ContainsText(TextDataFormat.Rtf))
{
richTextBox2.SelectedRtf
= Clipboard.GetData(DataFormats.Rtf).ToString();
}
}
private void richTextBox2_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Right)
{ //click event
//MessageBox.Show("you got it!");
ContextMenu contextMenu = new System.Windows.Forms.ContextMenu();
MenuItem menuItem = new MenuItem("Cut");
menuItem.Click += new EventHandler(CutAction);
contextMenu.MenuItems.Add(menuItem);
menuItem = new MenuItem("Copy");
menuItem.Click += new EventHandler(CopyAction);
contextMenu.MenuItems.Add(menuItem);
menuItem = new MenuItem("Paste");
menuItem.Click += new EventHandler(PasteAction);
contextMenu.MenuItems.Add(menuItem);
richTextBox2.ContextMenu = contextMenu;
}
}
我有两个问题:
richTextbox2
中标记文本后,我需要模拟鼠标右键单击以查看剪切粘贴复制菜单。 答案 0 :(得分:5)
删除Clipboard.Clear();
void CopyAction(object sender, EventArgs e) {
Clipboard.SetData(DataFormats.Rtf, richTextBox2.SelectedRtf);
}
您还可以使用Copy()
的{{1}}方法:
RichTextBox
粘贴:
void CopyAction(object sender, EventArgs e) {
richTextBox2.Copy();
}
答案 1 :(得分:2)
private void btnCopy_Click(object sender, EventArgs e)
{
richTextBox1.SelectAll();
richTextBox1.Copy();
}
private void btnPaste_Click(object sender, EventArgs e)
{
richTextBox2.Paste();
}
private void btnCut_Click(object sender, EventArgs e)
{
richTextBox1.SelectAll();
richTextBox1.Cut();
}
注意:Windows窗体内置了将文本从richTextBox复制到剪贴板的方法。 比如复制,粘贴,剪切(您必须首先选择要复制或剪切的文本。在我的示例中,我已经选择了所有文本)。
这里这个例子基本上它会将内容复制到剪贴板,还有重载方法请看方法的定义。
答案 2 :(得分:2)
尝试添加toolstripbar
,添加3 toolstripbuttons
。这是复制,剪切和粘贴的代码
private void toolStripButton1_Click(object sender, EventArgs e)
{
SendKeys.Send("^x");
}
private void toolStripButton2_Click(object sender, EventArgs e)
{
SendKeys.Send("^v");
}
private void toolStripButton3_Click(object sender, EventArgs e)
{
SendKeys.Send("^c");
}
代码直接与剪贴板一起使用。
答案 3 :(得分:0)
private void richTextBox2_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Right)
{ //click event
//MessageBox.Show("you got it!");
ContextMenu contextMenu = new System.Windows.Forms.ContextMenu();
MenuItem menuItem = new MenuItem("Cut");
menuItem.Click += new EventHandler(CutAction);
contextMenu.MenuItems.Add(menuItem);
menuItem = new MenuItem("Copy");
menuItem.Click += new EventHandler(CopyAction);
contextMenu.MenuItems.Add(menuItem);
menuItem = new MenuItem("Paste");
menuItem.Click += new EventHandler(PasteAction);
contextMenu.MenuItems.Add(menuItem);
richTextBox2.ContextMenu = contextMenu;
}
}
void CutAction(object sender, EventArgs e)
{
richTextBox1.Cut();
}
void CopyAction(object sender, EventArgs e)
{
richTextBox1.Copy();
}
void PasteAction(object sender, EventArgs e)
{`
richTextBox1.Paste();
}