/*
* Copyright 2018 faddenSoft
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
#if BUILD_FOR_WINDOWS // I don't know if other platforms will emulate the LVITEM stuff
namespace CommonWinForms {
// From https://stackoverflow.com/questions/1019388/
///
/// Unpleasant hackery to make "select all" faster. With 500K items it takes about 24
/// seconds to select everything individually, and there isn't a better way. With this
/// it only takes a few milliseconds.
///
public 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);
}
}
}
#endif //BUILD_FOR_WINDOWS