Author: Tomas Rutkauskas
I am using a function from the ShlObj unit to select a networked computer via a
Computer Browser. The browser window is called with SHBrowseForFolder(BrowseInfo),
the window displayed always seems to position itself in the lower right of the
screen. Is it possible to programatically reposition the window to be centered on
the screen?
Answer:
Yes, you provide a browse callback function for this task.
1 uses
2 ActiveX, ShlObj;
3
4 function CenterVertical(const rect: TRect; h: Integer): Integer;
5 begin
6 Result := (rect.bottom + rect.top - h) div 2;
7 end;
8
9 function CenterHorizontal(const rect: TRect; w: Integer): Integer;
10 begin
11 Result := (rect.right + rect.left - w) div 2;
12 end;
13
14 function BrowserCallback(Wnd: HWND; uMsg: UINT; lParam, lpData: LPARAM): Integer
15 stdcall;
16 var
17 r1, r2: TRect;
18 begin
19 result := 0;
20 if uMsg = BFFM_INITIALIZED then
21 begin
22 GetWindowRect(wnd, r1);
23 r2 := Rect(0, 0, Screen.Width, Screen.Height);
24 MoveWindow(wnd, CenterHorizontal(r2, r1.Right - r1.left), CenterVertical(r2,
25 r1.Bottom - r1.Top),
26 r1.Right - r1.Left, r1.Bottom - r1.Top, false);
27 end;
28 end;
29
30 procedure TForm1.Button1Click(Sender: TObject);
31 var
32 browseinfo: TBrowseInfo;
33 pidl: PItemIDList;
34 buf: array[0..MAX_PATH] of Char;
35 begin
36 fillchar(browseinfo, SizeOf(browseinfo), 0);
37 browseinfo.hwndOwner := Handle;
38 browseinfo.lpszTitle := 'Select directory';
39 browseinfo.ulFlags := BIF_RETURNONLYFSDIRS or BIF_NEWDIALOGSTYLE;
40 browseinfo.lpfn := BrowserCallback;
41 pidl := ShBrowseForFolder(browseinfo);
42 if Assigned(pidl) then
43 begin
44 ShGetPathfromIDList(pidl, buf);
45 ShowMessage(buf);
46 CoTaskMemFree(pidl);
47 end;
48 end;
|