首页 > 代码库 > winform 右键listview的内容,添加到粘贴板中

winform 右键listview的内容,添加到粘贴板中

using System;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApp28
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            listView1.View = View.Details;
            listView1.GridLines = true;
            listView1.FullRowSelect = true;
            listView1.Cursor = Cursors.Hand;
            listView1.Columns.Add("name");
            listView1.Columns.Add("age");
            for (int i = 0; i < 20; i++)
            {
                ListViewItem li = new ListViewItem() { Text="name"+i};
                li.SubItems.Add("age"+i);
                listView1.Items.Add(li);
            }

            listView1.MouseDown += ListView1_MouseDown;
        }

        private void ListView1_MouseDown(object sender, MouseEventArgs e)
        {
            //鼠标右键
            if (e.Button == MouseButtons.Right)
            {
                //获取鼠标在listview1的坐标
                Point p= listView1.PointToClient(Control.MousePosition);
                if (listView1.SelectedItems.Count > 0)
                {
                    //获取要复制的内容
                    ListViewItem li = listView1.GetItemAt(p.X, p.Y);
                    ListViewItem.ListViewSubItem ls= li.GetSubItemAt(p.X, p.Y);
                    string text = ls.Text;
                    //将内容添加到粘贴板中
                    try
                    {
                        Clipboard.SetDataObject(text);
                    }
                    catch (Exception  ee)
                    {
                        MessageBox.Show(this,ee.Message);
                    }


                    
                }
                else
                {
                    MessageBox.Show(this,"没有选中信息");
                }

            }


        }




    }
}

 

winform 右键listview的内容,添加到粘贴板中