Delphi richedit line insertion error

I've googled and checked many places for a solution, but all cases I found differed or involved something more advanced than simply adding or deleting lines. Basically, I want to make a sort of scr...

You are getting the RichEdit line insertion error because of check added to the Delphi 2009 version. This check verifies if the insertion of a new line has been successful and this check uses for it the selection position. Unfortunately, for the following piece of code:

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;

The workflow looks like this:

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.

Also, before someone fix this issue, don’t use even this, it will cause the same error:

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

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

If you didn’t fell asleep from this boring story, then I can suggest you just to avoid the manipulation with the lines in OnChange event as much as you can (better to say, only when you know what can happen).

Содержание

  1. Почему я получаю сообщение об ошибке вставки строки RichEdit при вызове Delete в событии OnChange?
  2. 1 ответы
  3. Delphi richedit line insertion error
  4. Why am I getting RichEdit line insertion error when I call Delete in OnChange event?
  5. 1 Answer 1
  6. What could cause a «richedit line insertion error» in C++Builder when inserting text in a different language?
  7. 2 Answers 2
  8. Related
  9. Hot Network Questions
  10. Subscribe to RSS
  11. Почему я получаю ошибку вставки строки RichEdit при вызове события Delete в OnChange?
  12. 1 ответ

Почему я получаю сообщение об ошибке вставки строки RichEdit при вызове Delete в событии OnChange?

Я гуглил и проверял много мест в поисках решения, но все случаи, которые я нашел, отличались или включали что-то более сложное, чем простое добавление или удаление строк. По сути, я хочу сделать своего рода богатое редактирование с прокруткой (альтернативой было бы перемещение каретки вниз, для чего я уже нашел решение).

Я добавляю к нему строки и проверяю Lines.Count с OnChange событие богатого редактирования, и как только оно достигает значения больше 15, я хочу позвонить Lines.Delete(0) , однако я получаю сообщение об ошибке:

Может кто-нибудь сказать мне, что я делаю неправильно здесь?

задан 06 мая ’12, 23:05

Ошибка, которую вы получаете, это RichEdit line insertion error , что вы можете упомянуть в своем вопросе. Я попытаюсь понять, почему, но вы можете просто удалить строку, прежде чем вставлять новую. — TLama

Когда вы набираете слова «ошибка», самое следующее вы должны печатать это точный ошибка, которую вы получаете, с полным сообщением об ошибке. — Ken White

@KenWhite, как сказал TLama, это уже точная ошибка, если только это не предоставит вам дополнительную информацию: First chance exception at $7505b9bc. Exception class EOutOfResources with message ‘RichEdit line insertion error’. — Raith

1 ответы

Вы получаете RichEdit line insertion error из-за проверки, добавленной в версию Delphi 2009. Эта проверка проверяет, была ли вставка новой строки успешной, и эта проверка использует для этого выбранную позицию. К сожалению, для следующего фрагмента кода:

Рабочий процесс выглядит так:

1. — TRichEdit.Lines.Add → TRichEdit.Lines.Insert

Получите позицию первого символа для строки, в которую будет вставлена ​​строка, добавьте разрыв строки к этой строке, настройте выделение (длина 0, начиная с начала строки) и вставьте строку, выполнив сообщение EM_REPLACESEL, что, кроме текста вставки, изменяет также позицию выделения. Упомянутая выше проверка еще не была выполнена, а тем временем вставка текста вызывает срабатывание события OnChange, где вызывается TRichEdit.Lines.Delete.

2. — TRichEdit.Lines.Delete

Удалить делает что-то подобное. Он получает индекс первого символа удаленной строки, устанавливает выделение, теперь уже по всей длине строки, и выполняет сообщение EM_REPLACESEL с пустой строкой. Но это также, конечно, меняет положение выбора. И в этом проблема, потому что сейчас мы возвращаемся к последней строке функции TRichEdit.Lines.Insert.

3. — TRichEdit.Lines.Add → TRichEdit.Lines.Insert

Теперь остается сделать последнюю вещь предыдущего вызова функции TRichEdit.Lines.Insert, проверку на зло, основанную только на позиции выбора. И поскольку позиция была изменена при удалении, она не соответствует ожидаемому результату, и вы получаете сообщение об ошибке.

Кроме того, прежде чем кто-то исправит эту проблему, не используйте даже это, это вызовет ту же ошибку:

Если вы не уснули от этой скучной истории, то могу посоветовать вам просто максимально избегать манипуляций со строками в событии OnChange (лучше сказать, только тогда, когда вы знаете, что может произойти).

Источник

Delphi richedit line insertion error

Like others here I also am having trouble with generating the reports in CSV and I get the RichEdit line insertion error. I am using Win 98 se.. Seems like this problem happens with certain versions of riched32.dll and the problem can be avoided in the programs code. Here is an excerpt from a search I did on google about the RichEdit line insertion error.
=================================================
In article , Brendon Weir wrote:
> I am having a similar problem with Delphi 3.01 and TRichEdit under Win98SE.
> In my code I use «RichEdit.Lines.Add» to add text to the richedit and get
> the same «RichEdit line insertion error», and it still occurs even if i set
> MaxLength to a really high number like 30, 000,000 right before adding
> the strings.

This is a bug (or a feature ) in some versions of the rich edit DLL, which
upends some code in the VCL wrapper class. You can work around it by not using
LInes.Add. Instead use this:

with richedit1 do begin
selstart := gettextlen;
seltext := linetoadd+#13#10
end;

If you add a great number of lines in one loop you can move the selstart :=
gettextlen line outside the loop, since each assignment to seltext will make
the caret end up after the inserted text.

Peter Below (TeamB) 100113.1101@compuserve.com)
No e-mail responses, please, unless explicitly requested!
Note: I’m unable to visit the newsgroups every day at the moment,
so be patient if you don’t get a reply immediately.

[ 06-03-2002, 03:45 AM: Message edited by: Night2000 ]

Источник

Why am I getting RichEdit line insertion error when I call Delete in OnChange event?

I’ve googled and checked many places for a solution, but all cases I found differed or involved something more advanced than simply adding or deleting lines. Basically, I want to make a sort of scrolling rich edit (alternative would be moving the caret to the bottom, which I already found a solution for).

I’m adding lines to it and checking Lines.Count with the OnChange event of the rich edit and as soon as it reaches value greater 15 I want to call Lines.Delete(0) , however I get the error:

Can someone tell me what am I doing wrong here ?

1 Answer 1

You are getting the RichEdit line insertion error because of check added to the Delphi 2009 version. This check verifies if the insertion of a new line has been successful and this check uses for it the selection position. Unfortunately, for the following piece of code:

The workflow looks like this:

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.

Also, before someone fix this issue, don’t use even this, it will cause the same error:

If you didn’t fell asleep from this boring story, then I can suggest you just to avoid the manipulation with the lines in OnChange event as much as you can (better to say, only when you know what can happen).

Источник

What could cause a «richedit line insertion error» in C++Builder when inserting text in a different language?

I have a C++Builder application using a TRichText control that has to display a report, running under Windows XP. The application was written in English but has been adapted to use other languages. Creating text on the TRichEdit (using the RichEdit->Lines->Add() function) is no problem as long as I am using Western languages. When I’m trying to add Russian (Cyrillic) text however the application throws an EOutOfResources exception with the «RichEdit line insertion error». Now this exception is usually thrown when the amount of text exceeds the RichEdit internal buffer (64KB) but that is certainly not the case and even adding one character fails.
It is not a unicode application so I have to switch codepages to see the application in Cyrillic.And then I can see all other texts (like menus and labels) are displayed correct.
So what else could cause this error ?

2 Answers 2

RTF expects anything outside of 7-bit ASCII to be escape sequences. See this page for more details on the escape sequences. I think the section that details control page encoding would be most useful for you.

Research shows it’s a problem that only occurs on Windows XP. Also the error does not occur when the Windows XP has the locale settings for the specific language. The problem seems to be in the RichEd32.dll that is supplied with this version of Windows. The VCL (Visual Component Library as used by C++Builder and Delphi) fails when the first character of a line of text that is added to the TRichText control is an escaped character. The solution is to use the following code to add a line:

This actually has to be done only once. After text was added to any RichEdit control in the application, all subsequent calls to ‘Lines->Add()’ will work without throwing the exception.

Hot Network Questions

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.1.14.43159

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Почему я получаю ошибку вставки строки RichEdit при вызове события Delete в OnChange?

Я искал в Google и проверил много мест для решения, но все случаи, которые я обнаружил, отличались или включали что-то более продвинутое, чем простое добавление или удаление строк. По сути, я хочу сделать своего рода прокрутку с расширенным редактированием (альтернативой было бы перемещение курсора вниз, для чего я уже нашел решение).

Я добавляю к нему строки и проверяю Lines.Count с помощью события OnChange расширенного редактирования, и как только оно достигает значения больше 15, я хочу вызвать Lines.Delete(0) , однако получаю сообщение об ошибке :

Может кто-нибудь сказать мне, что я здесь делаю не так?

1 ответ

Вы получаете RichEdit line insertion error из-за проверки, добавленной в версию Delphi 2009. Эта проверка проверяет, была ли вставка новой строки успешной, и эта проверка использует для этого позицию выбора. К сожалению, для следующего фрагмента кода:

Рабочий процесс выглядит так:

1. — TRichEdit.Lines.Add → TRichEdit.Lines.Insert

Получите позицию первого символа для строки, в которую будет вставлена ​​строка, добавьте разрыв строки к этой строке, установите выделение (длина 0, начиная с начала строки) и вставьте строку, выполнив сообщение EM_REPLACESEL, кроме текста вставка, также изменяет позицию выделения. Упомянутая выше проверка еще не была выполнена, и тем временем вставка текста вызывает событие OnChange, в котором вызывается TRichEdit.Lines.Delete.

2. — TRichEdit.Lines.Delete

Удаление делает нечто подобное. Он получает индекс первого символа удаленной строки, устанавливает выбор теперь по всей длине строки и выполняет сообщение EM_REPLACESEL с пустой строкой. Но, конечно, это также меняет позицию выбора. И в этом проблема, потому что теперь мы возвращаемся к последней строке функции TRichEdit.Lines.Insert.

3. — TRichEdit.Lines.Add → TRichEdit.Lines.Insert

Осталось выполнить последнее из предыдущего вызова функции TRichEdit.Lines.Insert, злонамеренная проверка, основанная только на позиции выбора. И так как позиция была изменена за время удаления, она не соответствует ожидаемому результату, и вы получаете сообщение об ошибке.

Кроме того, прежде чем кто-то исправит эту проблему, не используйте даже это, это вызовет ту же ошибку:

Если вы не заснули от этой скучной истории, то я могу посоветовать вам просто по возможности избегать манипуляций со строками в событии OnChange (лучше сказать, только когда вы знаете, что может случиться).

Источник

FROSYA_26

0 / 0 / 0

Регистрация: 22.02.2015

Сообщений: 56

1

Delphi 6-7

28.12.2022, 11:46. Показов 832. Ответов 21

Метки нет (Все метки)


Всем добрый день.В результате работы кода возникает ошибка «RichEdit line insertion error».Задача программы открывать файлы в формате cpp866 сразу перекодировать в windows 1251 и выводить информацию в RichEdit постранично.Само перекодирование работает,но с выводом есть проблемы. Буду благодарен любой помощи,прикладываю код.

Delphi
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
function StrOemToAnsi(const S: AnsiString): AnsiString;
begin
  if Length(S) = 0 then Result := ''
  else
    begin
      SetLength(Result, Length(S));
      OemToAnsiBuff(@S[1], @Result[1], Length(S));
    end;
end;
 
procedure TMainForm.OpenFiles(Sender: TObject);
begin
    if OpenDialog.Execute then
      TXT := TStringList.Create;
      TXT.LoadFromFile(OpenDialog.FileName);
      TXTS := StrOemToAnsi(TXT.Text);
      Page := 1;
      ShowPage;
end;
 
procedure TMainForm.ShowPage;
var
  i: Integer;
begin
  RichEdit.Clear;
  for i := LinesOfPage * (Page - 1) to LinesOfPage * Page - 1 do begin
    if i >= TXT.Count then
      Break;
      RichEdit.Lines.Add(TXTS[i]);
  end;
end;
 
function TMainForm.PageCount: Integer;
begin
  Result := TXT.Count div LinesOfPage;
  if TXT.Count mod LinesOfPage > 0 then
    Inc(Result);
end;
 
procedure TMainForm.NextPage;
begin
  if Page < PageCount then begin
    Inc(Page);
    ShowPage;
  end;
end;
 
procedure TMainForm.PrevPage;
begin
  if Page > 1 then begin
    Dec(Page);
    ShowPage;
  end;
end;
 
procedure TMainForm.Button1Click(Sender: TObject);
begin
  PrevPage;
end;
 
procedure TMainForm.Button2Click(Sender: TObject);
begin
   NextPage;
end;

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Модератор

8254 / 5477 / 2248

Регистрация: 21.01.2014

Сообщений: 23,578

Записей в блоге: 3

28.12.2022, 12:26

2

Что такое TXTS? Если публикуете какие-то обрывки своего кода — озаботьтесь хотя бы, чтобы описания переменных присутствовали.



0



0 / 0 / 0

Регистрация: 22.02.2015

Сообщений: 56

28.12.2022, 12:53

 [ТС]

3

Извините пожалуйста,сразу как-то и не подумал.

TXT // имя файла с текстом
TXTS // Имя файла уже с перекодированным текстом
LinesOfPage // количество строк на странице



0



Модератор

3199 / 1813 / 664

Регистрация: 15.11.2015

Сообщений: 7,259

28.12.2022, 14:04

4

Цитата
Сообщение от FROSYA_26
Посмотреть сообщение

TXT // имя файла с текстом

Цитата
Сообщение от FROSYA_26
Посмотреть сообщение

TXT := TStringList.Create;

Серьёзно? Давайте весь проект, или не ждите внятной помощи.



0



FROSYA_26

0 / 0 / 0

Регистрация: 22.02.2015

Сообщений: 56

28.12.2022, 14:54

 [ТС]

5

Простите меня ещё раз пожалуйста,виноват что сразу все не скинул.

Delphi
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
unit Unit1;
 
interface
 
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls;
 
type
TMainForm = class(TForm)
Button1: TButton;
Button2: TButton;
OpenDialog: TOpenDialog;
RichEdit: TRichEdit;
Button3: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure OpenFiles(Sender: TObject);
procedure ShowPage;
function PageCount: Integer;
procedure NextPage;
procedure PrevPage;
 
private
{ Private declarations }
public
{ Public declarations }
end;
 
var
MainForm: TMainForm;
TXT: TStringList; // имя файла с текстом 
TXTS : String;  // имя файла уже с перекодированным тестом
Page: Integer;
 
const
LinesOfPage = 30; // кол-во строк на странице
 
implementation
 
 
 
{$R *.dfm}
 
function StrOemToAnsi(const S: AnsiString): AnsiString;
begin
if Length(S) = 0 then Result := ''
else
begin
SetLength(Result, Length(S));
OemToAnsiBuff(@S[1], @Result[1], Length(S));
end;
end;
 
procedure TMainForm.OpenFiles(Sender: TObject);
begin
if OpenDialog.Execute then
TXT := TStringList.Create;
TXT.LoadFromFile(OpenDialog.FileName);
TXTS := StrOemToAnsi(TXT.Text);
Page := 1;
ShowPage;
end;
 
procedure TMainForm.ShowPage;
var
i: Integer;
begin
RichEdit.Clear;
for i := LinesOfPage * (Page - 1) to LinesOfPage * Page - 1 do begin
if i >= TXT.Count then
Break;
RichEdit.Lines.Add(TXTS[i]);
 
end;
end;
 
function TMainForm.PageCount: Integer;
begin
Result := TXT.Count div LinesOfPage;
if TXT.Count mod LinesOfPage > 0 then
Inc(Result);
end;
 
procedure TMainForm.NextPage;
begin
if Page < PageCount then begin
Inc(Page);
ShowPage;
end;
end;
 
procedure TMainForm.PrevPage;
begin
if Page > 1 then begin
Dec(Page);
ShowPage;
end;
end;
 
procedure TMainForm.Button1Click(Sender: TObject);
begin
PrevPage;
end;
 
procedure TMainForm.Button2Click(Sender: TObject);
begin
NextPage;
end;
end.



0



AzAtom

Модератор

3199 / 1813 / 664

Регистрация: 15.11.2015

Сообщений: 7,259

28.12.2022, 15:44

6

Я программу не запускал, но вопрос по алгоритму появился:

Delphi
1
2
3
4
5
6
7
8
9
10
11
procedure TMainForm.ShowPage;
var
i: Integer;
begin
RichEdit.Clear;
for i := LinesOfPage * (Page - 1) to LinesOfPage * Page - 1 do begin
if i >= TXT.Count then // <<<---------- Вот здесь в TXT.Count содержится количество строк в файле
Break;            // А в TXTS содержится весь перекодированный текст
RichEdit.Lines.Add(TXTS[i]); // <<<--------- А здесь добавляется LinesOfPage штук символов из TXTS, начиная с символа номер LinesOfPage * (Page - 1).
end;
end;

Если даже в каждой строке по 1 символу, то так не выйдет, так как, ещё есть символы конца строки.

Добавлено через 11 минут
FROSYA_26, вот эти 2 процедуры исправь вот так:

Delphi
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
procedure TMainForm.OpenFiles(Sender: TObject);
begin
  if OpenDialog.Execute then
  begin
    TXT := TStringList.Create;
    TXT.LoadFromFile(OpenDialog.FileName);
    TXT.Text := StrOemToAnsi(TXT.Text);
    Page := 1;
    ShowPage;
  end;
end;
 
procedure TForm1.ShowPage;
var
  i: Integer;
begin
  RichEdit.Clear;
  for i := LinesOfPage * (Page - 1) to LinesOfPage * Page - 1 do begin
    if i >= TXT.Count then
      Break;
    RichEdit.Lines.Add(TXT[i]);
  end;
