简体   繁体   中英

c# get all the opened windows title

I am writing a program to get all the windows title of Internet Explorer. Suppose if 2 windows of Internet Explorer are opened, the my program should show the titles & get the handles of all the Internet Explorer windows. Here is my program

using System.Diagnostics;

Process[] processlist = Process.GetProcesses();

foreach (Process process in processlist)
{
    if (!String.IsNullOrEmpty(process.MainWindowTitle))
    {
        Console.WriteLine("Process: {0} ID: {1} Window title: {2}", process.ProcessName, process.Id, process.MainWindowTitle);
    }
}

This program is working but only gets a single window's text. When I see, there are 3 to 4 iexplore.exe were running when 2 to 3 Internet Explorer windows are opened. While looking other answers, all they are using with one process, but there are 3-4 iexplore.exe present. How can I get all the handles of opened Internet Explorer windows ?

Thanks

You could use the ManagmenObjectSearcher to get all the parents object from a certain process

 private void Form1_Load(object sender, EventArgs e)
    {

        Process[] processlist = Process.GetProcesses();

        foreach (Process process in processlist)
        {
            if (!String.IsNullOrEmpty(process.MainWindowTitle))
            {
                if (process.Id == 4160)//this is chrome id for example/
                {
                    //Console.WriteLine("Process: {0} ID: {1} Window title: {2}", process.ProcessName, process.Id, process.MainWindowTitle);
                    List<Process> a = GetChild(process);

                    foreach( Process p in a)
                    {
                        Console.WriteLine("Process: {0} ID: {1} Window title: {2}", process.ProcessName, process.Id, process.MainWindowTitle);
                    }
                }
            }
        }
    }

    public  static List<Process> GetChild(Process process)
    {
        List<Process> children = new List<Process>();
        ManagementObjectSearcher mos = new ManagementObjectSearcher(String.Format("Select * From Win32_Process Where ParentProcessID={0}", process.Id));

        foreach (ManagementObject mo in mos.Get())
        {
            children.Add(Process.GetProcessById(Convert.ToInt32(mo["ProcessID"])));
        }

        return children;
    }

Goodluck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM