1. Computing

Extending TWinControl with a ViewOnly property

ReadOnly, Not Enabled, Not Grayed

From , former About.com Guide

Code submitted by Jens Borrisholt

In the Extending TCustomEditControls (TMemo, TRichEdit) with a ViewOnly property a usage of class helpers in Delphi for Win32 was "put to test".

Using class helpers I was able to add a "ViewOnly" property to any TCustomEditControl descendant like TEdit, TMemo or TRichEdit.

ViewOnly property is a mix of 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 for TWinControl descendants

In the VCL hierarchy the TWinControl type is the base class for all controls that are wrappers for Windows screen objects: TButton, TEdit, TMemo, TListBox, TCheckBox, etc.

Controls that extend the TWinControl class can receive user input focus and can serve as a container for other controls.

Here's the interface of the TWinControlHelper (implementation and the full source code available for download).

 TWinControlHelper = class Helper for TWinControl
 strict private
   function GetHookControl : TObject;
   function GetViewOnly: Boolean;
   procedure SetViewOnly(const Value: Boolean) ;
   function GetCanViewOnly: Boolean;
   procedure SetCanViewOnly(const Value: Boolean) ;
 public
   property ViewOnly : Boolean read GetViewOnly write SetViewOnly;
   property CanViewOnly : Boolean read GetCanViewOnly write SetCanViewOnly;
 end;
 

Here's how to use the new ViewOnly property - a class helpers gem:

  1. Take a form, new (empty) or existing.
  2. If there are no controls on the form, drop some.
  3. Add ViewOnlyU to the uses clause
  4. Add a button on your form, name the button btnViewOnly.
  5. Inside the form's OnCreate event handler add a line of code: btnViewOnly.CanViewOnly := False;
  6. Implement the OnClick event handler for the btnViewOnly as:
     procedure TTestForm.btnViewOnlyClick(Sender: TObject) ;
     begin
       ViewOnly := not ViewOnly;
     end;
     
You now have a form with a "ViewOnly" mode, automatically applied to it and all its child controls.

Download WinControls ViewOnly unit + demo application.

©2013 About.com. All rights reserved.