Mega Code Archive

 
Categories / Delphi / Examples
 

Playing with style Part 2

Title: Playing with style - Part 2 Question: I need a quick way to make a TEdit accepts only numeric charaters. How? Answer: You can obtain this result by adding the ES_NUMBER style to the edit field ones. Try this: procedure NumericOnly(theEdit: TEdit); var dwStyle: Longint; begin dwStyle := GetWindowLong(theEdit.Handle, GWL_STYLE) or ES_NUMBER; SetWindowLong(theEdit.Handle, GWL_STYLE, dwStyle); end; Important: With this style set, the edit field accepts only numeric characters; this mean that you cannot use dots, hyphens or any other punctuation mark!!! Of course you can derive a numeric only edit field from the base class TEdit in this way: unit NumericEdit; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TNumericEdit = class(TEdit) private { Private declarations } protected { Protected declarations } procedure CreateParams(var Params: TCreateParams); override; public { Public declarations } published { Published declarations } end; procedure Register; implementation procedure Register; begin RegisterComponents('Bigpepe', [TNumericEdit]); end; { TNumericEdit } procedure TNumericEdit.CreateParams(var Params: TCreateParams); begin inherited; Params.Style := Params.Style or ES_NUMBER; end; end. Is important to keep in mind that even if the derived control accepts only numeric characters, you can still set its Text property to any alphanumeric value. Enjoy!