C# – How to have context menu for selected text? &

cnetwinforms

2 problems:

  1. In google chrome if you select a word (say problem) and then right click on this selected text, the context menu shows two items 1. Copy 2.Search google for problem 3. Inspect element. The context menu is different from the context menu of that entire window. How can I have this separate context menu for selected text.

    The exact task I'm trying to accomplish is: I've a textbox (in winforms). Now when user rt clicks, the context menu show just paste. If text box is filled has some text and user selects some text and then right clicks on selected text, It should show context menu with
    items: copy, cut, paste, select all. How ?.

  2. For copying text user has 3 options:

    1. Copy (in context menu)
    2. Edit menu
    3. Ctrl+C

all these does same thing, copies selected data to clipboard. I want to overwrite functionality of copying selected data using these 3 methods to copying desired data to clipboard. How?

Best Answer

You can assign a custom ContextMenuStrip to the TextBox's ContextMenuStrip property. Thus I'd instantiate my own, populate it with items for copy/paste and the other items you need. Then, you can handle the ContextMenuStrip's Opening event, checking to see if there is selected text in the TextBox and modifying the menu's items just before it is shown (i.e. change your "Search google" item's Visible property).

private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
{
    var item = searchGoogleMenuItem;
    if (item.Visible = !string.IsNullOrEmpty(textBox1.SelectedText))
        item.Text = string.Format("Search Google '{0}'", textBox1.SelectedText);
}