We help IT Professionals succeed at work.

Minimize another application properly

skynergy
skynergy asked
on
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
Comment
Watch Question

Commented:
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;

Author

Commented:
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.

Commented:
replace with pwnd := 0;

Author

Commented:
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.
Commented:
glad I could help out :)

Author

Commented:
Thanx for your advice and help!

Explore More ContentExplore courses, solutions, and other research materials related to this topic.