2007. május 11., péntek

Disable the select and copy to clipboard capabilities in a TMemo


Problem/Question/Abstract:

How to disable the select and copy to clipboard capabilities in a TMemo

Answer:

Solve 1:

Use OnKeyDown and OnKeyPress handlers for the memo to catch the shortcuts for copy and cut and set key := 0 for them. Provide a handler for the OnContextMenu event in which you set Handled to true to prevent the default popup menu from coming up. That should do it.

procedure TForm1.Memo1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
  if ssCtrl in Shift then
    case Key of
      Ord('C'), Ord('X'), VK_INSERT: Key := 0;
    end
  else if (ssShift in Shift) and (Key = VK_DELETE) then
    Key := 0;
end;

procedure TForm1.Memo1ContextPopup(Sender: TObject; MousePos: TPoint;
  var Handled: Boolean);
begin
  Handled := true;
end;

procedure TForm1.Memo1KeyPress(Sender: TObject; var Key: Char);
begin
  if Key in [^C, ^X] then
    Key := #0;
end;


Solve 2:

The easiest way would be to set the Enabled property of the Memo (or Edit) control to False so that the control cannot receive events. This drawback to this method is the user won't be able to scroll the text and the disabled text looks bad.

In order to prevent the user from writing in the memo, we set its ReadOnly property to True.

To prevent the user from selecting text with the mouse, we generate the handler of the MouseMove event of the control and write the following code:

procedure TForm1.Memo1MouseMove(Sender: TObject;
  Shift: TShiftState; X, Y: Integer);
begin
  if ssLeft in Shift then
    Memo1.SelLength := 0;
end;

In order to prevent the user from performing a selection using the keyboard, we generate the handlers of the KeyDown and KeyUp events, assigning the OnKeyDown and OnKeyUp properties to the same procedure:

procedure TForm1.Memo1KeyDownUp(Sender: TObject;
  var Key: Word; Shift: TShiftState);
begin
  if (ssShift in Shift) and (Key in [VK_LEFT, VK_RIGHT, VK_UP,
    VK_DOWN, VK_PRIOR, VK_NEXT, VK_HOME, VK_END]) then
    Key := 0;
end;

Nincsenek megjegyzések:

Megjegyzés küldése