zeus
zeus

Reputation: 13357

How to automatically change the font color of a TcustomEdit when we set readonly to true

I want to update the font color of all my edit when they are set to readonly. For this I update TCustomEdit like this:

TMyCustomEdit = class(TCustomEdit)
private
  procedure EMSetReadOnly        (var Message: TMessage);      message 
end; 

procedure TMyCustomEdit.EMSetReadOnly (var Message: TMessage);
begin
  inherited;
  font.Color := clred;
end;

But i do not understand why this not work :( Ideally i want that my readonly Edit to have the same design than a disabled Tedit

Upvotes: 0

Views: 524

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 596121

Well, for starters, your code is incomplete, it should look more like this instead:

type
  TMyCustomEdit = class(TCustomEdit)
  private
    procedure EMSetReadOnly(var Message: TMessage); message EM_SETREADONLY;
    procedure UpdateFont;
  protected
    procedure CreateWnd; override;
  end;

procedure TMyCustomEdit.EMSetReadOnly(var Message: TMessage);
begin
  inherited;
  UpdateFont;
end;

procedure TMyCustomEdit.CreateWnd;
begin
  inherited;
  UpdateFont;
end;

procedure TMyCustomEdit.UpdateFont;
begin
  if (GetWindowLongPtr(Handle, GWL_STYLE) and ES_READONLY) <> 0 then
    Font.Color := clRed
  else
    Font.Color := clWindowText;
end;

With that said, to work correctly at runtime, you need to make sure that all of your Edit objects are actually using this class and not the standard TEdit class. If you want to do this at design-time, you would have to put this class into a package and install it into the IDE.

A simpler way is to just turn this into an interposer class instead:

type
  TEdit = class(Vcl.StdCtls.TEdit)
    ... same code as above ...
  end;

Place this class declaration above your TForm class declaration. Or in a separate unit that is included in your uses clause after the Vcl.StdCtrls unit. Either way, the DFM streaming system will use the last declared definition of TEdit for all TEdit objects in the TForm. No IDE installation required.

Upvotes: 4

Related Questions