end;

А переменную TXTS можно вообще убрать.



0



0 / 0 / 0

Регистрация: 22.02.2015

Сообщений: 56

28.12.2022, 15:56

 [ТС]

7

Большое спасибо AzAtom убрал лишнюю переменную так сказать,это действительно логично.



0



Модератор

3199 / 1813 / 664

Регистрация: 15.11.2015

Сообщений: 7,259

28.12.2022, 16:19

8

FROSYA_26, ещё желательно StringList (TXT) создавать только 1 раз, а то сейчас утечка памяти получается.



0



0 / 0 / 0

Регистрация: 22.02.2015

Сообщений: 56

28.12.2022, 16:34

 [ТС]

9

Большое спасибо за совет,сейчас поправлю.А относительно получаемой ошибки у Вас случайно нет идей в чем она может быть? Просто у меня появилась мысль что может ошибка связанна с длиной строки по которым идёт разделение по страницам? Просто отдельно в коде и перекодирование и разделение по страницам работает,а вот в месте пока никак



0



Модератор

3199 / 1813 / 664

Регистрация: 15.11.2015

Сообщений: 7,259

28.12.2022, 16:48

10

Цитата
Сообщение от FROSYA_26
Посмотреть сообщение

А относительно получаемой ошибки у Вас случайно нет идей в чем она может быть?

Это происходит потому, что при Page = 1 значение LinesOfPage * (Page — 1) равно 0, и получается пытаешься взять символ №0 из строки, TXTS[0], тут и получается ошибка.



0



0 / 0 / 0

Регистрация: 22.02.2015

Сообщений: 56

28.12.2022, 16:55

 [ТС]

11

Получается что у перекодированной строки нет первого символа в строке? Просто с обычным тхт файлом если не использовать перекодирование то все работает,а ошибка именно в разделении перекодированных файлов.Хммм
Извините пожалуйста меня,но может у вас есть какое-то решение этого вопроса,хотя бы примерное,я бы был вам премного благодарен за помощь



0



Модератор

3199 / 1813 / 664

Регистрация: 15.11.2015

Сообщений: 7,259

28.12.2022, 17:02

12

Цитата
Сообщение от FROSYA_26
Посмотреть сообщение

Получается что у перекодированной строки нет первого символа в строке?

Нет, это потому, что в строках (string) первый символ имеет номер 1, в отличие от остальных массивов, списков и т.д.



0



0 / 0 / 0

Регистрация: 22.02.2015

Сообщений: 56

28.12.2022, 18:29

 [ТС]

13

Так у меня же тоже после перекодирования получаются строки.Такие же как и в обычном файле просто в кодировке другой.Или я что-то не понимаю?

Добавлено через 5 минут
Так у меня же тоже после перекодирования получаются строки.Такие же как и в обычном файле просто в кодировке другой.Или я что-то не понимаю? А нет стоп,у меня же StringList,получается



0



Модератор

3199 / 1813 / 664

Регистрация: 15.11.2015

Сообщений: 7,259

28.12.2022, 19:00

14

FROSYA_26, в первом варианте все эти строки укладывались в одну строковую переменную TXTS, вот в ней первый символ имеет индекс 1. А по замыслу нужно не отдельные символы выбирать, а целиком строки, как в исправленном варианте.



0



FROSYA_26

0 / 0 / 0

Регистрация: 22.02.2015

Сообщений: 56

28.12.2022, 19:35

 [ТС]

15

Я вроде бы понял и исправил код как Вы советовали мне,но результат тот же и ошибка та же.

Delphi
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
unit Unit1;
 
interface
 
uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ComCtrls;
 
type
  TForm1 = class(TForm)
    Button1: TButton;
    Button2: TButton;
    Button3: TButton;
    RichEdit1: TRichEdit;
    OpenDialog1: TOpenDialog;
    procedure OpenFiles(Sender: TObject);
    procedure ShowPage;
    function PageCount: Integer;
    procedure NextPage;
    procedure PrevPage;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
 
  private
    { Private declarations }
  public
    { Public declarations }
  end;
 
var
  Form1: TForm1;
TXT: TStringList;
Page: Integer;
 
const
LinesOfPage = 30;
 
implementation
 
{$R *.dfm}
function StrOemToAnsi(const S: AnsiString): AnsiString;
begin
if Length(S) = 0 then Result := ''
else
begin
SetLength(Result, Length(S));
OemToAnsiBuff(@S[1], @Result[1], Length(S));
end;
 
end;
 
 
 
