Author: Jonas Bilinkevicius
Is there any way to control the amount of characters per line in a TMemo component,
e.g. that I can only store 7 lines of 50 chars each. The MaxLength property does
not help in this case as it controls the total number of characters in the control.
Answer:
Limiting a memo to 6 lines of input:
1
2 procedure TForm1.Memo1KeyPress(Sender: TObject; var Key: Char);
3 var
4 line: Integer;
5 begin
6 if key = #13 then
7 begin
8 with Sender as TMemo do
9 begin
10 if lines.count >= 6 then
11 begin
12 key := #0;
13 line := Perform(EM_LINEFROMCHAR, SelStart, 0);
14 if line < 5 then
15 SelStart := Perform(EM_LINEINDEX, line + 1, 0);
16 end;
17 end;
18 end;
19 end;
20
21 //Limiting a memo to 5 lines of input of max. 25 characters each:
22
23 procedure TForm1.Memo1KeyPress(Sender: TObject; var Key: Char);
24 var
25 line, col: Integer;
26 begin
27 with Sender as TMemo do
28 begin
29 line := Perform(EM_LINEFROMCHAR, SelStart, 0);
30 col := SelStart - Perform(EM_LINEINDEX, line, 0);
31 if key = #8 then
32 begin
33 { Do not allow backspace if caret is on first column and deleting the
34 linebreak of the line in front would result in a line of more than 25
35 characters. Inconvenient for the user but specs are specs... }
36 if (col = 0) and (line > 0) then
37 begin
38 if (Length(lines[line]) + Length(lines[line - 1])) > 25 then
39 Key := #0;
40 end;
41 end
42 else if key in [#13, #10] then
43 begin
44 { Handle hard linebreaks via Enter or Ctrl-Enter }
45 if lines.count >= 5 then
46 begin
47 { Max number of lines reached or exceeded, set caret to start of next
48 line or this line, if on the last }
49 key := #0;
50 if line = 4 then
51 SelStart := Perform(EM_LINEINDEX, line, 0)
52 else
53 SelStart := Perform(EM_LINEINDEX, line + 1, 0);
54 end;
55 end
56 else if Key >= ' ' then
57 begin
58 { Do swallow key if current line has reached limit. }
59 if Length(lines[line]) >= 25 then
60 Key := #0;
61 end;
62 end;
63 if Key = #0 then
64 Beep;
65 end;
66
67 procedure TForm1.Memo1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
68 var
69 line, col: Integer;
70 begin
71 if Key = VK_DELETE then
72 with Sender as TMemo do
73 begin
74 line := Perform(EM_LINEFROMCHAR, SelStart, 0);
75 col := SelStart - Perform(EM_LINEINDEX, line, 0);
76 if col = Length(lines[line]) then
77 if (line < 4) and ((Length(lines[line]) + Length(lines[line + 1])) > 25)
78 then
79 begin
80 key := 0;
81 Beep
82 end;
83 end;
84 end;
|