use*_*268 0 delphi action keyboard-shortcuts hotkeys
我用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.
Run Code Online (Sandbox Code Playgroud)
然而,当我按下 时ctrl+d,什么也没发生。我尝试调试它,发现它ctrl+d永远不会触发操作的快捷方式。为什么会发生这样的事?如何修复它?我过去使用过快捷功能并且它有效。
尝试Word('D'),或常数vkD,而不是Word('d')。快捷方式使用虚拟键代码,字母使用其大写值表示为虚拟键。在编辑控件中键入大写或小写字母使用相同的虚拟键,当该键转换为文本字符时,当前的 Shift 状态决定了字母的大小写。
另请注意,VCL在用于创建值的单元中拥有自己的ShortCut()函数(以及TextToShortCut()),因此您无需编写自己的函数。Vcl.MenusTShortCut
请参阅表示键和快捷方式,特别是将快捷方式表示为 TShortCut 的实例。
另外,您TAction在设计时就明确地放置在表单上,因此您应该简单地ShortCut使用对象检查器而不是在代码中分配它。然后这些细节将由框架自动为您处理。