Hola bit.
Si estas programando para GUI, te faltó aclarar sobre que control deseas realizar la comprobacion. Como lo mas común es que sea una instancia de
TEdit, voy a usar este componente para ejemplo.
Para números naturales:
Código Delphi
[-]
...
uses Windows;
procedure TForm1.FormCreate(Sender: TObject);
begin
SetWindowLong(Edit1.Handle, GWL_STYLE,
GetWindowLong(Edit1.Handle, GWL_STYLE) + ES_NUMBER);
end;
Para números reales:
Código Delphi
[-]
procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char);
begin
with Sender as TEdit do
ReadOnly:= (not (Key in[ #8,'0'..'9','-',DecimalSeparator])) or
((Key = DecimalSeparator)and(Pos(DecimalSeparator, Text)> 0) or
((Key = '-')and(SelStart<>0)));
end;
procedure TForm1.Edit1Exit(Sender: TObject);
var
d: Double;
begin
with (Sender as TEdit) do
if not TryStrToFloat(Text, d) then
begin
SetFocus;
raise Exception.Create('Ingrese un número válido');
end;
end;
Si en cambio estas en modo consola, la cosa se complica un poco:
Código Delphi
[-]
program Project1;
uses Windows, SysUtils;
function Readkey: Char;
var
hConsoleInput: THandle;
lpBuffer: INPUT_RECORD;
nLength: Longword;
begin
Result:= #0;
hConsoleInput:= GetStdHandle(STD_INPUT_HANDLE);
if hConsoleInput <> INVALID_HANDLE_VALUE then
while ReadConsoleInput(hConsoleInput, lpBuffer, 1, nLength) do
if (lpBuffer.EventType = KEY_EVENT) and (TKeyEventRecord(lpBuffer.Event).bKeyDown) then
begin
Result:= TKeyEventRecord(lpBuffer.Event).AsciiChar;
Exit;
end;
end;
var
ch: Char;
num : Integer;
begin
Write('Ingrese un numero: ');
repeat
ch := ReadKey;
if ch in ['0'..'9'] then
begin
write(ch);
num:= num *10 + Ord(ch)-48
end;
until ch = #13;
Writeln(#10,'Ingreso el numero: ', num);
Readln;
end.
Saludos
Edito: No había visto el mensaje de Iván y repetí la función que publicó