Advertisement
JQSOFT

DragSelectListView - VB.NET

Mar 9th, 2020
668
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
VB.NET 2.31 KB | None | 0 0
  1. ' March 10, 2020
  2. ' --------------
  3.  
  4. Imports System.Runtime.InteropServices
  5. Imports System.Windows.Forms
  6. Imports System.Drawing
  7.  
  8. Public Class DragSelectListView
  9.     Inherits ListView
  10.  
  11.     Private startPoint As Point
  12.  
  13.     Sub New()
  14.         DoubleBuffered = True
  15.     End Sub
  16.  
  17.     Protected Overrides Sub OnMouseDown(e As MouseEventArgs)
  18.         MyBase.OnMouseDown(e)
  19.  
  20.         If e.Button = MouseButtons.Left AndAlso
  21.             Items.Count > 1 Then
  22.             Dim vsp = GetScrollPos(Handle, Orientation.Vertical)
  23.             Dim yoffset = Font.Height * vsp
  24.  
  25.             startPoint = New Point(e.X, e.Y + yoffset)
  26.         End If
  27.     End Sub
  28.  
  29.     Protected Overrides Sub OnMouseMove(e As MouseEventArgs)
  30.         MyBase.OnMouseMove(e)
  31.  
  32.         If e.Button = MouseButtons.Left AndAlso Items.Count > 1 Then
  33.             Dim vsp = GetScrollPos(Handle, Orientation.Vertical)
  34.             Dim fh = Font.Height
  35.             Dim yoffset = fh * vsp
  36.  
  37.             Dim selRect As New Rectangle(Math.Min(startPoint.X, e.Location.X),
  38.                                        Math.Min(startPoint.Y - yoffset, e.Location.Y),
  39.                                        Math.Abs(e.Location.X - startPoint.X),
  40.                                        Math.Abs(e.Location.Y - startPoint.Y + yoffset))
  41.  
  42.             Dim cr = ClientRectangle
  43.  
  44.             'Toggle selection...
  45.             For Each item In Items.Cast(Of ListViewItem).
  46.                 Where(Function(x) x.Bounds.IntersectsWith(cr))
  47.                 item.Selected = selRect.IntersectsWith(item.Bounds)
  48.             Next
  49.  
  50.             'Scroll if needed...
  51.             Dim p = PointToClient(Cursor.Position)
  52.             Dim lvi = GetItemAt(p.X, p.Y)
  53.  
  54.             If lvi Is Nothing Then Return            
  55.  
  56.             If lvi.Index > 0 AndAlso (p.Y - lvi.Bounds.Height * 1.5) <= fh Then
  57.                 Items(lvi.Index - 1).EnsureVisible()
  58.             ElseIf lvi.Index < Items.Count - 1 AndAlso (p.Y + lvi.Bounds.Height * 1.5) > (Height - fh) Then
  59.                 Items(lvi.Index + 1).EnsureVisible()
  60.             End If
  61.         End If
  62.     End Sub
  63.  
  64.     <DllImport("user32.dll", CharSet:=CharSet.Auto)>
  65.     Private Shared Function GetScrollPos(hWnd As IntPtr,
  66.                                         nBar As Orientation) As Integer
  67.     End Function
  68.  
  69. End Class
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement