Adding a select all shortcut (Ctrl + A) to a .net listview?

前端 未结 5 489
野趣味
野趣味 2020-12-11 01:09

Like the subject says I have a listview, and I wanted to add the Ctrl + A select all shortcut to it. My first problem is that I can\'t figure out how

5条回答
  •  抹茶落季
    2020-12-11 01:21

    These works for small lists, but if there are 100,000 items in a virtual list, this could take a long time. This is probably overkill for your purposes, but just in case::

    class NativeMethods {
        private const int LVM_FIRST = 0x1000;
        private const int LVM_SETITEMSTATE = LVM_FIRST + 43;
    
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        public struct LVITEM
        {
            public int mask;
            public int iItem;
            public int iSubItem;
            public int state;
            public int stateMask;
            [MarshalAs(UnmanagedType.LPTStr)]
            public string pszText;
            public int cchTextMax;
            public int iImage;
            public IntPtr lParam;
            public int iIndent;
            public int iGroupId;
            public int cColumns;
            public IntPtr puColumns;
        };
    
        [DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Auto)]
        public static extern IntPtr SendMessageLVItem(IntPtr hWnd, int msg, int wParam, ref LVITEM lvi);
    
        /// 
        /// Select all rows on the given listview
        /// 
        /// The listview whose items are to be selected
        public static void SelectAllItems(ListView list) {
            NativeMethods.SetItemState(list, -1, 2, 2);
        }
    
        /// 
        /// Deselect all rows on the given listview
        /// 
        /// The listview whose items are to be deselected
        public static void DeselectAllItems(ListView list) {
            NativeMethods.SetItemState(list, -1, 2, 0);
        }
    
        /// 
        /// Set the item state on the given item
        /// 
        /// The listview whose item's state is to be changed
        /// The index of the item to be changed
        /// Which bits of the value are to be set?
        /// The value to be set
        public static void SetItemState(ListView list, int itemIndex, int mask, int value) {
            LVITEM lvItem = new LVITEM();
            lvItem.stateMask = mask;
            lvItem.state = value;
            SendMessageLVItem(list.Handle, LVM_SETITEMSTATE, itemIndex, ref lvItem);
        }
    }
    

    and you use it like this::

    NativeMethods.SelectAllItems(this.myListView);
    

提交回复
热议问题