我想要一个关键控制相机. TForm没有Onkeypress所以如何从键盘读取这个输入? procedure TForm2.FormKeyPress(Sender: TObject; var Key: Char);var ok: boolean;begin ok := true; case Key of 'a': camera1.Position.y:=camera1.
procedure TForm2.FormKeyPress(Sender: TObject; var Key: Char); var ok: boolean; begin ok := true; case Key of 'a': camera1.Position.y:=camera1.Position.y+1; 'A': camera1.Position.y:=camera1.Position.y+1; 'd': camera1.Position.y:=camera1.Position.y-1; 'D': camera1.Position.y:=camera1.Position.y-1; 'w': camera1.Position.X:=camera1.Position.X-1; 'W': camera1.Position.X:=camera1.Position.X-1; 'x': camera1.Position.X:=camera1.Position.X+1; 'X': camera1.Position.X:=camera1.Position.X+1; 'q': camera1.RotationAngle.z := camera1.RotationAngle.z-1; 'Q': camera1.RotationAngle.z := camera1.RotationAngle.z-1; 'e': camera1.RotationAngle.z := camera1.RotationAngle.z+1; 'E': camera1.RotationAngle.z := camera1.RotationAngle.z+1; 'z': camera1.Position.z:=camera1.Position.z+1; 'Z': camera1.Position.z:=camera1.Position.z+1; 'c': camera1.Position.z:=camera1.Position.z-1; 'C': camera1.Position.z:=camera1.Position.z-1; else ok := false; end; {case} //if ok then // Invalidate; positionChange(camera1); RotationAngleChange(camera1); end;更新到最新版本的XE2(AFAIK Update 4 Hotfix 1)和
请改用TForm.OnKeyDown或TForm.OnKeyUp事件.这是我用过的快速测试:
procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); begin case KeyChar of 'A'..'Z', 'a'..'z': Caption := 'Got an alpha ' + KeyChar; '0'..'9': Caption := 'Got a number ' + KeyChar; else Caption := 'Got something else ' + KeyChar; end; KeyChar := #0; end;
根据这个Embarcadero forums post,在没有上述更新的XE2中你需要实际覆盖TForm.KeyDown事件(根据@ TLama的请求添加;他是找到它并在评论中发布到我的答案的人):
type TForm1 = class(TForm) Memo1: TMemo; private public procedure KeyDown(var Key: Word; var KeyChar: Char; Shift: TShiftState); override; end; implementation procedure TForm1.KeyDown(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); begin case KeyChar of 'A'..'Z', 'a'..'z': Caption := 'Got an alpha ' + KeyChar; '0'..'9': Caption := 'Got a number ' + KeyChar; else Caption := 'Got something else ' + KeyChar; end; KeyChar := #0; end;
(就像一个注释,你可以稍微缩短你的代码):
procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); begin ok := true; case KeyChar of 'A', 'a': camera1.Position.y:=camera1.Position.y+1; 'D', 'd': camera1.Position.y:=camera1.Position.y-1; 'W', 'w': camera1.Position.X:=camera1.Position.X-1; 'X', 'x': camera1.Position.X:=camera1.Position.X+1; 'Q', 'q': camera1.RotationAngle.z := camera1.RotationAngle.z-1; 'E', 'e': camera1.RotationAngle.z := camera1.RotationAngle.z+1; 'Z', 'z': camera1.Position.z:=camera1.Position.z+1; 'C', 'c': camera1.Position.z:=camera1.Position.z-1; else ok := false; end; {case} if ok then begin // Invalidate; KeyChar := #0; // Remove keystroke, because you've handled it end; positionChange(camera1); RotationAngleChange(camera1); end;