ListView鼠标框选实现蓝色蒙板

此问题留心已久,今日方悉心求之,记录心得。

ListView控件,不论Delphi中的TListView还是c#中的ListView,在开启其MultiSelect属性时,鼠标框选只是显示框张,如下图示:

相信如系统资源管理器那样,框选以蓝色蒙板显示,视觉效果要好上许多。里外翻阅,发现与LVS_EX_DOUBLEBUFFER标记有关。

根据此线索,改造之。

1、Delphi之TListView

type
  TListView = class(ComCtrls.TListView)
  private
   procedure WMEraseBkgnd(var Message: TWMEraseBkgnd); message WM_ERASEBKGND;
  protected
    procedure CreateWnd; override;
  end;

...

uses
CommCtrl;
{ TListView } procedure TListView.CreateWnd; var Styles: DWORD; begin inherited CreateWnd; if CheckWin32Version(5, 1) then begin Styles := ListView_GetExtendedListViewStyle(WindowHandle); Styles := Styles or LVS_EX_DOUBLEBUFFER; ListView_SetExtendedListViewStyle(WindowHandle, Styles); end; end; procedure TListView.WMEraseBkgnd(var Message: TWMEraseBkgnd); begin DefaultHandler(Message); end;

2、c#之ListView

    class ListViewEx : System.Windows.Forms.ListView
    {
        public ListViewEx()
        {
            // 开启双缓冲
            this.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);
            UpdateStyles();

            // Enable the OnNotifyMessage event so we get a chance to filter out 
            // Windows messages before they get to the form's WndProc
            this.SetStyle(ControlStyles.EnableNotifyMessage, true);
        }

        protected override void OnNotifyMessage(Message m)
        {
            //Filter out the WM_ERASEBKGND message
            if (m.Msg != 0x14)
                base.OnNotifyMessage(m);
        }
    }

验证实现所需,效果如下图:

原文地址:https://www.cnblogs.com/crwy/p/9332256.html