| 1 | unit UKeyboard;
|
|---|
| 2 |
|
|---|
| 3 | interface
|
|---|
| 4 |
|
|---|
| 5 | uses
|
|---|
| 6 | Contnrs, SysUtils, Forms, Classes, Controls;
|
|---|
| 7 |
|
|---|
| 8 | type
|
|---|
| 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 |
|
|---|
| 27 | implementation
|
|---|
| 28 |
|
|---|
| 29 | { TKeyboard }
|
|---|
| 30 |
|
|---|
| 31 | constructor TKeyboard.Create;
|
|---|
| 32 | begin
|
|---|
| 33 | Queue := TQueue.Create;
|
|---|
| 34 | end;
|
|---|
| 35 |
|
|---|
| 36 | destructor TKeyboard.Destroy;
|
|---|
| 37 | begin
|
|---|
| 38 | Queue.Free;
|
|---|
| 39 | inherited;
|
|---|
| 40 | end;
|
|---|
| 41 |
|
|---|
| 42 | function TKeyboard.KeyPressed: Boolean;
|
|---|
| 43 | begin
|
|---|
| 44 | Result := Queue.Count > 0;
|
|---|
| 45 | end;
|
|---|
| 46 |
|
|---|
| 47 | procedure TKeyboard.PressKey(Key: Char);
|
|---|
| 48 | begin
|
|---|
| 49 | Queue.Push(Pointer(Ord(Key)));
|
|---|
| 50 | if Assigned(FOnKeyPressedEvent) then
|
|---|
| 51 | FOnKeyPressedEvent(Self);
|
|---|
| 52 | end;
|
|---|
| 53 |
|
|---|
| 54 | function TKeyboard.ReadKey: Char;
|
|---|
| 55 | begin
|
|---|
| 56 | while Queue.Count = 0 do begin
|
|---|
| 57 | Sleep(10);
|
|---|
| 58 | Application.ProcessMessages;
|
|---|
| 59 | end;
|
|---|
| 60 | Result := Chr(Integer(Queue.Pop));
|
|---|
| 61 | end;
|
|---|
| 62 |
|
|---|
| 63 | function TKeyboard.ReadLn: string;
|
|---|
| 64 | var
|
|---|
| 65 | Key: Char;
|
|---|
| 66 | begin
|
|---|
| 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);
|
|---|
| 81 | end;
|
|---|
| 82 |
|
|---|
| 83 | end.
|
|---|