Restore a minimized window of another application

前端 未结 6 1173
情深已故
情深已故 2020-11-27 17:00

I\'m adding some code to an app that will launch another app if it isn\'t already running, or if it is, bring it to the front. This requires a small amount of interop/WinAPI

6条回答
  •  甜味超标
    2020-11-27 17:54

    I know its too late, still my working code is as follows so that someone later can get quick help :)

    using System.Runtime.InteropServices;
    using System.Diagnostics;
    
    [DllImport("user32.dll")]
    static extern bool SetForegroundWindow(IntPtr hWnd);
    
    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
    
    [DllImport("user32.dll", EntryPoint = "FindWindow")]
    public static extern IntPtr FindWindowByCaption(IntPtr ZeroOnly, string lpWindowName);
    
    private static void ActivateApp(string processName)
    {
        Process[] p = Process.GetProcessesByName(processName);
    
        if (p.Length > 0)
        {
            IntPtr handle = FindWindowByCaption(IntPtr.Zero, p[0].ProcessName);
            ShowWindow(handle, 9); // SW_RESTORE = 9,
            SetForegroundWindow(handle);
        }
    } 
    
    ActivateApp(YOUR_APP_NAME);
    

    Actually, FindWindowByCaption is the key here, this method collects the window handle correctly when app is running silently in the system tray and also when app is minimized.

提交回复
热议问题