在Delphi中定义快捷方式的"correct"是哪一种方式?
Which way is the "correct" one to define a shortcut in Delphi?
关于如何在 Delphi 程序中定义快捷方式的示例有很多,但是
他们归结为两种不同的方式:
- 将任何 scCtrl、scShift 和 scAlt 常量添加到键的 Ord()
- 使用Menus.ShortCut函数
例如
Action.ShortCut := scCtrl + scShift + Ord('K');
// vs
Action.ShortCut := Menus.ShortCut(Word('K'), [ssCtrl, ssShift]);
这两种方式哪一种更可取?如果是,是哪一个,为什么?
我想说的是,只要有一个功能可以完成这项工作,最好使用该功能。
因为将来有可能发生某些变化,拥有一个函数会给你一个 "hard link" 调用,所以如果函数被弃用,你会收到通知,如果函数逻辑发生变化,你静静地获取更新。
否则,您将无法从中受益。
现在在这种特殊情况下,捷径的定义在未来 10 到 20 年内发生变化的可能性有多大?
大概none。但我仍然提倡函数调用(如果不是为了什么,但你不必记住逻辑(是加法还是逻辑 ORing?稍后可能会问自己)
代码几乎相同,但 ShortCut
有一些额外的检查:
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;
因为 RegisterHotKey function uses Virtual key codes(其值从 $00 到 $FE)这个额外的检查很重要。
注意代替Ord文档,真正的Ord
函数returns smallint(有符号Word
),所以使用国家字符可以更改修饰符,它包含在 ShortCut 值的高字节中。
因此,更优选使用 ShortCut
函数。
关于如何在 Delphi 程序中定义快捷方式的示例有很多,但是 他们归结为两种不同的方式:
- 将任何 scCtrl、scShift 和 scAlt 常量添加到键的 Ord()
- 使用Menus.ShortCut函数
例如
Action.ShortCut := scCtrl + scShift + Ord('K');
// vs
Action.ShortCut := Menus.ShortCut(Word('K'), [ssCtrl, ssShift]);
这两种方式哪一种更可取?如果是,是哪一个,为什么?
我想说的是,只要有一个功能可以完成这项工作,最好使用该功能。
因为将来有可能发生某些变化,拥有一个函数会给你一个 "hard link" 调用,所以如果函数被弃用,你会收到通知,如果函数逻辑发生变化,你静静地获取更新。
否则,您将无法从中受益。
现在在这种特殊情况下,捷径的定义在未来 10 到 20 年内发生变化的可能性有多大? 大概none。但我仍然提倡函数调用(如果不是为了什么,但你不必记住逻辑(是加法还是逻辑 ORing?稍后可能会问自己)
代码几乎相同,但 ShortCut
有一些额外的检查:
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;
因为 RegisterHotKey function uses Virtual key codes(其值从 $00 到 $FE)这个额外的检查很重要。
注意代替Ord文档,真正的Ord
函数returns smallint(有符号Word
),所以使用国家字符可以更改修饰符,它包含在 ShortCut 值的高字节中。
因此,更优选使用 ShortCut
函数。