This article is about OnShortCut event of Delphi Forms. Lets discuss the requirement first.
Requirement: Assme that I have two Delphi forms in my project (MyForm1 and MyFrom2). Now my requirement is that, if I am on MyForm1 and press ESC, I should go to MyForm2 and vice versa.
Consider the code of MyForm1:
unit uf_MyUnit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons, Vcl.Imaging.jpeg, Vcl.ExtCtrls, Vcl.ComCtrls;
type
TfMyUnit1 = class(TForm)
procedure FormShortCut(var Msg: TWMKey; var Handled: Boolean);
private
public
end;
var
fMyForm1: TfMyUnit1;
implementation
uses uf_MyUnit2;
{$R *.dfm}
procedure TfMyUnit1.FormShortCut(var Msg: TWMKey; var Handled: Boolean);
begin
case Msg.CharCode of
27 : begin
Handled := true;
fMyForm2.Show;
fMyForm1.Close;
end;
end;
end;
end.
Explanation: Remember to add FormShortCut function on the OnShortCut event of the form. By adding this function on the OnShortCut event of the form, this function will immediately gets fired when any key is pressed. '27' is the keycode for ESC key. So when ESC key is pressed fMyForm2 is displayed and current form is closed.
Similar is the code for MyForm2:
unit uf_MyUnit2;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons, Vcl.Imaging.jpeg, Vcl.ExtCtrls, Vcl.ComCtrls;
type
TfMyUnit2 = class(TForm)
procedure FormShortCut(var Msg: TWMKey; var Handled: Boolean);
private
public
end;
var
fMyForm2: TfMyUnit2;
implementation
uses uf_MyUnit1;
{$R *.dfm}
procedure TfMyUnit2.FormShortCut(var Msg: TWMKey; var Handled: Boolean);
begin
case Msg.CharCode of
27 : begin
Handled := true;
fMyForm1.Show;
fMyForm2.Close;
end;
end;
end;
end.
No comments:
Post a Comment