Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Showing a Context Menu for an item in a ListView

Tags:

c#

winforms

I know how to make a contextMenu that pops up when I right click on a listView, what I want is for it to pop up when I right click on an item. I am trying to make a chat server and client, and now... Now I want to view client info when I right click on a connected client's item.

How can I do this?

like image 265
Daaksin Avatar asked Nov 18 '12 06:11

Daaksin


People also ask

How is context menu applied to a list view?

Android context menu appears when user press long click on the element. It is also known as floating menu. It affects the selected content while doing action on it. It doesn't support item shortcuts and icons.

How do I display the context menu?

A. Pressing Shift-F10 will bring up the context menu for any selected item. Just pressing F10 shifts the cursor focus to the first menu item (normally File).


3 Answers

private void listView1_MouseClick(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Right)
    {
        var focusedItem = listView1.FocusedItem;
        if (focusedItem != null && focusedItem.Bounds.Contains(e.Location))
        {
            contextMenuStrip1.Show(Cursor.Position);
        }
    } 
}

You can put connected client information in the contextMenuStrip1. and when you right click on a item, you can show the information from that contextMenuStrip1.

like image 75
Rashedul.Rubel Avatar answered Oct 22 '22 15:10

Rashedul.Rubel


You are going to have to use the ListViews Context Menu, but change it according to the ListView Item you right click on.

private void listView1_MouseDown(object sender, MouseEventArgs e)
{
    bool match = false;

    if (e.Button == System.Windows.Forms.MouseButtons.Right)
    {
        foreach (ListViewItem item in listView1.Items)
        {
            if (item.Bounds.Contains(new Point(e.X, e.Y)))
            {
                MenuItem[] mi = new MenuItem[] { new MenuItem("Hello"), new MenuItem("World"), new MenuItem(item.Name) };
                listView1.ContextMenu = new ContextMenu(mi);
                match = true;
                break;
            }
        }
        if (match)
        {
            listView1.ContextMenu.Show(listView1, new Point(e.X, e.Y));
        }
        else
        {
            //Show listViews context menu
        }

    }

}
like image 40
Mark Hall Avatar answered Oct 22 '22 15:10

Mark Hall


You can trigger MouseDown or MouseUp event of ListView in which if MouseButton.Right then grab the selected Item by using ListView.Hittest and give the Context menu related to that Selected Item.

For more clear info you can go through this link

like image 4
Mr_Green Avatar answered Oct 22 '22 14:10

Mr_Green