source: TEditExtensions/UIPv4Edit.pas

Last change on this file was 1, checked in by chronos, 13 years ago
  • Added: TEDitExtensions component.
File size: 2.3 KB
Line 
1unit UIPv4Edit;
2
3interface
4
5uses
6 Classes, SysUtils, StdCtrls, StrUtils;
7
8type
9
10{ TIPv4Edit }
11
12 TIPv4Edit = class(TEdit)
13 private
14 FAddress: Cardinal;
15 procedure ChangeExecute(Sender: TObject);
16 procedure SetAddress(const AValue: Cardinal);
17 public
18 function TryStrToIPv4(S: string; out Value: Cardinal): Boolean;
19 constructor Create(AOwner: TComponent); override;
20 destructor Destroy; override;
21 published
22 property Address: Cardinal read FAddress write SetAddress;
23 end;
24
25procedure Register;
26
27implementation
28
29procedure Register;
30begin
31 RegisterComponents('TEditExtensions', [TIPv4Edit]);
32end;
33
34{ TIPv4Edit }
35
36procedure TIPv4Edit.ChangeExecute(Sender: TObject);
37var
38 NewText: string;
39 Temp: Cardinal;
40begin
41 NewText := Text;
42 Delete(NewText, SelStart + 1, 1);
43 if TryStrToIPv4(NewText, Temp) then
44 FAddress := Temp;
45 SetAddress(FAddress);
46end;
47
48procedure TIPv4Edit.SetAddress(const AValue: Cardinal);
49var
50 LastPos: Integer;
51 Adr: string;
52 I: Integer;
53 Octet: string;
54begin
55 FAddress := AValue;
56 LastPos := SelStart;
57 OnChange := nil;
58 Adr := '';
59 for I := 0 to 3 do begin
60 Octet := IntToStr((FAddress shr (24 - (I * 8))) and $ff);
61 Adr := Adr + Octet + DupeString(' ', 3 - Length(Octet));
62 if I < 3 then Adr := Adr + '.';
63 end;
64 Text := Adr;
65 OnChange := ChangeExecute;
66 if LastPos = 3 then LastPos := 4;
67 if LastPos = 7 then LastPos := 8;
68 if LastPos = 11 then LastPos := 12;
69 SelStart := LastPos;
70end;
71
72function TIPv4Edit.TryStrToIPv4(S: string; out Value: Cardinal): Boolean;
73var
74 P: Integer;
75 Octet: Integer;
76 OctetText: string;
77 I: Integer;
78begin
79 Result := False;
80 Value := 0;
81 for I := 0 to 3 do begin
82 if I < 3 then begin
83 P := Pos('.', S);
84 if P > 0 then
85 OctetText := Copy(S, 1, P - 1) else Exit;
86 Delete(S, 1, P);
87 end else OctetText := S;
88 if TryStrToInt(Trim(OctetText), Octet) then begin
89 if (Octet >= 0) and (Octet <= 255) then
90 Value := Value or (Byte(Octet) shl (24 - (I * 8)))
91 else Exit;
92 end else Exit;
93 end;
94 Result := True;
95end;
96
97constructor TIPv4Edit.Create(AOwner: TComponent);
98begin
99 inherited Create(AOwner);
100 OnChange := ChangeExecute;
101end;
102
103destructor TIPv4Edit.Destroy;
104begin
105 inherited Destroy;
106end;
107
108end.
109
Note: See TracBrowser for help on using the repository browser.