在选项卡中将上下文菜单添加到richtextbox

时间:2015-02-17 21:47:07

标签: c# winforms richtextbox

这是用于制作包含富文本框的新标签并选择当前richtextbox的代码。

 private RichTextBox GetRichTextBox()
    {
        RichTextBox rtb = null;
        TabPage tp = tabControl1.SelectedTab;

        if (tp != null)
        {
            rtb = tp.Controls[0] as RichTextBox;
        }

        return rtb;
    }

    private void newToolStripMenuItem_Click(object sender, EventArgs e)
    {
        TabPage tp = new TabPage("New Document");
        RichTextBox rtb = new RichTextBox();
        rtb.Dock = DockStyle.Fill;

        tp.Controls.Add(rtb);
        tabControl1.TabPages.Add(tp);
    }

我需要能够在richtextbox中添加一个上下文菜单,包括我可能需要的剪切,复制,粘贴和其他控件。我不知道该怎么做。

1 个答案:

答案 0 :(得分:0)

通常,您可以向表单添加ContextMenuStrip,使用设计器定义菜单项,然后转到RichTextBox属性并将ContextMenuStrip实例分配给RichTextBox的ContextMenuStrip属性。

但是,您可以使用代码动态创建相同的界面:

TabPage tp = new TabPage("New Document");
RichTextBox rtb = new RichTextBox();
rtb.Dock = DockStyle.Fill;
ContextMenuStrip ctx = new ContextMenuStrip();
ctx.Items.Add(new ToolStripMenuItem("Cut",null, cutClick));
ctx.Items.Add(new ToolStripMenuItem("Copy", null, copyClick))
ctx.Items.Add(new ToolStripMenuItem("Paste", null, pasteClick));
// Add other menu items as you need

rtb.ContextMenuStrip = ctx;
.....



void cutClick(object sender, EventArgs e)
{
    RichTextBox rtb = sender as RichTextBox;
    if(rtb.SelectedText.Length > 0)
        rtb.Cut();
}
void copyClick(object sender, EventArgs e)
{
    RichTextBox rtb = sender as RichTextBox;
    if(rtb.SelectedText.Length > 0)
       rtb.Copy();
}
void pasteClick(object sender, EventArgs e)
{
    RichTextBox rtb = sender as RichTextBox;
    DataFormats.Format textFormat = DataFormats.GetFormat(DataFormats.Text);
    if(rtb.CanPaste(textFormat))
        rtb.Paste();
}