1. Computing

Extending TCustomEditControls (TMemo, TRichEdit) with a ViewOnly property

ViewOnly property: a better mix of ReadOnly and Enabled

From , former About.com Guide

Code submitted by Jens Borrisholt

In Delphi, descendants of the TCustomEdit type, like TEdit, TMemo and TRichEdit, expose two properties you can use to make the editor not-editable.

ReadOnly property determines whether the user can change the text of the edit control. To restrict the edit control to display only, set the ReadOnly property to true.

When ReadOnly is true, a user cannot edit the contents of the edit control BUT he or she CAN select a block of text, activate the default context menu and, for example, copy the selected text.
Plus: when ReadOnly is true - a user can still enter the control.

Enabled property controls whether the control responds to mouse, keyboard, and timer events. To disable a control, set Enabled to false. Disabled controls appear dimmed / grayed.

ViewOnly?

How about a ViewOnly property that would be a mix or Enabled and ReadOnly where the control with ViewOnly set to true will not be grayed, will be read only but a user will not be able to set the input focus to the control?

ViewOnly = [+ReadOnly, +Disabled, -Grayed]

The idea is to somehow extend every TCustomEdit descendant with a ViewOnly property so that it is possible to write : Memo1.ViewOnly := True, or Edit1.ViewOnly := True.

Extend existing controls by adding new properties? Class helpers!

Here's the interface part (full unit plus a demo project available for download) of the TCustomEditHelper class helper for TCustomEdit (and descendants):

 TCustomEditHelper = class Helper for TCustomEdit
 strict private
   function GetHookControl : TObject;
   function GetViewOnly: Boolean;
   procedure SetViewOnly(const Value: Boolean) ;
 public
   property ViewOnly : Boolean read GetViewOnly write SetViewOnly;
 end;
 

Download Viewonly unit + demo application.

Interested in Extending TWinControl with a ViewOnly property?

©2013 About.com. All rights reserved.