Tuesday, February 8, 2011

Minimize a external application with Delphi

Is there a way to Minimize an external application that I don't have control over from with-in my Delphi application?

for example notepad.exe, except the application I want to minimize will only ever have one instance.

  • I'm not a Delphi expert, but if you can invoke win32 apis, you can use FindWindow and ShowWindow to minimize a window, even if it does not belong to your app.

    Re0sless : I voted you up, as you put me on the right track, but in the end I used Neftali's code
    From Juanma
  • You can use FindWindow to find the application handle and ShowWindow to minimize it.

    var  
      Indicador :Integer;
    begin 
      // Find the window by Classname
      Indicador := FindWindow(PChar('notepad'), nil);
      // if finded
      if (Indicador <> 0) then begin
        // Minimize
        ShowWindow(Indicador,SW_MINIMIZE);
      end;
    end;
    
    From NeftalĂ­
  • Thanks for this, in the end i used a modifyed version of Neftali's code, I have included it below in case any one else has the same issues in the future.

    FindWindow(PChar('notepad'), nil);
    

    was always returning 0, so while looking for a reason why I found this function that would find the hwnd, and that worked a treat.

    function FindWindowByTitle(WindowTitle: string): Hwnd;
        var
          NextHandle: Hwnd;
          NextTitle: array[0..260] of char;
    begin
          // Get the first window
          NextHandle := GetWindow(Application.Handle, GW_HWNDFIRST);
          while NextHandle > 0 do
          begin
            // retrieve its text
            GetWindowText(NextHandle, NextTitle, 255);
            if Pos(WindowTitle, StrPas(NextTitle)) <> 0 then
            begin
              Result := NextHandle;
              Exit;
            end
            else
              // Get the next window
              NextHandle := GetWindow(NextHandle, GW_HWNDNEXT);
          end;
          Result := 0;
    end;
    
    procedure hideExWindow()
    var Indicador:Hwnd;
    begin
        // Find the window by Classname
        Indicador := FindWindowByTitle('MyApp'); 
        // if finded
        if (Indicador <> 0) then
        begin
            // Minimize
            ShowWindow(Indicador,SW_HIDE); //SW_MINIMIZE
        end;
    end;
    
    Lars Fosdal : Note that this will not work on Windows Vista unless your application run with elevated privileges.
    From Re0sless

0 comments:

Post a Comment