procedure TForm1.OpenFiles(Sender: TObject);
begin
if OpenDialog1.Execute then
TXT := TStringList.Create;
TXT.LoadFromFile(OpenDialog1.FileName);
TXT.Text := StrOemToAnsi(TXT.Text);
Page := 1;
ShowPage;
end;
 
procedure TForm1.ShowPage;
var
i: Integer;
begin
RichEdit1.Clear;
for i := LinesOfPage * (Page - 1) to LinesOfPage * Page - 1 do begin
if i >= TXT.Count then
Break;
RichEdit1.Lines.Add(TXT[i]);
 
end;
end;
 
function TForm1.PageCount: Integer;
begin
Result := TXT.Count div LinesOfPage;
if TXT.Count mod LinesOfPage > 0 then
Inc(Result);
end;
 
procedure TForm1.NextPage;
begin
if Page < PageCount then begin
Inc(Page);
ShowPage;
end;
end;
 
procedure TForm1.PrevPage;
begin
if Page > 1 then begin
Dec(Page);
ShowPage;
end;
end;
 
procedure TForm1.Button1Click(Sender: TObject);
begin
  PrevPage;
end;
 
procedure TForm1.Button2Click(Sender: TObject);
begin
 NextPage;
end;
end.



0



AzAtom

Модератор

3199 / 1813 / 664

Регистрация: 15.11.2015

Сообщений: 7,259

28.12.2022, 19:46

16

Лучший ответ Сообщение было отмечено FROSYA_26 как решение

Решение

Цитата
Сообщение от FROSYA_26
Посмотреть сообщение

результат тот же и ошибка та же

У меня работает.

Delphi
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
unit Unit1;
 
interface
 
uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ComCtrls;
 
type
  TForm1 = class(TForm)
    Button1: TButton;
    Button2: TButton;
    OpenDialog: TOpenDialog;
    RichEdit: TRichEdit;
    Button3: TButton;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure Button3Click(Sender: TObject);
  private
    { Private declarations }
    TXT: TStringList; // Текст
    Page: Integer;
    procedure ShowPage;
    function PageCount: Integer;
    procedure NextPage;
    procedure PrevPage;
  public
    { Public declarations }
  end;
 
var
  Form1: TForm1;
 
const
  LinesOfPage = 30; // кол-во строк на странице
 
implementation
 
{$R *.dfm}
 
// https://www.cyberforum.ru/delphi-beginners/thread3065738.html
 
function StrOemToAnsi(const S: AnsiString): AnsiString;
begin
  if Length(S) = 0 then
    Result := ''
  else
  begin
    SetLength(Result, Length(S));
    OemToAnsiBuff(@S[1], @Result[1], Length(S));
  end;
end;
 
//procedure TMainForm.OpenFiles(Sender: TObject);
procedure TForm1.Button3Click(Sender: TObject);
begin
  if OpenDialog.Execute then
  begin
    TXT := TStringList.Create;
    TXT.LoadFromFile(OpenDialog.FileName);
    TXT.Text := StrOemToAnsi(TXT.Text);
    Page := 1;
    ShowPage;
  end;
end;
 
procedure TForm1.ShowPage;
var
  i: Integer;
begin
  RichEdit.Clear;
 
  for i := LinesOfPage * (Page - 1) to LinesOfPage * Page - 1 do begin
    if i >= TXT.Count then
      Break;
    RichEdit.Lines.Add(TXT[i]);
  end;
end;
 
function TForm1.PageCount: Integer;
begin
  Result := TXT.Count div LinesOfPage;
  if TXT.Count mod LinesOfPage > 0 then
    Inc(Result);
end;
 
procedure TForm1.NextPage;
begin
  if Page < PageCount then begin
    Inc(Page);
    ShowPage;
  end;
end;
 
procedure TForm1.PrevPage;
begin
  if Page > 1 then begin
    Dec(Page);
    ShowPage;
  end;
end;
 
procedure TForm1.Button1Click(Sender: TObject);
begin
  PrevPage;
end;
 
procedure TForm1.Button2Click(Sender: TObject);
begin
  NextPage;
end;
 
end.

Вложения

Тип файла: rar delphi-beginners thread3065738 OEM to ANSI.rar (4.3 Кб, 2 просмотров)



1



0 / 0 / 0

Регистрация: 22.02.2015

Сообщений: 56

28.12.2022, 20:02

 [ТС]

17

Спасибо за помощь,оно вроде как работает.Один файл я смог открыть и он нормально разбивает,но остальные почему-то даже не открываются с такой же ошибкой.Как вы думаете это может быть из-за длины строки?

Миниатюры

Ошибка: RichEdit line insertion error
 



0



Модератор

3199 / 1813 / 664

