2

我正在尝试在 Delphi 2010 中的 RichEdit 控件上的 OnChange 事件调用的过程中使用以下代码将“逗号”替换为“逗号 + 空格”。

SomeString := RichEdit.Lines.Strings[RichEdit.Lines.Count-1];
Position  := Pos(',', SomeString);
if Position > 0 then
begin
  Delete(SomeString, Position, 1);
  Insert(', ',  SomeString, Position);
  RichEdit.Lines.Strings[RichEdit.Lines.Count-1] := SomeString;
end;

它工作得很好,但我不能再通过键盘使用 BACKSPACE 和 DEL(在 RichEdit 控件上),因为插入的字符就像障碍物。另一组插入的字符不会发生这种情况,只有“逗号+空格”才会发生。

有人可以告诉我我在这里做错了什么吗?

4

1 回答 1

2

试试这段代码

  //get the string
  SomeString := RichEdit.Lines.Strings[RichEdit.Lines.Count-1];
  //replace the 'comma' with 'comma+space'
  SomeString :=StringReplace(SomeString ,',',', ',[rfReplaceAll,rfIgnoreCase]);
  //now delete the extra space which gets added each time you call this event
  SomeString :=StringReplace(SomeString ,',  ',', ',[rfReplaceAll,rfIgnoreCase]);
  //your desired result
  RichEdit.Lines.Strings[RichEdit.Lines.Count-1] := SomeString ;

请记住 BACKSPACE 和 DEL 工作正常。但是对于您的代码,每次您尝试更改 RichEdit 的内容时都会添加一个额外的空间。因此给人的印象是 2 个键不起作用。

由于您在删除逗号前的空格时遇到问题,我将提供另一种解决方案

向类添加一个布尔变量isComma: Boolean
稍后在RichEdit 的OnKeyPress事件中插入此代码

  isComma := False;
  if key = ',' then
    isComma := True;

OnChange事件代码在这里

var
  CurPoint: TPoint;
  cText: string;
  cLine: string;
begin
  if isComma then
  begin
    cLine:=' ';   //character to be added after comma, ' ' in here
    CurPoint:=RichEdit1.CaretPos;
    cText:=RichEdit1.Lines.Strings[CurPoint.y];
    //add ' ' where the cursor is i.e. after the comma
    cText:=Copy(cText,0,CurPoint.x)+cLine+Copy(cText,CurPoint.x+1,Length(cText));
    RichEdit1.Lines.Strings[CurPoint.y]:=cText;
  end;
end;
于 2013-05-09T07:45:57.683 回答