Help & Manual authoring tool
Setting CanClose property to False presents a couple of problems. This article shows how to overcome them.

Preventing the user from closing a form

Copyright © 2000 Ernesto De Spirito

InstallAWARE - MSI without rocket science

To prevent the user from closing a form you can simply set CanClose to False in the CloseQuery event of the form, but this has two problems:

  1. The Close button in the title bar and the Close menu item in the form's system menu are enabled giving the users the false sensation that they can close the form when actually they can't and then they complain that your application is not working properly. No comments!

  2. In the CloseQuery event you don't have a direct way to know if the user is closing the form or if you are closing the form by code.

You can disable these elements the "Close" menu item in the form's system menu. This is done by calling the EnableMenuItem API function (see the example below). Nonetheless, the user can still close the form using the Alt+F4 key combination, so we have to set the KeyPreview form property to True and write an event handler for the OnKeyDown event to cancel out this hot key.

Here you have the source code:

uses SysUtils, Windows;

procedure TForm1.FormCreate(Sender: TObject);
var
  hSysMenu: HMENU;
begin
  hSysMenu := GetSystemMenu(Self.Handle, False);
  if hSysMenu <> 0 then begin
    EnableMenuItem(hSysMenu, SC_CLOSE,
      MF_BYCOMMAND Or MF_GRAYED);
    DrawMenuBar(Self.Handle);
  end;
  KeyPreview := True;
end;

procedure TForm1.FormKeyDown(Sender: TObject;
  var Key: Word; Shift: TShiftState);
begin
  if (Key = VK_F4) and (ssAlt in Shift) then
    Key := 0;
end;
JfControls Library - for Delphi and C++ Builder
Copyright © 2000/2006 Ernesto De Spirito.   All rights reserved.