鼠标中键/滚动条/翻页操作时锁定Dbgrid的选定纪录不动


Q:数据查询后 我选中一行数据,在用鼠标滚轮往下翻的时候,选中的行数据就不是我刚才选中的了.同样点击表格那个向下的箭头,也是如此.如何锁定选中的行数据,即时翻页的时候它也不动

地址:http://community.csdn.net/Expert/topic/4084/4084438.xml?temp=.5828516

A:

继承一个TDbgrid,自己画焦点。

WindowProc 中拦截鼠标中键消息,发送WM_VSCROLL消息,控制滚动条随鼠标中键移动

MouseDown中记录选中的行,用dataset的recno属性标记。翻页或鼠标中键以及滚动条的变化不再改变当前行

DrawColumnCell中重画表格

示例:

新建一个form,添加一个TTable,TDatasource,TDbgrid.
============================================

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.

优质内容筛选与推荐>>
1、Windows2012R2 设置NTP时间服务器
2、c#中结构与类的区别(转载CSDN.NET)
3、【Linux】sudo用户权限管理
4、shell 脚本使用记录
5、MFC对话框(控件消息)


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号