Hello all.
I would like to add a small handler.
Imagine that i have a listbox, and when i right click i want to appear a menu with two options .
How can i do it ?
Thanks in advance.

Dani AI

Generated

As pointed out, the designer route (create a ContextMenuStrip and attach it) is the simplest approach. For a reliable user experience you usually also want to: 1) detect which item the user right-clicked, 2) select that item before showing the menu, and 3) enable/disable or populate menu items just before the menu opens. This avoids acting on the wrong item when users right-click empty space or when multiple selection modes are in use.

A compact pattern—handle the listbox mouse event, pick the index under the cursor with IndexFromPoint, adjust selection as appropriate, then call ContextMenuStrip.Show. Use the Opening event on the ContextMenuStrip to enable/disable items or cancel the menu when nothing is relevant.

private void listBox1_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button != MouseButtons.Right) return;

    int idx = listBox1.IndexFromPoint(e.Location);
    if (idx != ListBox.NoMatches)
    {
        if (listBox1.SelectionMode == SelectionMode.One ||
            !listBox1.SelectedIndices.Contains(idx))
            listBox1.SelectedIndex = idx;
    }
    else
    {
        listBox1.ClearSelected();
    }

    contextMenuStrip1.Show(listBox1, e.Location);
}

See the docs for ListBox.IndexFromPoint and the ContextMenuStrip.Opening event for details and edge cases: ListBox.IndexFromPoint and .

Recommended Answers

All 3 Replies

You should drop a "contextMenuStrip" on to the form. You can click on it and add items in the designer. Also click on the listbox and assign the "ContextMenu" property to the new context menu strip you dropped on the form

Thanks for the fast response ,works gr8 =)

You're welcome and good luck! :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.