Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does TEdit.OnChange trigger when Ctrl+A is pressed?

I am running a Delphi XE7 VCL app on Windows 7.

I have observed that the TEdit.OnChange event triggers when Ctrl+A (select all) is pressed. Why is that?

I need to reliably trigger the OnChange event only when the text in the TEdit really changes. Unfortunately, no OnBeforeChange event is available so I can compare the text before and after a change.

So, how to implement a reliable OnChange event for TEdit?

like image 818
Server Overflow Avatar asked Feb 14 '17 15:02

Server Overflow


1 Answers

Yes, it's not a bad base implementation:

procedure TCustomEdit.CNCommand(var Message: TWMCommand);
begin
  if (Message.NotifyCode = EN_CHANGE) and not FCreating then Change;
end;

This message comes not taking in consideration that the 'A' that is the button that is firing the EN_CHANGE, currently comes together with the state of ctrl pressed.

What you can do is check if Ctrl is pressed or not:

procedure TForm44.edt1Change(Sender: TObject);

  function IsCtrlPressed: Boolean;
  var
    State: TKeyboardState;
  begin
    GetKeyboardState(State);
    Result := ((State[VK_CONTROL] and 128) <> 0);
  end;
begin
  if IsCtrlPresed then
    Exit;

  Caption := 'Ctrl is not pressed';
end;

To avoid reading the state of the whole key board, you can do what was suggested by David Heffernan:

procedure TForm44.edt1Change(Sender: TObject);

  function IsCtrlPresed: Boolean;
  begin
    Result := GetKeyState(VK_CONTROL) < 0;
  end;
begin
  if IsCtrlPresed then
    Exit;

  Caption := 'Ctrl is not pressed';
end;
like image 115
Rodrigo Farias Rezino Avatar answered Oct 10 '22 00:10

Rodrigo Farias Rezino