Регистрация: 15.11.2015

Сообщений: 7,259

28.12.2022, 21:09

18

Цитата
Сообщение от FROSYA_26
Посмотреть сообщение

но остальные почему-то даже не открываются

Где файл, чтобы попробовать?



0



0 / 0 / 0

Регистрация: 22.02.2015

Сообщений: 56

28.12.2022, 21:21

 [ТС]

19

Извините,что сразу не скинул



0



Модератор

3199 / 1813 / 664

Регистрация: 15.11.2015

Сообщений: 7,259

29.12.2022, 01:44

20

FROSYA_26, здесь RTF документ и кодировка CP1251. Нужно расширение сменить на .RTF и откроется в том же word-е, только страницу сделать альбомной надо.



1



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

29.12.2022, 01:44

Помогаю со студенческими работами здесь

Ошибка There was an error parsing the query. [ Token line number = 1,Token line offset = 43,Token in error = записи ]
В чем проблема, не могу понять. Вот исходник:

using System;
using System.Collections.Generic;…

Ошибка Parse error: syntax error, unexpected T_VARIABLE on line 11
Добрый день. Столкнулась с такой ошибкой в коде формы Parse error: syntax error, unexpected…

Ошибка Parse error: syntax error, unexpected ‘[‘ in W:domainshospitalCateringSys-masterindex.php on line 69
Открываю через OpenServer, php 7.1
я понимаю что говорит об не закрытых скобках в строке 69, НО…

ошибка в коде Parse error: syntax error, unexpected ‘{‘ in E:OpenServerdomainstest.ruindex.php on line 17
ошибка в коде Parse error: syntax error, unexpected ‘{‘ in E:OpenServerdomainstest.ruindex.php…

Ошибка Parse error: syntax error, unexpected T_STRING in /home/bh22299/public_html/wp-config.php on line 25
Здравствуйте. Залил сайт на хостинг и выдаёт ошибку

Вот участок кода из файла конфига…….

В чем ошибка? Parse error: syntax error, unexpected ‘[‘ in Z:homelocalhostwwwincconfig.php on line 17
Что в этой строке не так?

static $a =

Я новичок в этом деле. Голову сломал с этой ошибкой….

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

20

Post
«RichEdit line insertion error» possible cause and program solution.

Like others here I also am having trouble with generating the reports in CSV and I get the RichEdit line insertion error. I am using Win 98 se.. Seems like this problem happens with certain versions of riched32.dll and the problem can be avoided in the programs code. Here is an excerpt from a search I did on google about the RichEdit line insertion error.
=================================================
In article <3b3db741_2@dnews>, Brendon Weir wrote:
> I am having a similar problem with Delphi 3.01 and TRichEdit under Win98SE.
> In my code I use «RichEdit.Lines.Add» to add text to the richedit and get
> the same «RichEdit line insertion error», and it still occurs even if i set
> MaxLength to a really high number like 30, 000,000 right before adding
> the strings.

This is a bug (or a feature <g>) in some versions of the rich edit DLL, which
upends some code in the VCL wrapper class. You can work around it by not using
LInes.Add. Instead use this:

with richedit1 do begin
selstart := gettextlen;
seltext := linetoadd+#13#10
end;

If you add a great number of lines in one loop you can move the selstart :=
gettextlen line outside the loop, since each assignment to seltext will make
the caret end up after the inserted text.

Peter Below (TeamB) 100113.1101@compuserve.com)
No e-mail responses, please, unless explicitly requested!
Note: I’m unable to visit the newsgroups every day at the moment,
so be patient if you don’t get a reply immediately.

<small>[ 06-03-2002, 03:45 AM: Message edited by: Night2000 ]</small>


Форум программистов Vingrad

Модераторы: Snowy, MetalFan, bems, Poseidon

Поиск:

Ответ в темуСоздание новой темы
Создание опроса
> Загрузка ресурса в RichEdit 

:(

   

Опции темы

Volkogriz
  Дата 25.3.2010, 18:48 (ссылка)
| (нет голосов)
Загрузка ... Загрузка …




Быстрая цитата

Цитата

Бывалый
*

Профиль
Группа: Участник
Сообщений: 216
Регистрация: 16.9.2007

Репутация: нет
Всего: 1

Доброе время суток!
Проблемма такая, при загрузки ресурса в RichEdit выбивает ошибку

Код

RichEdit line insertion error

Что не так?
Если поместить в ресурс тукстовый файл то всё хорошо но если ртф то ошибка при открытии, но сам файл загружается а потом ошибку выбивает(((

Код

procedure TForm1.Image2Click(Sender: TObject); 
var 
LinesLoad:LongWord; 
begin 
RichEdit1.Clear; 
LinesLoad:= FindResource( hInstance, 'Proj',RT_RCDATA); 
LinesLoad := LoadResource(hInstance,LinesLoad); 
begin 
RichEdit1.Lines.Add(StrPas(PChar( LinesLoad))); 
begin 
FreeResource(LinesLoad); 
end; 
end; 
end;  

Зарание благодарен!
С уважением,
Volkogriz! 

———————

(«`-»-/»).___..—»»`-._`6_6  ) ,,,`-.  ( »’ ).` «_-.__.’)(_Y_.)’  ._»’ )  `._ `. «-.__’.-‘_..`—‘_..-_/»’/—‘_.’ ,'(il).-»»'(li).’  ((!.-‘

PM MAIL ICQ   Вверх
Volkogriz
Дата 26.3.2010, 04:50 (ссылка)
| (нет голосов)
Загрузка ... Загрузка …




Быстрая цитата

Цитата

Бывалый
*

Профиль
Группа: Участник
Сообщений: 216
Регистрация: 16.9.2007

Репутация: нет
Всего: 1

Кто нить подскажет, хотябы намекните чтоб понять гте капать.
что только не пробовал выдаёт ошибку!
подскажите плиз
Зарание благодарен!
С уважением,
Volkogriz! 

———————

(«`-»-/»).___..—»»`-._`6_6  ) ,,,`-.  ( »’ ).` «_-.__.’)(_Y_.)’  ._»’ )  `._ `. «-.__’.-‘_..`—‘_..-_/»’/—‘_.’ ,'(il).-»»'(li).’  ((!.-‘

PM MAIL ICQ   Вверх
Volkogriz
Дата 26.3.2010, 06:21 (ссылка)
| (нет голосов)
Загрузка ... Загрузка …




Быстрая цитата

Цитата

Бывалый
*

Профиль
Группа: Участник
Сообщений: 216
Регистрация: 16.9.2007

Репутация: нет
Всего: 1

Всем спасибо разабрался спустя ночь)))

Код

var
LinesLoad:LongWord;
LinesStream:TStringStream;
begin
RichEdit1.Clear;
begin
LinesLoad:= FindResource( hInstance, 'Proj',RT_RCDATA);
LinesLoad := LoadResource(hInstance,LinesLoad);
LinesStream:=TStringStream.create(StrPas(PChar( LinesLoad)));
begin
richedit1.Lines.LoadFromStream(LinesStream);
begin
LinesStream.free;
FreeResource(LinesLoad);
end;
end;
end;
end;

———————

(«`-»-/»).___..—»»`-._`6_6  ) ,,,`-.  ( »’ ).` «_-.__.’)(_Y_.)’  ._»’ )  `._ `. «-.__’.-‘_..`—‘_..-_/»’/—‘_.’ ,'(il).-»»'(li).’  ((!.-‘

PM MAIL ICQ   Вверх
Gwire
Дата 26.3.2010, 13:30 (ссылка)
| (нет голосов)
Загрузка ... Загрузка …




Быстрая цитата

Цитата

Бывалый
*

Профиль
Группа: Участник
Сообщений: 216
Регистрация: 7.8.2007
Где: Николаев

Репутация: 1
Всего: 4

Может вот так было бы проще? smile

Код

var RS: TResourceStream;
begin
    RS:= TResourceStream.Create( hInstance, 'Proj', RT_RCDATA );
    RichEdit1.Lines.LoadFromStream( RS );
    RS.Free;
end;

PM MAIL   Вверх



















Ответ в темуСоздание новой темы
Создание опроса
Правила форума «Delphi: Для новичков»
SnowyMetalFan
bemsPoseidon
Rrader

Запрещается!

1. Публиковать ссылки на вскрытые компоненты

2. Обсуждать взлом компонентов и делиться вскрытыми компонентами

  • Литературу по Дельфи обсуждаем здесь
  • Действия модераторов можно обсудить здесь
  • С просьбами о написании курсовой, реферата и т.п. обращаться сюда
  • Вопросы по реализации алгоритмов рассматриваются здесь
  • 90% ответов на свои вопросы можно найти в DRKB (Delphi Russian Knowledge Base) — крупнейшем в рунете сборнике материалов по Дельфи


Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, Snowy, MetalFan, bems, Poseidon, Rrader.

 

0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | Delphi: Для новичков | Следующая тема »

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Delphi error io pending
  • Delphi error i o error 103
  • Delphi error file not found dfm
  • Delphi error creating form ancestor for not found
  • Delphi could not load ssl library как исправить

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии