在Delphi中更新TMemo文本后保留负/反向字符串选择?

时间:2013-01-31 17:34:32

标签: delphi

在Delphi中,我无法在备忘录中保留SelStartSelLength,当选择为负/反向时,每5秒更新一次文本。

使用否定/反向选择我的意思是我已经在某处开始了选择,并且在按住左移箭头键的同时按住了一些。

代码:

var
  caret: TPoint;
  sel_start, sel_length: Integer;
begin
  sel_start := Memo1.SelStart;    //          =  5
  sel_length := Memo1.SelLength;  //          = 10
  caret := Memo1.CaretPos;        // caret.x  = 15

  //'adi and bl' selected
  caret.x := sel_start;
  Memo1.Lines.Clear;
  Memo1.Lines.Add('laditadi and blah blah');
  Memo1.SelStart := sel_start;
  Memo1.SelLength := sel_length;

  Memo1.CaretPos := caret;
end;

事实上,设置SelLength似乎实际上移动了插入符号。设置SelLength后设置插入符号SelLength := 0;。由于文字不断变化,我无法在之前和之后使用TMemo.SelText / TMemo.SetSelText

我无法找到保留插入符号的方法...任何线索?

1 个答案:

答案 0 :(得分:2)

如果sel_start与Caret的字符位置具有相同的值,则通过将selstart设置为selstart + sellength并将sellength设置为-sellength来反转选择。

procedure TForm1.Button1Click(Sender: TObject);
var
  caret: TPoint;
  sel_start, sel_length,CharFromPos: Integer;
begin
  Memo1.SetFocus;
  GetCaretPos(Caret);
  CharFromPos := SendMessage(Memo1.Handle, EM_CHARFROMPOS, 0 ,Caret.Y*$FFFF + Caret.X) AND $FFFF;
  sel_start := Memo1.SelStart;    //          =  5
  sel_length := Memo1.SelLength;  //          = 10

  Memo1.Lines.Clear;
  Memo1.Lines.Add('laditadi and blah blah'#13#10'laditadi and blah blah');
  if  sel_start<>CharFromPos then
      begin
       Memo1.SelStart := sel_start;
       Memo1.SelLength := sel_length;
      end
    else
      begin
       Memo1.SelStart := sel_start + sel_length;
       Memo1.SelLength := - sel_length;
      end;

end;
procedure TForm1.Timer1Timer(Sender: TObject);
var
 p:Tpoint;
 b:Boolean;
 CharFromPos:Integer;
begin
   b := GetCaretPos(p);
   CharFromPos := SendMessage(Memo1.Handle, EM_CHARFROMPOS, 0 ,p.Y*$FFFF + p.X) AND $FFFF;
   Caption := Format('SelStart %d CharFromPos %d',[Memo1.SelStart,CharFromPos])
end;