Jonas
Jonas

Reputation: 1373

How to disable copy/paste in TEdit

I would like to prevent copy, cut and paste in my TEdit. How can I do this?

I tried setting the Key=NULL on KeyDown event when CTRL+V was pressed on the control, but it didn't work.

Upvotes: 3

Views: 6048

Answers (6)

T.G. Grace
T.G. Grace

Reputation: 35

An old question, but the same bad answers are still floating around.

unit LockEdit;

// Version of TEdit with a property CBLocked that prevents copying, pasting,
// and cutting when the property is set.

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils, StdCtrls, Windows;

type

  TLockEdit = class(TEdit)
  protected
      procedure WndProc(var msg: TMessage); override;
  private
      FLocked: boolean;
  public
      property CBLocked: boolean read FLocked write FLocked default false;
  end;

implementation

  procedure TLockEdit.WndProc(Var msg: TMessage);
  begin
  if ((msg.msg = WM_PASTE) or (msg.msg = WM_COPY) or (msg.msg = WM_CUT))
      and CBLocked
          then msg.msg:=WM_NULL;
  inherited;
  end;

end.                

Upvotes: 0

Lionmaru
Lionmaru

Reputation: 180

Uses Clipbrd;

procedure TForm1.Edit1Enter(Sender: TObject);
begin
  Clipboard.AsText := '';
end;

Upvotes: 0

Marus Gradinaru
Marus Gradinaru

Reputation: 3120

Assign this to TEdit.OnKeyPress :

procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char);
begin
 if (Key=#22) or (Key=#3) then Key:=#0;   // 22 = [Ctrl+V] / 3 = [Ctrl+C]
end;

Upvotes: 5

dschaeffer
dschaeffer

Reputation: 618

I know this is an old question but I'll add what I have found. The original poster almost had the solution. It works fine if you ignore cut/copy/paste in the key press event instead of the key down event. ie (c++ builder)

void __fastcall Form::OnKeyPress(TObject *Sender, System::WideChar &Key)
{
   if( Key==0x03/*ctrl-c*/ || Key==0x16/*ctrl-v*/ || Key==0x018/*ctrl-x*/ )
      Key = 0;  //ignore key press
}

Upvotes: 2

Josh Kelley
Josh Kelley

Reputation: 58402

You'll need to prevent the WM_CUT, WM_COPY, and WM_PASTE messages from being sent to your TEdit. This answer describes how do to this using just the Windows API. For the VCL, it may be sufficient to subclass TEdit and change its DefWndProc property or override its WndProc method.

Upvotes: 5

Łukasz Lew
Łukasz Lew

Reputation: 50338

You can use some global programs that grab shortcuts and block C-V C-C C-X when TEdit window is active

Upvotes: 0

Related Questions