右键单击单词建议(Hunspell)

Right Click with word suggestions(Hunspell)

我有一个 richtextbox 和 ContextMenuStrip,它们可以剪切、复制、过去和 select 所有它们都可以正常工作,但现在我尝试添加单词建议,就像用户 select 一个单词一样并右键单击它应该显示 him\her:

的富文本框

这是应该的,但问题是建议列表会在每次右键单击时重复自身(在我 select 这个词之后)

代码如下:

ContextMenuStrip cms = new ContextMenuStrip { ShowImageMargin = true };

public void AddContextMenu(RichTextBox rtb)
    {
       if (rtb.ContextMenuStrip == null)
        {
            ToolStripMenuItem tsmiCut = new ToolStripMenuItem("Cut");
            tsmiCut.Image = msg.Properties.Resources.cut;
            tsmiCut.Click += (sender, e) => rtb.Cut();
            cms.Items.Add(tsmiCut);
            ToolStripMenuItem tsmiCopy = new ToolStripMenuItem("Copy");
            tsmiCopy.Image = msg.Properties.Resources.copy;
            tsmiCopy.Click += (sender, e) => rtb.Copy();
            cms.Items.Add(tsmiCopy);
            ToolStripMenuItem tsmiPaste = new ToolStripMenuItem("Paste");
            tsmiPaste.Image = msg.Properties.Resources.paste;
            tsmiPaste.Click += (sender, e) => rtb.Paste();
            cms.Items.Add(tsmiPaste);

            cms.Items.Add("-");
            ToolStripMenuItem sALL = new ToolStripMenuItem("Select All");
            sALL.Image = msg.Properties.Resources.select_all;
            sALL.Click += (sender, e) => rtb.SelectAll();
            cms.Items.Add(sALL);
            rtb.ContextMenuStrip = cms;
        }
    }

private void richTextBox_MouseDown(object sender, MouseEventArgs e)
    {
        Hunspell hunspell = new Hunspell("en_US.aff", "en_US.dic");
        hunspell.Spell(richTextBox.SelectedText);
        List<string> suggestions = hunspell.Suggest(richTextBox.SelectedText);

        ToolStripSeparator line = new ToolStripSeparator();
        AddContextMenu(richTextBox);


        if (e.Button == MouseButtons.Right)
        {
            foreach (string suggestion in suggestions)
            {
                ToolStripMenuItem sugg = new ToolStripMenuItem(suggestion);
                if (cms.Items.Contains(sugg))
                {
                    cms.Items.Remove(sugg);
                }
                else
                {
                    cms.Items.Add(sugg);
                }
            }
        }

    }

您需要一个合同来区分建议菜单项和其余菜单项,然后在添加建议时,首先删除现有建议项,然后添加新项。

这里以ToolStripMenuItemTag属性为例,所有标签中有suggestion的菜单项都被认为是作为建议:

public void Suggest(List<string> words, ContextMenuStrip menu)
{
    string suggestion = "suggestion";
    menu.Items.Cast<ToolStripItem>().Where(x => x.Tag == (object)suggestion)
        .ToList().ForEach(x => menu.Items.Remove(x));

    words.ToList().ForEach(x =>
    {
        var item = new ToolStripMenuItem(x);
        item.Tag = suggestion;
        item.Click += (s, e) => MessageBox.Show(x);
        menu.Items.Insert(0, item);
    });
}

作为用法,一个词:

Suggest(new List<string> { "something", "something else" }, contextMenuStrip1);

换句话说:

Suggest(new List<string> { "another", "another one" }, contextMenuStrip1);