Disable Alt-F4 in Delphi program

Posted by webmaster Guido on June 08, 2003

In Reply to: Disable (again) posted by Joey on June 03, 2003

: In a previous topic you told how to disbale the ctrl-alt, alt-tab etc... keys! But these do not work to stop the: ALT-F4 fuction, how do i get about doin this?

With just one line of code, you can disable the Alt-F4 key combination in a Delphi application. Intercept all the keypresses at the level of the form, inspect which keys are pressed, and suppress the keys if Alt+F4 was pressed.

The first thing that you have to do is to set the KeyPreview property of the form to "True". This can be done in the Object Inspector. That way, all the keypresses go to the form first, instead of for example to a menu, or to the component that has the focus,...

Next, also in the Object Inspector, you create an OnKeyDown handler for the form. Next, add a line that inspects keyboard keys that are pressed and suppresses them if necessary:

procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
  if (Key = VK_F4) and (ssAlt in Shift) then Key := 0;
end;

If F4 and ALT are pressed together, this procedure "swallows" the key. Any other key combination is passed on automatically to the next level (to a menu, or to a TEdit, a TButton,...)


Find related articles

Suggested keywords:
  onkeydown,  keypreview,  keypress,  onkeypress


[ Delphi Forum ]
[ DelphiLand: free Delphi source code, tips, tutorials ]