gpt4 book ai didi

delphi - 当我在 OnChange 事件中调用 Delete 时,为什么会出现 RichEdit 行插入错误?

转载 作者:行者123 更新时间:2023-12-03 15:52:51 29 4
gpt4 key购买 nike

我用谷歌搜索并检查了很多地方来寻找解决方案,但我发现的所有情况都不同或涉及比简单添加或删除行更高级的东西。基本上,我想进行一种滚动丰富的编辑(替代方法是将插入符号移动到底部,我已经找到了解决方案)。

我正在向其中添加行,并使用丰富编辑的 OnChange 事件检查 Lines.Count ,一旦它达到大于 15 的值,我就想调用Lines.Delete(0),但是我收到错误:

RichEdit line insertion error

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

最佳答案

由于 Delphi 2009 版本中添加了检查,您收到 RichEdit 行插入错误。此检查验证新行的插入是否成功,并且此检查使用选择位置。不幸的是,对于以下代码:

procedure TForm1.Button1Click(Sender: TObject);
begin
RichEdit1.Clear;
RichEdit1.Lines.Add('1');
end;

procedure TForm1.RichEdit1Change(Sender: TObject);
begin
if RichEdit1.Lines.Count > 0 then
RichEdit1.Lines.Delete(0);
end;

工作流程如下所示:

1. - TRichEdit.Lines.Add → TRichEdit.Lines.Insert

Get the position of the first char for the line where the string will be inserted, add the linebreak to that string, setup the selection (0 length, starting at the line beginning) and insert the string by performing EM_REPLACESEL message, what except the text insertion, changes also the selection position. The check mentioned above has not been performed yet, and in the meantime that text insertion causes the OnChange event to fire, where the TRichEdit.Lines.Delete is called.

2. - TRichEdit.Lines.Delete

Delete does something similar. It gets the first character index of the deleted line, setup the selection, now in the whole line length and performs the EM_REPLACESEL message with the empty string. But it also changes the selection position of course. And that's the problem, because we are now going back to the last line of the TRichEdit.Lines.Insert function.

3. - TRichEdit.Lines.Add → TRichEdit.Lines.Insert

Now the last thing of a previous call of the TRichEdit.Lines.Insert function remains to be done, the evil check based just on the selection position. And since the position has been changed by the meantime deletion, it doesn't match to the expected result and you are getting the error message.

另外,在有人解决这个问题之前,甚至不要使用这个,它会导致同样的错误:

procedure TForm1.Button1Click(Sender: TObject);
begin
RichEdit1.Lines.Add('1');
end;

procedure TForm1.RichEdit1Change(Sender: TObject);
begin
RichEdit1.SelStart := 0;
end;

如果您没有从这个无聊的故事中睡着,那么我可以建议您尽可能避免对 OnChange 事件中的行进行操作(更好地说,只有当您知道会发生什么时)。

关于delphi - 当我在 OnChange 事件中调用 Delete 时,为什么会出现 RichEdit 行插入错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10474883/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com