Author: Jonas Bilinkevicius
How to centre a MessageBox on a form
Answer:
1 { ... }
2 msgCaption: PChar; {var to hold caption}
3 { ... }
4
5 procedure pmChangeMessageBox(var Msg: TMessage); message WM_USER + 1024;
6
7 procedure TForm1.pmChangeMessageBox(var Msg: TMessage);
8 var
9 MBHwnd: THandle;
10 MBRect: TRect;
11 x, y, w, h: integer;
12 begin
13 MBHwnd := FindWindow(MAKEINTRESOURCE(WC_DIALOG), msgCaption);
14 if (MBHwnd <> 0) then
15 begin
16 GetWindowRect(MBHWnd, MBRect);
17 w := MBRect.Right - MBRect.Left;
18 h := MBRect.Bottom - MBRect.Top;
19 {center horizontal}
20 x := Form1.Left + ((Form1.Width - w) div 2);
21 {keep on screen}
22 if x < 0 then
23 x := 0
24 else if x + w > Screen.Width then
25 x := Screen.Width - w;
26 {center vertical}
27 y := Form1.Top + ((Form1.Height - h) div 2);
28 {keep on screen}
29 if y < 0 then
30 y := 0
31 else if y + h > Screen.Height then
32 y := Screen.Height - h;
33 SetWindowPos(MBHWnd, 0, x, y, 0, 0, SWP_NOACTIVATE or SWP_NOSIZE or
34 SWP_NOZORDER);
35 end;
36 end;
37
38 //Example use:
39
40 PostMessage(Handle, WM_USER + 1024, 0, 0);
41 msgCaption := 'Confirm';
42 MessageBox(Handle, 'Save changes?', msgCaption, MB_ICONQUESTION or MB_YESNOCANCEL);
|