在閱讀代碼時,我發現在KeyDown事件中您可以設定Key := 0;為進一步停止處理該事件。例如:TIncrementalForm.FormKeyDown被編碼為:
procedure TIncrementalForm.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if Key = VK_RETURN then begin
Key := 0; // Stop processing by input window
if Shift = [ssShift] then
btnPrevClick(nil)
else
btnNextClick(nil);
end;
end;
另一個例子來自unit FindFrm:
procedure TFindForm.cboFindTextKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if Key = VK_TAB then begin
cboFindText.SelText := #9;
Key := 0; // prevent propagation
end;
end;
我自己測驗過,但它不起作用:
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TForm1 = class(TForm)
Memo1: TMemo;
Memo2: TMemo;
Button1: TButton;
procedure Memo1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
private const
VK_X = Ord('X');
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Memo1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if Key = VK_X then
begin
Key := 0;
Memo2.Lines.Add('yes');
end;
end;
end.
我的意圖是:每當用戶按住控制元件x中的鍵時,TMemo我都會執行一些業務邏輯(即在備忘錄中添加“是”)并停止進一步處理。但結果是密鑰x仍然插入到TMemo文本中。我想知道如何禁用默認鍵按住事件行為(插入相應的鍵)。
uj5u.com熱心網友回復:
這里的關鍵(沒有雙關語)是使用OnKeyPress而不是OnKeyDown:
procedure TForm1.Memo1KeyPress(Sender: TObject; var Key: Char);
begin
if Key = 'x' then
begin
Key := #0;
Memo1.Lines.Add('yes');
end;
end;
uj5u.com熱心網友回復:
不是答案,而是評論,但我需要發布代碼,所以......
您可以使用以下函式測驗當前的Shift 狀態:
CONST
VK_ALT = VK_MENU;
VK_CTRL = VK_CONTROL;
FUNCTION KeyPressed(VirtualKey : WORD) : BOOLEAN;
BEGIN
Result:=(GetKeyState(VirtualKey) AND $80000000<>0)
END;
FUNCTION Shift : BOOLEAN;
BEGIN
Result:=KeyPressed(VK_SHIFT)
END;
FUNCTION Alt : BOOLEAN;
BEGIN
Result:=KeyPressed(VK_ALT)
END;
FUNCTION Ctrl : BOOLEAN;
BEGIN
Result:=KeyPressed(VK_CTRL)
END;
但請注意,您必須在鍵盤事件的尾端和新的鍵盤事件發生之前呼叫這些函式,因為此呼叫將回傳來自最新鍵盤事件的狀態,而不是當時必須處于活動狀態的狀態你想要(如果你在鍵盤事件處理程式之外呼叫它)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/418501.html
標籤:
下一篇:將圖片上傳到服務器時應用程式凍結
