我用 Delphi 10.4 撰寫了一個程式。UI 的主要部分只是一個 TMemo。當用戶在其中輸入內容時,應用程式會自動將 TMemo 中的文本復制到剪貼板。它看起來像這樣:

這個自動復制部分運行良好。但是,我也想讓用戶通過快捷方式更改深色主題或淺色主題。我啟用了深色主題和淺色主題。

代碼如下所示:
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Clipbrd, System.Actions,
Vcl.ActnList, Vcl.Themes;
type
TForm1 = class(TForm)
txt: TMemo;
ActionList1: TActionList;
act_change_theme: TAction;
procedure txtChange(Sender: TObject);
procedure act_change_themeExecute(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
var
is_dark: Boolean;
implementation
{$R *.dfm}
function ShortCut(Key: Word; Shift: TShiftState): TShortCut;
begin
Result := 0;
if HiByte(Key) <> 0 then
Exit; // if Key is national character then it can't be used as shortcut
Result := Key;
if ssShift in Shift then
Inc(Result, scShift); // this is identical to " " scShift
if ssCtrl in Shift then
Inc(Result, scCtrl);
if ssAlt in Shift then
Inc(Result, scAlt);
end;
procedure TForm1.act_change_themeExecute(Sender: TObject);
begin
if is_dark then
begin
TStyleManager.TrySetStyle('Windows', false);
is_dark := false;
end
else
begin
TStyleManager.TrySetStyle('Carbon', false);
is_dark := true;
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
is_dark := false;
act_change_theme.ShortCut := ShortCut(Word('d'), [ssCtrl]);
end;
procedure TForm1.txtChange(Sender: TObject);
begin
try
Clipboard.AsText := txt.Lines.GetText;
except
on E: Exception do
end;
end;
end.
但是,當我按下 時ctrl d,什么也沒發生。我試圖除錯它,我發現它ctrl d永遠不會觸發操作的快捷方式。為什么會這樣?如何解決?我過去使用過快捷功能并且它有效。
uj5u.com熱心網友回復:
TryWord('D')或常量vkD,而不是Word('d')。快捷方式使用虛擬鍵代碼,字母使用它們的大寫值表示為虛擬鍵。在編輯控制元件中輸入大寫或小寫字母使用相同的虛擬鍵,當鍵轉換為文本字符時,當前的移位狀態決定了字母的大小寫。
另請注意,VCL在創建值的單元中有自己的ShortCut()函式(也有TextToShortCut()),因此您無需撰寫自己的函式。Vcl.MenusTShortCut
請參閱表示鍵和快捷方式,尤其是將快捷方式表示為 TShortCut 的實體。
此外,您TAction在設計時明確放置在表單上,??因此您應該ShortCut使用物件檢查器簡單地分配它,而不是在代碼中。然后框架會自動為您處理這些細節。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/343686.html
