在StringGrid中强制选择单元格 - Delphi

use*_*313 5 delphi

是否可以强制选择我的StrinGrid?我想只允许用户水平选择单元格,即使鼠标在选择时可以上下移动,我想要stringgrid只在有MouseDown的行上显示选择.因此,当用户想要选择一系列单元格时,他将单击鼠标,向右(或向左)拖动鼠标,同时查看如何一个接一个地选择单元格,然后是MouseUp事件.在拖动时,我不希望用户在移动鼠标时看到其他行(而不是拖动开始的行).我假设我应该在StringGrid的onMouseMove中做一些事情......但是怎么样?

到目前为止我的代码是:

// this draws a focus rect around the selected cell (DefaultDrawing=false)
procedure TForm2.sgDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect;
  State: TGridDrawState);
begin
if (gdFocused in State)or(gdSelected in State) then
            begin
              sg.Canvas.Pen.Color:=$00FFEECC;
              sg.Canvas.MoveTo(Rect.Left,Rect.Top);
              sg.Canvas.LineTo(Rect.Right,Rect.Top);
              sg.Canvas.LineTo(Rect.Right,Rect.Bottom);
              sg.Canvas.LineTo(Rect.Left,Rect.Bottom);
              sg.Canvas.LineTo(Rect.Left,Rect.Top);
            end
            else
            begin
              sg.Canvas.Brush.Color:=clWhite;
              sg.Canvas.FillRect(Rect);
            end;
end;

procedure TForm2.sgMouseDown(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
 myrow:=sg.Row;
 mycol:=sg.Col;
end;

procedure TForm2.sgMouseMove(Sender: TObject; Shift: TShiftState; X,
  Y: Integer);
begin
  sg.Row:=myrow;
end;
Run Code Online (Sandbox Code Playgroud)

可能吗?我怎样才能做到这一点?

Jen*_*olt 5

是的,它是可行的.我不是控制网格,而是在选择:using Windows.ClipCursor; 时设置鼠标移动的范围.

首先在mouseDown上计算有效边界:

procedure TForm8.StringGrid1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
  StringGrid: TStringGrid;
  GridRect: TGridRect;
  Row: Integer;
  CursorClipArea: TRect;
  BoundsRect: TRect;
begin
  // The Sender argument to StringGrid1Click is actually the StringGrid itself,
  // and the following "as" cast lets you assign it to the StringGrid local variable
  // in a "type-safe" way, and access its properties and methods via the temporary variable
  StringGrid := Sender as TStringGrid;

  // Now we can retrieve the use selection
  GridRect := StringGrid.Selection;

  // and hence the related GridRect
  // btw, the value returned for Row automatically takes account of
  // the number of FixedRows, if any, of the grid
  Row := GridRect.Top;

  //Then set the bounds of the mouse movement.
  //ClipCursor uses Screen Coordinates to you'll have to use ClientToScreen
  CursorClipArea.TopLeft := StringGrid.ClientToScreen(StringGrid.CellRect(StringGrid.FixedCols, Row).TopLeft);
  CursorClipArea.BottomRight := StringGrid.ClientToScreen(StringGrid.CellRect(StringGrid.ColCount - 1, Row).BottomRight);
  Windows.ClipCursor(@CursorClipArea)
end;

//Then on mouse up release the mouse
    procedure TForm8.StringGrid1MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
    begin
      //Release mouse
      Windows.ClipCursor(nil)
    end;
Run Code Online (Sandbox Code Playgroud)