How to minimize IE Browser using C# ?

2019-02-26 06:35发布

问题:

How can I minimize the IE Browser using C#? I tried the code mentioned below which didn't work:

var processes = Process.GetProcessesByName("*iexplorer.*");

if (processes.Any()) 
{

    var handle = processes.First().MainWindowHandle;
    ShowWindow(handle, SW_SHOWMINIMIZED); 

}

Are there any other methods to achieve minimizing of the IE Browser?

回答1:

As Damien says, there is no fullproof way to do this as the user owns the browser, not your app. Your code isn't working because you are trying to use a wildcard symbol (*) like you would do on Google, but this doesn't work here. GetProcessesByName is literally looking for a process named *iexplorer.*. You can confirm this by placing a breakpoint underneath this line, and hovering over processList, it is an empty array. Changing this to iexplore fixes this problem.

Some tested and working code is below:

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace ConsoleApplication1
{
    class Program
    {
        [DllImport("user32.dll")]
        static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

        static void Main()
        {
            var processes = Process.GetProcessesByName("iexplore");

            foreach (var process in processes)
            {
                ShowWindow(process.MainWindowHandle, 2);
            }
        }
    }
}