如何防止滚轮选择TStringGrid的最后一行?

WeG*_*ars 0 delphi scrollwheel tstringgrid

我有一个包含多行的TStringGrid,其中我实现了某种"只读"行.更准确地说,我不允许用户点击倒数第二行.如果用户点击最后一行,则没有任何反应; 焦点不会移动到该行的单元格.

我有代码(在KeyDown中),一切顺利.但是,如果用户单击顶行然后使用鼠标滚轮向下滚动,最终焦点将移动到倒数第二行.知道如何防止这种情况吗?

Dav*_*nan 5

好吧,你可以覆盖DoMouseWheelDown来实现这一目标.

function TMyStringGrid.DoMouseWheelDown(Shift: TShiftState; 
  MousePos: TPoint): Boolean;
begin
  if Row<RowCount-2 then
    //only allow wheel down if we are above the penultimate row
    Result := inherited DoMouseWheelDown(Shift, MousePos)
  else
    Result := False;
end;
Run Code Online (Sandbox Code Playgroud)

但是你怎么知道没有其他方法将焦点转移到最后一行?

事实上,一个更好的解决方案是覆盖SelectCell:

function TMyStringGrid.SelectCell(ACol, ARow: Longint): Boolean;
begin
  Result := ARow<RowCount-1;
end;
Run Code Online (Sandbox Code Playgroud)

当您这样做时,您不需要任何KeyDown代码,并且您不需要覆盖DoMouseWheelDown.将阻止将所选单元格更改为最后一行的所有可能机制.

正如@TLama正确指出的那样,你不需要子类TStringGrid来实现这一点.你可以使用这个OnSelectCell活动:

procedure TForm1.StringGrid1SelectCell(Sender: TObject; ACol, ARow: Longint;
  var CanSelect: Boolean);
begin
  CanSelect := ARow<(Sender as TStringGrid).RowCount-1;
end;
Run Code Online (Sandbox Code Playgroud)