/// <summary> /// Set the state of the passed Listview item's index. /// </summary> /// <param name="index">Listview item's index.</param> /// <param name="selected">Select the passed item?</param> public void SelectItem(int index, bool selected) { var ptrItem = IntPtr.Zero; try { // Determine whether selecting or unselecting. uint select = selected ? (uint)ListViewCallBackMask.LVIS_SELECTED : 0; // Fill in the LVITEM structure with state fields. var stateItem = new LvItem { Mask = (uint)ListViewItemMask.LVIF_STATE, Item = index, SubItem = 0, State = @select, StateMask = (uint)ListViewCallBackMask.LVIS_SELECTED }; // Copy the structure to unmanaged memory. ptrItem = Marshal.AllocHGlobal(Marshal.SizeOf(stateItem.GetType())); Marshal.StructureToPtr(stateItem, ptrItem, true); // Send the message to the control window. Win32.SendMessage( this.Handle, (int)ListViewMessages.LVM_SETITEMSTATE, (IntPtr)index, ptrItem); } catch (Exception ex) { System.Diagnostics.Trace.WriteLine($"VirtualListView.SetItemState error={ex.Message}"); // TODO: should this eat any exceptions? throw; } finally { // Always release the unmanaged memory. if (ptrItem != IntPtr.Zero) { Marshal.FreeHGlobal(ptrItem); } } }
/// <summary> /// Set the state of the passed Listview item's index. /// </summary> /// <param name="index">Listview item's index.</param> /// <param name="selected">Select the passed item?</param> public void SelectItem(int index, bool selected) { var ptrItem = IntPtr.Zero; try { // Determine whether selecting or unselecting. uint select = selected ? (uint)ListViewCallBackMask.LVIS_SELECTED : 0; // Fill in the LVITEM structure with state fields. var stateItem = new LvItem { Mask = (uint)ListViewItemMask.LVIF_STATE, Item = index, SubItem = 0, State = @select, StateMask = (uint)ListViewCallBackMask.LVIS_SELECTED }; // Copy the structure to unmanaged memory. ptrItem = Marshal.AllocHGlobal(Marshal.SizeOf(stateItem.GetType())); Marshal.StructureToPtr(stateItem, ptrItem, true); // Send the message to the control window. Win32.SendMessage( this.Handle, (int)ListViewMessages.LVM_SETITEMSTATE, index, ptrItem.ToInt32()); } catch (Exception ex) { System.Diagnostics.Trace.WriteLine("VirtualListView.SetItemState error=" + ex.Message); // TODO: should this eat any exceptions? throw; } finally { // Always release the unmanaged memory. if (ptrItem != IntPtr.Zero) { Marshal.FreeHGlobal(ptrItem); } } }