Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
722 views
in Technique[技术] by (71.8m points)

.net - add menu item to default context menu

I'd like to add a menu item to the default ContextMenu of a RichTextBox.

I could create a new context menu but then I lose the spell check suggestions that show up in the default menu.

Is there a way to add an item without re-implementing everything?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's not too tricky to reimplement the RichTextBox context menu with spelling suggestions, Cut, Paste, etc.

Hook up the context menu opening event as follows:

AddHandler(RichTextBox.ContextMenuOpeningEvent, new ContextMenuEventHandler(RichTextBox_ContextMenuOpening), true);

Within the event handler build the context menu as you need. You can recreate the existing context menu menu items with the following:

private IList<MenuItem> GetSpellingSuggestions()
{
    List<MenuItem> spellingSuggestions = new List();
    SpellingError spellingError = myRichTextBox.GetSpellingError(myRichTextBox.CaretPosition);
    if (spellingError != null)
    {
        foreach (string str in spellingError.Suggestions)
        {
            MenuItem mi = new MenuItem();
            mi.Header = str;
            mi.FontWeight = FontWeights.Bold;
            mi.Command = EditingCommands.CorrectSpellingError;
            mi.CommandParameter = str;
            mi.CommandTarget = myRichTextBox;
            spellingSuggestions.Add(mi);
        }
    }
    return spellingSuggestions;
}

private IList<MenuItem> GetStandardCommands()
{
    List<MenuItem> standardCommands = new List();

    MenuItem item = new MenuItem();
    item.Command = ApplicationCommands.Cut;
    standardCommands.Add(item);

    item = new MenuItem();
    item.Command = ApplicationCommands.Copy;
    standardCommands.Add(item);

    item = new MenuItem();
    item.Command = ApplicationCommands.Paste;
    standardCommands.Add(item);

    return standardCommands;
}

If there are spelling errors, you can create Ignore All with:

MenuItem ignoreAllMI = new MenuItem();
ignoreAllMI.Header = "Ignore All";
ignoreAllMI.Command = EditingCommands.IgnoreSpellingError;
ignoreAllMI.CommandTarget = textBox;
newContextMenu.Items.Add(ignoreAllMI);

Add separators as required. Add those to the new context menu's items, and then add your shiny new MenuItems.

I'm going to keep looking for a way to obtain the actual context menu though, as this is relevant to something I'll be working on in the near future.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...