在 Delphi 10.4.2 Win32 VCL 应用程序中,并基于问题 + 解决方案 here它提供了一种获取快捷键的字符串表示形式的方法(但大概不可能同时为快捷键传递 SHIFTSTATE)我写了这段代码:
function MyGetSpecialShortcutName(ShortCut: TShortCut): string;
// gets shortcut name for e.g. VK_NUMPAD0 where TMenuItem.Shortcut gets the wrong shortcut name
var
ScanCode: Integer;
KeyName: array[0..255] of Char;
begin
Result := '';
FillChar(KeyName, SizeOf(KeyName), 0);
ScanCode := Winapi.Windows.MapVirtualKey(LoByte(Word(ShortCut)), 0) shl 16;
if ScanCode <> 0 then
begin
if Winapi.Windows.GetKeyNameText(ScanCode, KeyName, Length(KeyName)) <> 0 then
Result := KeyName;
end;
end;
function GetSpecialShortcutNameWithShiftState(const AScanCode: Word; const AShiftState: System.Classes.TShiftState = []): string;
begin
Result := MyGetSpecialShortcutName(Vcl.Menus.ShortCut(AScanCode, AShiftState));
end;
用法:
Result := GetSpecialShortcutNameWithShiftState(VK_A, [ssCTRL]);
但是,结果是“A”,而预期的结果应该是“CTRL+A”。
如何获取包含 SHIFTSTATE 的快捷键的字符串表示形式?
最佳答案
OP 想要键名完全本地化,但为了完整起见,我首先展示 VCL 已经有一个函数来获取部分未本地化的字符串,即 ShortCutToText
在 Menus
单元中:
ShortCutToText(ShortCut(Ord('A'), [ssShift, ssAlt]))
这会在所有系统上返回 Shift+Alt+A
。
现在,使用 Win32 函数 GetKeyNameText
Q中已经提到,很容易获得完全本地化的快捷字符串:
function GetKeyName(AKey: Integer): string;
var
name: array[0..128] of Char;
begin
FillChar(name, SizeOf(name), 0);
GetKeyNameText(MapVirtualKey(AKey, 0) shl 16, @name[0], Length(name));
Result := name;
end;
function ModifierVirtualKey(AModifier: Integer): Integer;
begin
case AModifier of
Ord(ssShift):
Result := VK_SHIFT;
Ord(ssCtrl):
Result := VK_CONTROL;
Ord(ssAlt):
Result := VK_MENU;
else
Result := 0;
end;
end;
function ShortcutToString(AKey: Integer; AShiftState: TShiftState = []): string;
begin
Result := '';
for var Modifier in AShiftState do
begin
var ModifierKey := ModifierVirtualKey(Ord(Modifier));
if ModifierKey <> 0 then
Result := Result + IfThen(not Result.IsEmpty, '+') + GetKeyName(ModifierKey);
end;
Result := Result + IfThen(not Result.IsEmpty, '+') + GetKeyName(AKey);
end;
(这里我使用了 StrUtils
中的 IfThen
overload。)
现在,
ShortcutToString(Ord('A'), [ssShift, ssAlt])
在我的瑞典语系统上返回 SKIFT+ALT+A
。您可能已经猜到,SKIFT
是 SHIFT
键的瑞典语名称。
关于delphi - 如何获取包含 SHIFTSTATE 的快捷键的字符串表示形式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66782162/