简体   繁体   中英

How to get multiple instance details of single process in c#?

In my desktop triplE application is running. Its process name is "Orig_sysdsner". Here single process is creating but multiple instances are creating where each instance title will be unique. Now i want to get all instances of this process with instance name. How to do it in C#?

Below function i have tried but getting last opened instance details.

public static List<string> GetDGDesignEditorRunningInstance()
{
    List<string> runningInstanceList = new List<string>();
    List<Process> processList = Process.GetProcessesByName("Orig_sysdsner").ToList();
    try
    {
        foreach (Process process in processList)
        {
            //string instanceName = process.MainModule.FileName;
            string instanceName = process.MainWindowTitle;
            runningInstanceList.Add(instanceName);
        }

    }
    catch (Exception ex)
    {
        throw ex;
    }
    return runningInstanceList;
}

A process may not have a window title. If I execute this :

var runningInstanceList=Process.GetProcessesByName("Chrome")
                           .Select(proc=>proc.MainWindowTitle)
                           .ToList();

I'll get back 16 entries and only one of them will have a MainWindowTitle. Chrome uses tabs and background processes that don't show any title.

If I use MicrosoftEdgeCP I'll get back 17 strings, all with the same title, Microsoft Edge .

BTW you don't need the call to .ToList() to iterate over the array returned by GetProcessByName . foreach works on anything that implements IEnumerable or IEnumerable<T> . You can use LINQ to select the items you need so you can get rid of the loop and adding the titles to the result list one by one, eg:

var runningInstanceList=Process.GetProcessesByName("Chrome")
                           .Select(proc=>new { proc.Id,
                                               proc.ProcessName,
                                               proc.MainWindowTitle
                                             })
                           .ToList();

Will return the unique process ID , the name and window title if it exists.

You can use Process Explorer and add the Window Title to the process list to see what title is reported by each application.

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