Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // March 10, 2020
- using System;
- using System.Linq;
- using System.Windows.Forms;
- using System.Drawing;
- using System.ComponentModel;
- using System.Runtime.InteropServices;
- namespace JQ.Windows.Forms
- {
- [DesignerCategory("Code")]
- public class DragSelectListView : ListView
- {
- #region Class Members
- private Point StartPoint;
- #endregion
- #region Constructors
- public DragSelectListView() : base() => DoubleBuffered = true;
- #endregion
- #region Base
- protected override void OnMouseDown(MouseEventArgs e)
- {
- base.OnMouseDown(e);
- if (e.Button == MouseButtons.Left && Items.Count > 1)
- {
- var vsp = GetScrollPos(Handle, Orientation.Vertical);
- var yOffset = Font.Height * vsp;
- StartPoint = new Point(e.X, e.Y + yOffset);
- }
- }
- protected override void OnMouseMove(MouseEventArgs e)
- {
- base.OnMouseMove(e);
- if(e.Button == MouseButtons.Left && Items.Count > 1)
- {
- var vsp = GetScrollPos(Handle, Orientation.Vertical);
- var fh = Font.Height;
- var yoffset = fh * vsp;
- var selRect = new Rectangle(Math.Min(StartPoint.X, e.Location.X),
- Math.Min(StartPoint.Y - yoffset, e.Location.Y),
- Math.Abs(e.Location.X - StartPoint.X),
- Math.Abs(e.Location.Y - StartPoint.Y + yoffset));
- var cr = ClientRectangle;
- //Toggle...
- foreach (var item in Items.Cast<ListViewItem>()
- .Where(x => x.Bounds.IntersectsWith(cr)))
- item.Selected = selRect.IntersectsWith(item.Bounds);
- //Scroll if needed...
- var p = PointToClient(Cursor.Position);
- var lvi = GetItemAt(p.X, p.Y);
- if (lvi == null) return;
- if (lvi.Index > 0 && (p.Y - lvi.Bounds.Height) <= fh)
- Items[lvi.Index - 1].EnsureVisible();
- else if (lvi.Index < Items.Count - 1 && (p.Y + lvi.Bounds.Height) > (Height - fh))
- Items[lvi.Index + 1].EnsureVisible();
- }
- }
- #endregion
- #region win32
- [DllImport("user32.dll", CharSet = CharSet.Auto)]
- private static extern int GetScrollPos(IntPtr hWnd, Orientation nBar);
- #endregion
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement