2007. július 12., csütörtök

Disable the close button of a TForm


Problem/Question/Abstract:

How to disable the close button of a TForm

Answer:

Solve 1:

procedure EnableCloseButton(const bEnable: Boolean);
const
  MenuFlags: array[Boolean] of Integer = (MF_DISABLED, MF_ENABLED);
var
  hSysMenu: HMENU;
begin
  hSysMenu := GetSystemMenu(Handle, False);
  if hSysMenu > 0 then
    EnableMenuItem(hSysMenu, SC_CLOSE, MF_BYCOMMAND or MenuFlags[bEnable]);
end;


Solve 2:

The usual approach is to disable or enable the corresponding item in the forms system menu. However, that does not work for all of them. You can always trap the WM_SYSCOMMAND message caused by clicking on the items and not pass it on, but this way the border icons do not appear disabled.

{ ... }
EnableMenuItem(GetSystemMenu(handle, False), SC_CLOSE, MF_BYCOMMAND or MF_GRAYED);        

That will disable the close box, for example.


Solve 3:

Remember that certain combinations will cause different results (ie. removing the system menu will also disable minimize/ maximize etc.)

procedure TForm1.Button1Click(Sender: TObject);
var
  Style: Integer;
begin
  Style := GetWindowLong(Handle, GWL_STYLE);
  {disable minimize}
  Style := Style - WS_MINIMIZEBOX;
  {disable maximize}
  Style := Style - WS_MAXIMIZEBOX;
  {remove system menu}
  Style := Style - WS_SYSMENU;
  {set new style}
  SetWindowLong(Handle, GWL_STYLE, Style);
  {repaint the title bar}
  RedrawWindow(Handle, nil, 0, RDW_FRAME or RDW_INVALIDATE);
end;

Nincsenek megjegyzések:

Megjegyzés küldése