在一个应用程序上,我有一个键盘钩子,当按下 Escape 按钮时,它会关闭一个 MDI 子窗体。打开 TOpenDialog 类后代时出现问题(使用Execute)。考虑以下代码(仅用于示例)
unit Unit4;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm4 = class(TForm)
OpenDialog1: TOpenDialog;
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
function KeyboardProc(code: integer; wp: WPARAM; lp: LPARAM): LResult stdcall;
function CanDoCloseOnEscape: boolean;
var
Form4: TForm4;
KeybHook : HHook;
implementation
{$R *.dfm}
function CanDoCloseOnEscape: boolean;
var
Control: TWinControl;
Form: TForm;
begin
Control := Screen.ActiveControl;
Form := Screen.ActiveForm;
Result := true;
end;
function KeyboardProc(code: integer; wp: WPARAM; lp: LPARAM): LResult stdcall;
begin
case wp of
VK_ESCAPE:
if CanDoCloseOnEscape then
begin
PostMessage(Screen.ActiveForm.Handle, WM_Close, 0, 0);
exit;
end;
end;
end;
procedure TForm4.Button1Click(Sender: TObject);
begin
if OpenDialog1.Execute then
begin
ShowMessage('executed');
end;
end;
initialization
KeybHook := SetWindowsHookEx(WH_KEYBOARD, KeyboardProc, hInstance,GetWindowTask(application.Handle));
finalization
UnhookWindowsHookEx(KeybHook);
end.
控制 := Screen.ActiveControl;
- 没有将 opendialog 作为主动控件。
因此,即使对话框仍然打开,也会执行键盘挂钩并关闭表单。