source: Console test/UKeyboard.pas

Last change on this file was 2, checked in by george, 15 years ago
  • Přidáno: Prvotní načtení tříd.
File size: 1.7 KB
Line 
1unit UKeyboard;
2
3interface
4
5uses
6 Contnrs, SysUtils, Forms, Classes, Controls;
7
8type
9 TShowKeyEvent = procedure(Key: Char) of object;
10
11 TKeyboard = class
12 private
13 FOnKeyPressedEvent: TNotifyEvent;
14 FOnShowKey: TShowKeyEvent;
15 published
16 Queue: TQueue;
17 constructor Create;
18 function KeyPressed: Boolean;
19 function ReadKey: Char;
20 function ReadLn: string;
21 destructor Destroy; override;
22 procedure PressKey(Key: Char);
23 property OnKeyPressed: TNotifyEvent read FOnKeyPressedEvent write FOnKeyPressedEvent;
24 property OnShowKey: TShowKeyEvent read FOnShowKey write FOnShowKey;
25 end;
26
27implementation
28
29{ TKeyboard }
30
31constructor TKeyboard.Create;
32begin
33 Queue := TQueue.Create;
34end;
35
36destructor TKeyboard.Destroy;
37begin
38 Queue.Free;
39 inherited;
40end;
41
42function TKeyboard.KeyPressed: Boolean;
43begin
44 Result := Queue.Count > 0;
45end;
46
47procedure TKeyboard.PressKey(Key: Char);
48begin
49 Queue.Push(Pointer(Ord(Key)));
50 if Assigned(FOnKeyPressedEvent) then
51 FOnKeyPressedEvent(Self);
52end;
53
54function TKeyboard.ReadKey: Char;
55begin
56 while Queue.Count = 0 do begin
57 Sleep(10);
58 Application.ProcessMessages;
59 end;
60 Result := Chr(Integer(Queue.Pop));
61end;
62
63function TKeyboard.ReadLn: string;
64var
65 Key: Char;
66begin
67 Result := '';
68 repeat
69 Key := ReadKey;
70 if Key = #8 then begin
71 if Length(Result) > 0 then SetLength(Result, Length(Result) - 1)
72 else Key := #0;
73 end else
74 if Key = #13 then
75 else Result := Result + Key;
76 if Assigned(FOnShowKey) then
77 FOnShowKey(Key);
78 until Key = #13;
79 if Assigned(FOnShowKey) then
80 FOnShowKey(#10);
81end;
82
83end.
Note: See TracBrowser for help on using the repository browser.