unit Unit1;
interface
{鼠标中键/滚动条/翻页操作时锁定Dbgrid的选定纪录不动
by jinjazz}
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Grids, DBGrids, DB, DBTables, StdCtrls;
type
TDBGrid = class(DBGrids.TDBGrid)
private
FOldGridWnd: TWndMethod;
SelectedRow: integer;
procedure NewGridWnd(var Message: TMessage);
protected
procedure DrawColumnCell(const Rect: TRect; DataCol: Integer;
Column: TColumn; State: TGridDrawState); override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); override;
public
constructor Create(AOwner: TComponent); override;
end;
type
TForm1 = class(TForm)
Table1: TTable;
DataSource1: TDataSource;
DBGrid1: TDBGrid;
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
{ TDBGrid }
constructor TDBGrid.Create(AOwner: TComponent);
begin
inherited;
Options := Options + [dgindicator];
Self.FOldGridWnd := Self.WindowProc;
Self.WindowProc := NewGridWnd;
SelectedRow := -1;
end;
procedure TDBGrid.NewGridWnd(var Message: TMessage);
var
IsNeg: Boolean;
begin
if Message.Msg = WM_MOUSEWHEEL then
begin
IsNeg := Short(Message.WParamHi) < 0;
if IsNeg then
SendMessage(Handle, WM_VSCROLL, SB_LINEDOWN, 0)
else
SendMessage(Handle, WM_VSCROLL, SB_LINEUP, 0)
end
else
Self.FOldGridWnd(Message);
end;
procedure TDbGrid.DrawColumnCell(const Rect: TRect; DataCol: Integer;
Column: TColumn; State: TGridDrawState);
begin
if SelectedRow=-1 then SelectedRow:=DataSource.DataSet.RecNo;
Color := clinfobk;
Options := Options + [dgRowSelect];
if ((State = [gdSelected]) or (State = [gdSelected, gdFocused])) then
begin
Canvas.Brush.color := Color;
Canvas.Font.Color := Font.Color;
end;
if DataSource.DataSet.RecNo = selectedRow then
Canvas.Brush.color := clRed; //当前行以红色显示,其它行使用背景的浅绿色
Canvas.pen.mode := pmmask;
DefaultDrawColumnCell(Rect, DataCol, Column, State);
end;
procedure TDBGrid.MouseDown(Button: TMouseButton; Shift: TShiftState; X,
Y: Integer);
var
Cell: TGridCoord;
begin
inherited;
if Button = mbLeft then
begin
selectedRow := DataSource.DataSet.RecNo;
repaint;
end;
end;
end.