I have added the following code to my program which, as i understood, must disable alphabets from being entered. I set the form's KeyPreview property to True, Next i added this code
procedure FormKeyPress(Sender: TObject; var Key: Char) ;
which was defined as
procedure TFibo.FormKeyPress(Sender: TObject; var Key: Char);
begin
if Key in ['a'..'z'] then Key := #0
end;
This does not seem to work, as i am able to enter a-z in the form's edit components; what am i doing wrong?
This is the code for my program
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TFibo = class(TForm)
lblInput: TLabel;
edtInput: TEdit;
procedure FormKeyPress(Sender: TObject; var Key: Char) ;
end;
var
Fibo: TFibo;
implementation
{$R *.dfm}
procedure Tfibo.FormKeyPress(Sender:TObject;var Key:char);
begin
if Key in ['a'.开发者_StackOverflow社区.'z', 'A'..'Z'] then
Key := #0
end;
end.
Your code works fine in that it blocks 'a' to 'z'. Perhaps your problem is that it doesn't block upper case characters. For that you would need:
if Key in ['a'..'z', 'A'..'Z'] then
Key := #0
Problem solved. Setting the OnKeyPress
event in the event tab worked.
Use the Object Inspector of the Form to set the OnkeyPress event. I had written the code but not assigned the event through the Object Inspector. Hence , the event was not registered and it was not firing.
You didn't mention Delphi version. If you're on a pre-Unicode version, simply make sure you handle both lowercase and uppercase char like this:
if Key in ['a'..'z', 'A'..'Z'] then Key := #0;
If you're on Unicode delphi, include the Character
unit and try this:
if TCharacter.IsLetter(Key) then Key := #0;
Or you can try to use IsCharAlpha API function:
if IsCharAlpha(Key) then Key := #0;
While reading between the lines, it seems as if you want to allow upper-case letters, but not lowercase. Instead of filtering the lowercase characters, why not set the CharCase
property of the editbox to ecUpperCase
? That way, all characters entered are converted to uppercase.
精彩评论