Tile the open windows when calling an external application from your program (Views: 102)


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.


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);
  tileflags: array[Boolean] of UINT = (MDITILE_VERTICAL, MDITILE_HORIZONTAL);
  currhwnd: HWND;
  newhwnd: HWND;
  counter: Integer;
  wndArray: array of HWND;
  currhwnd := GetForegroundWindow;
  if ShellExecute(currhwnd, nil, Pchar(appname), nil, nil, SW_SHOWNORMAL) > 32 then
    counter := 0;
      newhwnd := GetForegroundWindow;
      if (newhwnd <> 0) and (newhwnd <> currhwnd) then
        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}
      counter >= 20;
    raise Exception.CreateFmt('Could not find main window of %s', [appname]);
  raise Exception.CreateFmt('Could not execute %s', [appname]);

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

<< Back to main page