2004. május 8., szombat

How to centre a MessageBox on a form


Problem/Question/Abstract:

How to centre a MessageBox on a form

Answer:

{ ... }
msgCaption: PChar; {var to hold caption}
{ ... }

procedure pmChangeMessageBox(var Msg: TMessage); message WM_USER + 1024;

procedure TForm1.pmChangeMessageBox(var Msg: TMessage);
var
  MBHwnd: THandle;
  MBRect: TRect;
  x, y, w, h: integer;
begin
  MBHwnd := FindWindow(MAKEINTRESOURCE(WC_DIALOG), msgCaption);
  if (MBHwnd <> 0) then
  begin
    GetWindowRect(MBHWnd, MBRect);
    w := MBRect.Right - MBRect.Left;
    h := MBRect.Bottom - MBRect.Top;
    {center horizontal}
    x := Form1.Left + ((Form1.Width - w) div 2);
    {keep on screen}
    if x < 0 then
      x := 0
    else if x + w > Screen.Width then
      x := Screen.Width - w;
    {center vertical}
    y := Form1.Top + ((Form1.Height - h) div 2);
    {keep on screen}
    if y < 0 then
      y := 0
    else if y + h > Screen.Height then
      y := Screen.Height - h;
    SetWindowPos(MBHWnd, 0, x, y, 0, 0, SWP_NOACTIVATE or SWP_NOSIZE or
      SWP_NOZORDER);
  end;
end;

Example use:

PostMessage(Handle, WM_USER + 1024, 0, 0);
msgCaption := 'Confirm';
MessageBox(Handle, 'Save changes?', msgCaption, MB_ICONQUESTION or MB_YESNOCANCEL);

Nincsenek megjegyzések:

Megjegyzés küldése