如何在 Delphi StringGrid 单元格中移动光标位置?

How to move cursor position in Delphi StringGrid cell?

当您有一个设置了 goEditing 选项的 TStringGrid 并且一个单元格中有几行文本时,当您通过单击它来编辑该单元格时,光标将位于该文本的最末尾。如何将光标移动到另一个位置?我的特殊问题是,如果文本末尾有回车 return,则用户认为该单元格为空。我想将光标移动到任何马车 returns.

之前

与其试图操纵编辑器的光标,我建议首先尝试避免在 StringGrid 中存储尾随换行符。您可以使用 OnGetEditText 事件在编辑器激活时 trim 关闭尾部换行符,并在用户输入新文本时使用 OnSetEditText 事件 trim 关闭它们。

假设您使用的是 VCLInplaceEditorTCustomGrid 的 属性。它是 TInplaceEdit 类型,继承自 TCustomEdit。您可以在其中移动光标 就像 TEdit.

如果您使用的是自动编辑单元格内容的方式,可以使用下面的方式来移动光标。我已经测试过了,它对我有用。 (我在 Windows 10 使用柏林)

unit Main;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Grids;

const
  WM_MY_MESSAGE = WM_USER + 1;

type
  TStringGridEx = class helper for TStringGrid
  public
    function GetInplaceEditor(): TInplaceEdit;
  end;

  TForm1 = class(TForm)
    aGrid: TStringGrid;
    procedure FormCreate(Sender: TObject);
    procedure aGridGetEditText(Sender: TObject; ACol, ARow: Integer; var Value: string);
  private
    procedure OnMyMessage(var Msg: TMessage); message WM_MY_MESSAGE;
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.aGridGetEditText(Sender: TObject; ACol, ARow: Integer; var Value: string);
begin
  PostMessage(Handle, WM_MY_MESSAGE, 0, 0);
end;

procedure TForm1.FormCreate(Sender: TObject);
var
  y: Integer;
  x: Integer;
begin
  for y := 0 to aGrid.RowCount do
  begin
    for x := 0 to aGrid.ColCount do // fill the grid
      aGrid.Cells[x, y] := Format('Col %d, Row %d'#13#10, [x, y]);
  end;
end;

procedure TForm1.OnMyMessage(var Msg: TMessage);
var
  pInplaceEdit: TInplaceEdit;
begin
  pInplaceEdit := aGrid.GetInplaceEditor();
  if Assigned(pInplaceEdit) then
  begin
    pInplaceEdit.SelStart := pInplaceEdit.EditText.TrimRight.Length;
    pInplaceEdit.SelLength := 0;
  end;
end;

{ TStringGridEx }

function TStringGridEx.GetInplaceEditor: TInplaceEdit;
begin
  Result := InplaceEditor; // get access to InplaceEditor
end;

end.

山姆