본문 바로가기

delphi

stringgrid를 마우스로 드레그하여 선택한 다음 병합하는 코드

반응형
SMALL

마우스로 StringGrid 드래그를 구현한 다음 선택한 셀을 병합하려면 OnMouseDown, OnMouseMove 및 OnMouseUp 이벤트를 사용하여 마우스 이동을 추적하고 사용자가 선택한 셀을 확인할 수 있다.

var
  Dragging: Boolean;
  DragRect: TRect;
  MergeLeft, MergeTop: Integer;
  MergeText: string;

procedure TForm1.GridMouseDown(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
  if (Button = mbLeft) and not (ssShift in Shift) then
  begin
    Dragging := True;
    DragRect := Grid.CellRect(Grid.Col, Grid.Row);
    MergeLeft := Grid.Col;
    MergeTop := Grid.Row;
    MergeText := Grid.Cells[MergeLeft, MergeTop];
    Grid.Canvas.Brush.Color := clHighlight;
    Grid.Canvas.FillRect(DragRect);
  end;
end;

procedure TForm1.GridMouseMove(Sender: TObject; Shift: TShiftState;
  X, Y: Integer);
var
  NewRect: TRect;
begin
  if Dragging then
  begin
    Grid.Canvas.Brush.Color := clBtnFace;
    Grid.Canvas.FillRect(DragRect);
    NewRect := Grid.CellRect(Grid.MouseCoord(X, Y).X, Grid.MouseCoord(X, Y).Y);
    DragRect := Rect(Min(DragRect.Left, NewRect.Left), Min(DragRect.Top, NewRect.Top),
      Max(DragRect.Right, NewRect.Right), Max(DragRect.Bottom, NewRect.Bottom));
    Grid.Canvas.Brush.Color := clHighlight;
    Grid.Canvas.FillRect(DragRect);
    DrawGridSelection;
  end;
end;

procedure TForm1.GridMouseUp(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
var
  R: TRect;
  C, R1, C1: Integer;
begin
  if Dragging then
  begin
    Dragging := False;
    R := Rect(0, 0, 0, 0);
    for C := DragRect.Left to DragRect.Right - 1 do
    begin
      for R1 := DragRect.Top to DragRect.Bottom - 1 do
      begin
        if (C = MergeLeft) and (R1 = MergeTop) then Continue;
        if C = DragRect.Left then
          MergeText := Grid.Cells[C, R1];
        Grid.Cells[C, R1] := '';
        R := UnionRect(R, Grid.CellRect(C, R1));
      end;
    end;
    Grid.Cells[MergeLeft, MergeTop] := MergeText;
    Grid.Canvas.Brush.Color := clBtnFace;
    Grid.Canvas.FillRect(DragRect);
    Grid.Canvas.Brush.Color := clWindow;
    Grid.Canvas.FillRect(R);
  end;
end;

procedure TForm1.DrawGridSelection;
var
  R: TRect;
  C, R1: Integer;
begin
  Grid.Canvas.Brush.Style := bsClear;
  Grid.Canvas.Pen.Mode := pmXor;
  Grid.Canvas.Pen.Style := psDot;
  Grid.Canvas.Pen.Color := clBlack;
  for C := DragRect.Left to DragRect.Right - 1 do
  begin
    for R1 := DragRect.Top to DragRect.Bottom - 1 do
    begin
      R := Grid.CellRect(C, R1);
      Grid.Canvas.Rectangle(R);
    end;
  end;
  Grid.Canvas.Pen.Mode := pmCopy;
end;
반응형
LIST