I have a richtextbox and ContextMenuStrip which have cut, copy, past and select all they all work with no probelm but now I tried to add word suggestion like if the user select a word and right click on the richtextbox it should show him\her:
- word suggestion
- word suggestion
- word suggestion
- ...etc
- "Line break"
- Cut
- Copy
- Past
- "Line break"
- Select all
this is how it should be but the problem is suggestions list keeps duplicate itself with each right click(after I select the word)
here is the code:
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);
}
}
}
}