2006. július 31., hétfő

Tile the open windows when calling an external application from your program


Problem/Question/Abstract:

I want to execute an external program from my Delphi application when I click on a button. However, when the program is executed, I want both my Delphi application and the external program to tile side by side (just like in Windows own "Tile windows") vertically.

Answer:

The problem boils down to finding the started programs window handle. Once you have that the tiling boils down to a single call to the TileWIndow API function. The following is starting an application and tiling its window with the current application window.

procedure StartAppAndTileWindows(const appname: string; const windows: array of HWND;
  tileHorizontal: Boolean = true);
const
  tileflags: array[Boolean] of UINT = (MDITILE_VERTICAL, MDITILE_HORIZONTAL);
var
  currhwnd: HWND;
  newhwnd: HWND;
  counter: Integer;
  wndArray: array of HWND;
begin
  currhwnd := GetForegroundWindow;
  if ShellExecute(currhwnd, nil, Pchar(appname), nil, nil, SW_SHOWNORMAL) > 32 then
  begin
    counter := 0;
    repeat
      Sleep(100);
      newhwnd := GetForegroundWindow;
      if (newhwnd <> 0) and (newhwnd <> currhwnd) then
      begin
        SetLength(wndArray, High(windows) + 2);
        Move(windows[0], wndArray[0], (High(windows) + 1) * sizeof(HWND));
        wndArray[High(wndArray)] := newhwnd;
        TileWindows(0, {tile on desktop}
          tileflags[tileHorizontal], {mode as per param}
          nil, {use desktops full client area}
          Length(wndArray), {count of windows to tile}
          @wndArray[0]); {array of window handles to tile}
        Exit;
      end
      else
        Inc(counter);
    until
      counter >= 20;
    raise Exception.CreateFmt('Could not find main window of %s', [appname]);
  end;
  raise Exception.CreateFmt('Could not execute %s', [appname]);
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  StartAppAndTileWindows('notepad.exe', [handle]);
end;

Nincsenek megjegyzések:

Megjegyzés küldése