在富文本框中启用复制,剪切,过去的窗口

时间:2013-09-23 18:37:50

标签: c# vb.net visual-studio

我的程序中有一个富文本框(richTextBox1),如下所示。但是,当我右键单击它时,它不会弹出“复制,剪切,过去”窗口。你能否告诉我如何在我的Rich Text Box中启用这个“复制,剪切,过去”窗口?我是C#的新手,如果您知道如何解决这个问题,请一步一步让我知道

enter image description here

7 个答案:

答案 0 :(得分:27)

尝试使用此代码

<强> UPDATED CODE:

        private void richTextBox1_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);

                richTextBox1.ContextMenu = contextMenu;
            }
        }
        void CutAction(object sender, EventArgs e)
        {
            richTextBox1.Cut();
        }

        void CopyAction(object sender, EventArgs e)
        {
            Graphics objGraphics;
            Clipboard.SetData(DataFormats.Rtf, richTextBox1.SelectedRtf);
            Clipboard.Clear();
        }

        void PasteAction(object sender, EventArgs e)
        {
            if (Clipboard.ContainsText(TextDataFormat.Rtf))
            {
                richTextBox1.SelectedRtf
                    = Clipboard.GetData(DataFormats.Rtf).ToString();
            }
        } 

如果您要使用记事本(without styles )等其他应用程序复制粘贴,请替换以下方法

       void CopyAction(object sender, EventArgs e)
        {
            Clipboard.SetText(richTextBox1.SelectedText);
        }

        void PasteAction(object sender, EventArgs e)
        {
            if (Clipboard.ContainsText())
            {
                richTextBox1.Text
                    += Clipboard.GetText(TextDataFormat.Text).ToString();
            }
        }  

答案 1 :(得分:20)

如果您有多个RichTextBox,则可以使用此extension方法:

public static void AddContextMenu(this RichTextBox rtb)
{
    if (rtb.ContextMenuStrip == null)
    {
        ContextMenuStrip cms = new ContextMenuStrip()
        {
            ShowImageMargin = false
        };

        ToolStripMenuItem tsmiUndo = new ToolStripMenuItem("Undo");
        tsmiUndo.Click += (sender, e) => rtb.Undo();
        cms.Items.Add(tsmiUndo);

        ToolStripMenuItem tsmiRedo = new ToolStripMenuItem("Redo");
        tsmiRedo.Click += (sender, e) => rtb.Redo();
        cms.Items.Add(tsmiRedo);

        cms.Items.Add(new ToolStripSeparator());

        ToolStripMenuItem tsmiCut = new ToolStripMenuItem("Cut");
        tsmiCut.Click += (sender, e) => rtb.Cut();
        cms.Items.Add(tsmiCut);

        ToolStripMenuItem tsmiCopy = new ToolStripMenuItem("Copy");
        tsmiCopy.Click += (sender, e) => rtb.Copy();
        cms.Items.Add(tsmiCopy);

        ToolStripMenuItem tsmiPaste = new ToolStripMenuItem("Paste");
        tsmiPaste.Click += (sender, e) => rtb.Paste();
        cms.Items.Add(tsmiPaste);

        ToolStripMenuItem tsmiDelete = new ToolStripMenuItem("Delete");
        tsmiDelete.Click += (sender, e) => rtb.SelectedText = "";
        cms.Items.Add(tsmiDelete);

        cms.Items.Add(new ToolStripSeparator());

        ToolStripMenuItem tsmiSelectAll = new ToolStripMenuItem("Select All");
        tsmiSelectAll.Click += (sender, e) => rtb.SelectAll();
        cms.Items.Add(tsmiSelectAll);

        cms.Opening += (sender, e) =>
        {
            tsmiUndo.Enabled = !rtb.ReadOnly && rtb.CanUndo;
            tsmiRedo.Enabled = !rtb.ReadOnly && rtb.CanRedo;
            tsmiCut.Enabled = !rtb.ReadOnly && rtb.SelectionLength > 0;
            tsmiCopy.Enabled = rtb.SelectionLength > 0;
            tsmiPaste.Enabled = !rtb.ReadOnly && Clipboard.ContainsText();
            tsmiDelete.Enabled = !rtb.ReadOnly && rtb.SelectionLength > 0;
            tsmiSelectAll.Enabled = rtb.TextLength > 0 && rtb.SelectionLength < rtb.TextLength;
        };

        rtb.ContextMenuStrip = cms;
    }
}

并使用它:richTextBox1.AddContextMenu();

屏幕截图:screenshot

答案 2 :(得分:3)

标准RichTextBox不包含用于剪切,复制和粘贴的上下文菜单。但是,您可以查看this article,其中包含实现您自己的完整代码!

答案 3 :(得分:3)

我认为 Thilina H 提供的解决方案非常好,除了很少的错误。

  1. MouseUp 事件导致第二次点击后右键单击开始。我建议使用 MouseDown 事件而不是 MouseUp 事件。

  2. 我第二次测试了 CopyAction 方法。在我的情况下, CopyAction 方法没有复制输入字符。我必须编辑这样的代码:

    Clipboard.SetText(richTextBox1.SelectedText.Replace("\n", "\r\n"));
    
  3. richTextBox1.SelectedText 为空时,程序显示异常。我只是编辑了下面显示的 CopyAction 方法来解决问题。

        if (chatBox.SelectedText != null && chatBox.SelectedText != "")
        {
            Clipboard.SetText(richTextBox1.SelectedText.Replace("\n", "\r\n"));
        }
    
  4. 快乐的编码!

答案 4 :(得分:1)

如果您需要将标准上下文菜单添加到多个RichTextBox实例,那么创建从RichTextBox继承的自定义扩展组件可能会更好。可以从Solution Explorer项目上下文菜单Add - &gt;添加新组件。新物品...... - &gt;自定义控制。

您还可以定义上下文菜单打开的处理程序,以检查是否选择了任何文本,剪贴板不为空以及控件是否设置为只读。

支持其他有用的标准操作(如撤消,重做,删除和全选)也很不错。

namespace Common
{
    public partial class RichTextBoxEx : RichTextBox
    {
        public RichTextBoxEx()
        {
            AddContextMenu();
        }

        public void AddContextMenu()
        {
            ContextMenuStrip cms = new ContextMenuStrip { ShowImageMargin = false };

            ToolStripMenuItem tsmiUndo = new ToolStripMenuItem("Undo");
            tsmiUndo.Click += (sender, e) => { if (CanUndo) Undo(); };
            tsmiUndo.ShortcutKeys = Keys.Z | Keys.Control;
            cms.Items.Add(tsmiUndo);

            ToolStripMenuItem tsmiRedo = new ToolStripMenuItem("Redo");
            tsmiRedo.Click += (sender, e) => { if (CanRedo) Redo(); };
            tsmiRedo.ShortcutKeys = Keys.Y | Keys.Control;
            cms.Items.Add(tsmiRedo);

            cms.Items.Add(new ToolStripSeparator());

            ToolStripMenuItem tsmiCut = new ToolStripMenuItem("Cut");
            tsmiCut.Click += (sender, e) => Cut();
            tsmiCut.ShortcutKeys = Keys.X | Keys.Control;
            cms.Items.Add(tsmiCut);

            ToolStripMenuItem tsmiCopy = new ToolStripMenuItem("Copy");
            tsmiCopy.Click += (sender, e) => Copy();
            tsmiCopy.ShortcutKeys = Keys.C | Keys.Control;
            cms.Items.Add(tsmiCopy);

            ToolStripMenuItem tsmiPaste = new ToolStripMenuItem("Paste");
            tsmiPaste.Click += (sender, e) => Paste();
            tsmiPaste.ShortcutKeys = Keys.V | Keys.Control;                
            cms.Items.Add(tsmiPaste);

            ToolStripMenuItem tsmiDelete = new ToolStripMenuItem("Delete");
            tsmiDelete.Click += (sender, e) => { SelectedText = ""; };                                
            cms.Items.Add(tsmiDelete);

            cms.Items.Add(new ToolStripSeparator());

            ToolStripMenuItem tsmiSelectAll = new ToolStripMenuItem("Select All");
            tsmiSelectAll.Click += (sender, e) => { SelectionStart = 0; SelectionLength = Text.Length; };
            tsmiSelectAll.ShortcutKeys = Keys.A | Keys.Control;
            cms.Items.Add(tsmiSelectAll);

            cms.Opening += delegate (object sender, CancelEventArgs e) 
            {
                tsmiUndo.Enabled = CanUndo && !this.ReadOnly;
                tsmiRedo.Enabled = CanRedo && !this.ReadOnly;
                tsmiCut.Enabled = (SelectionLength != 0) && !this.ReadOnly;
                tsmiCopy.Enabled = SelectionLength != 0;
                tsmiPaste.Enabled = Clipboard.ContainsText() && !this.ReadOnly;
                tsmiDelete.Enabled = (SelectionLength != 0) && !this.ReadOnly;
                tsmiSelectAll.Enabled = (TextLength > 0) && (SelectionLength < TextLength);
            };

            ContextMenuStrip = cms;
        }
    }
}

答案 5 :(得分:1)

我只想补充Thilina H的答案(海报上标记为正确答案的答案) 这是我的复制和粘贴功能,它们更像记事本。

void CopyAction(object sender, EventArgs e)
{
    if (richTextBox1.SelectedText != null && richTextBox1.SelectedText != "")
    {
        Clipboard.SetText(richTextBox1.SelectedText);
    }
}

void PasteAction(object sender, EventArgs e)
{
    if (Clipboard.ContainsText())
    {
        int selstart = richTextBox1.SelectionStart;
        if (richTextBox1.SelectedText != null && richTextBox1.SelectedText != "")
        {
            richTextBox1.Text = richTextBox1.Text.Remove(selstart, richTextBox1.SelectionLength);
        }

        string clip = Clipboard.GetText(TextDataFormat.Text).ToString();
        richTextBox1.Text = richTextBox1.Text.Insert(selstart, clip);
        richTextBox1.SelectionStart = selstart + clip.Length;
    }
}

我希望它有所帮助;

答案 6 :(得分:0)

感谢@Jaex

https://stackoverflow.com/a/36624233/5132252

https://stackoverflow.com/a/435510/5132252

    [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Winapi)]
    internal static extern IntPtr GetFocus();

    private Control GetFocusedControl()
    {
        Control focusedControl = null;
        // To get hold of the focused control:
        IntPtr focusedHandle = GetFocus();
        if (focusedHandle != IntPtr.Zero)
            // Note that if the focused Control is not a .Net control, then this will return null.
            focusedControl = Control.FromHandle(focusedHandle);
        return focusedControl;
    }

    private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
    {

        if (Clipboard.ContainsText())
        {
            var FocusedControl = GetFocusedControl();

            if (FocusedControl != null)
                switch (FocusedControl.GetType().Name)
                {
                    case "RichTextBox":
                        {
                            var RichTextBox = FocusedControl as RichTextBox;
                            RichTextBox.Paste();
                            break;
                        }
                    case "TextBox":
                        {
                            var TextBox = FocusedControl as TextBox;
                            TextBox.Paste();
                            break;
                        }

                }
        }
    }