【问题标题】:How to move cursor position in Delphi StringGrid cell?如何在 Delphi StringGrid 单元格中移动光标位置?
【发布时间】:2016-09-20 15:32:21
【问题描述】:

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

【问题讨论】:

  • 您可以尝试保持编辑器控件并在单击后执行 SelectAll 就地编辑器(不是主网格)

标签: delphi tstringgrid


【解决方案1】:

假设您使用的是 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.

山姆

【讨论】:

  • 怎么样?我可以看到 TStringGrid 没有像 SelStart 这样的东西。
  • 好的,但是你在哪里设置 SelStart 呢?在 GetEditText 或 SetEditText 中设置似乎不起作用。
  • @fullerm 我不确定你是如何开始显示编辑器的。如果您使用ShowEditor 函数开始编辑,则在此之后立即设置SelStart。如果它是自动的,你必须做更多的工作。取决于您的代码和情况。一种方法是从OnGetEditText 内部将自定义消息发布到主窗体,稍后在处理消息时您可以设置SelStart
  • 我只是单击单元格进入编辑模式。在 OnGetEditText 中设置 SelStart 无效。你自己试过吗?发送等效消息有何不同?
  • 山姆,为了完整起见,也许您可​​以编辑您的答案,将您在 cmets 中所说的内容包含在内
【解决方案2】:

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

【讨论】:

  • 我需要能够存储尾随回车。
  • 那就不要使用OnSetEditText
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-23
  • 1970-01-01
  • 2022-12-06
  • 1970-01-01
相关资源
最近更新 更多