Author: Tomas Rutkauskas
How to set a TEdit or TMemo to overwrite instead of insert
Answer:
Solve 1:
You have to fake it because the control does not natively support overtype mode.
Provide overtype capability for edits and memos:
1 2 procedure TScratchMain.Memo1KeyPress(Sender: TObject; var Key: Char);
3 begin4 if (Sender is TCustomEdit) and Odd(GetKeyState(VK_INSERT)) then5 with TCustomEdit(Sender) do6 if SelLength = 0 then7 case Key of8 ' '..#126, #128..#255:
9 begin10 SelLength := 1;
11 if (SelLength > 0) and (SelText[1] = #13) then12 SelLength := 2;
13 end;
14 end;
15 end;
With this handler the control will start out in insert mode since the state of
VK_INSERT is not toggled by default. Pressing it once will toggle the key and put
the control in overtype mode. If you want it to start out in overtype, use "not
Odd(...)" in the If statement.
Solve 2:
I managed to simulate it by doing this (you need to declare the FOverwrite: boolean
somewhere in the form):
16 17 procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char);
18 type19 TSmallPoint = packedrecord20 case integer of21 0: (x, y: Smallint);
22 1: (long: integer);
23 end;
24 var25 CaretPos: TPoint;
26 sCaretPos: TSmallPoint;
27 begin28 if (FOverwrite) and (Edit1.SelLength = 0) then29 begin30 GetCaretPos(CaretPos);
31 sCaretPos.x := CaretPos.x;
32 sCaretPos.y := CaretPos.y;
33 Edit1.SelStart := SendMessage(Edit1.Handle, EM_CHARFROMPOS, 0, sCaretPos.long);
34 Edit1.SelLength := 1;
35 Edit1.SelText := Key;
36 Key := #0;
37 end;
38 end;
39 40 procedure TForm1.Edit1KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
41 begin42 case Key of43 VK_INSERT: FOverwrite := not FOverwrite;
44 end;
45 end;