简体   繁体   中英

How to copy listview sub item text to clipboard using contextmenu copy?

private void lstDisplayHardware_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                ListViewItem item = lstDisplayHardware.GetItemAt(e.X, e.Y);
                ContextMenu m = new ContextMenu();
                m.MenuItems.Add(new MenuItem("Cut"));
                m.MenuItems.Add(new MenuItem("Copy"));
                m.MenuItems.Add(new MenuItem("Paste"));

                if (item != null)
                {
                    item.Selected = true;
                    m.MenuItems.Add(new MenuItem(string.Format("Do something to row {0}", item.Position.ToString())));
                    Clipboard.SetData(item.SubItems[1].Text, lstDisplayHardware);
                }
                m.Show(lstDisplayHardware, new Point(e.X, e.Y));
            }
        }

lstDisplayHardware is the ListView control. When I right click, it doesn't copy the data to the clipboard.

What I want to do is when I click/select "Copy" it will copy the sub-item text to the clipboard.

Right now, it doesn't copy the text to the clipboard at all.

To do that, you need to handle a menu item click:

MenuItem miCopy = new MenuItem();
miCopy.Click += miCopy_Click;

void miCopy_Click(object sender, EventArgs e)
{
    //what you want to do  
}
 ContextMenu m = new ContextMenu();
m.MenuItems.Add(miCopy);

I don't think the Clipboard.SetData is what you want.

Try using Clipboard.SetText(item.SubItems[1].Text);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM