为了账号安全,请及时绑定邮箱和手机立即绑定

右键单击单词建议(Hunspell)

右键单击单词建议(Hunspell)

C#
慕标琳琳 2022-07-23 08:57:13
我有一个 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);
查看完整描述

1 回答

?
皈依舞

TA贡献1851条经验 获得超3个赞

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


这里作为一个例子,我使用Tag的属性ToolStripMenuItem作为合同,并且所有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);


查看完整回答
反对 回复 2022-07-23
  • 1 回答
  • 0 关注
  • 114 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号