Link to home
Start Free TrialLog in
Avatar of skynergy
skynergy

asked on

Minimize another application properly

I am using the following code:

procedure TfMain.MinimizeActiveWindow;
var
   wnd: HWND;
begin
  wnd := GetForegroundWindow;
  ShowWindow(wnd, SW_MINIMIZE);
end;

The code works with any active window but it doesn't minimize some windows to the taskbar but only to the desktop just above the windows start button. Does someone knows how to correctly minimize the active window?

Thanx
Magnus
Avatar of rondi
rondi

try something like

//-------------BOF code snippet---------------------

procedure TfMain.MinimizeActiveWindow;
var
  wnd,pwnd: HWND;
begin
  wnd := GetForegroundWindow;
  pwnd := -1;
  while true do
  begin
    pwnd := GetParent(wnd);
    if (pwnd = wnd) or (pwnd <= 0) then
    begin
      pwnd := wnd;
      break;
    end;
  end;
  if pwnd > 0 then
    SendMessage(pwnd,WM_SYSCOMMAND,SC_MINIMIZE,0);  //or use ShowWindow(pwnd, SW_MINIMIZE);
end;

//-------------EOF code snippet---------------------

I'm hoping GetParent will stop at the application's handle or main window handle. If you find that GetParent is also getting the Desktop window, then you'll need to:

procedure TfMain.MinimizeActiveWindow;
var
  wnd,pwnd,dwnd: HWND;
begin
  wnd := GetForegroundWindow;
  dwnd := GetDesktopWindow;
  pwnd := -1;
  while true do
  begin
    pwnd := GetParent(wnd);
    if (pwnd = wnd) or (pwnd <= 0) or (pwnd = dwnd) then
    begin
      pwnd := wnd;
      break;
    end;
  end;
  if pwnd > 0 then
    SendMessage(pwnd,WM_SYSCOMMAND,SC_MINIMIZE,0);  //or use ShowWindow(pwnd, SW_MINIMIZE);
end;
Avatar of skynergy

ASKER

When trying to compile your first set of code I get the following error:
"[Error] Main.pas(872): Constant expression violates subrange bounds".
Line 872 is " pwnd := -1;"

I am using Delphi 5.
replace with pwnd := 0;
I changed my code using the line "SendMessage(wnd,WM_SYSCOMMAND,SC_MINIMIZE,0);" instead of "ShowWindow(wnd, SW_MINIMIZE);" and it's working ok now on windows that didn't work ok.
ASKER CERTIFIED SOLUTION
Avatar of rondi
rondi

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanx for your advice and help!