右键单击单词建议(Hunspell)

我有一个 Richtextbox 和 ContextMenuStrip,它们可以剪切、复制、过去和选择所有它们都可以在没有问题的情况下工作,但现在我尝试添加单词建议,比如用户选择一个单词并右键单击它应该向他显示的 Richtextbox:

  • 词建议

  • 词建议

  • 词建议

  • ...ETC

  • “越线”

  • 复制

  • 过去的

  • “越线”

  • 全选

这是应该的,但问题是建议列表在每次右键单击时都会保持重复(在我选择单词之后)

这是代码:

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



慕标琳琳
浏览 115回答 1
1回答

皈依舞

您需要一个契约来区分建议菜单项和其余菜单项,然后在添加建议时,首先删除现有建议项,然后添加新项。这里作为一个例子,我使用Tag的属性ToolStripMenuItem作为合同,并且所有suggestion在其标签中的菜单条项目都被视为建议:public void Suggest(List<string> words, ContextMenuStrip menu){&nbsp; &nbsp; string suggestion = "suggestion";&nbsp; &nbsp; menu.Items.Cast<ToolStripItem>().Where(x => x.Tag == (object)suggestion)&nbsp; &nbsp; &nbsp; &nbsp; .ToList().ForEach(x => menu.Items.Remove(x));&nbsp; &nbsp; words.ToList().ForEach(x =>&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; var item = new ToolStripMenuItem(x);&nbsp; &nbsp; &nbsp; &nbsp; item.Tag = suggestion;&nbsp; &nbsp; &nbsp; &nbsp; item.Click += (s, e) => MessageBox.Show(x);&nbsp; &nbsp; &nbsp; &nbsp; menu.Items.Insert(0, item);&nbsp; &nbsp; });}作为用法,一句话:Suggest(new List<string> { "something", "something else" }, contextMenuStrip1);换个说法:Suggest(new List<string> { "another", "another one" }, contextMenuStrip1);
打开App,查看更多内容
随时随地看视频慕课网APP