ramaraog
ramaraog

Reputation: 67

How can i get Current running Application name and ID in WinForm C#?

public static string GetActiveProcessFileName()
{        
   try
    {
        IntPtr hwnd = GetForegroundWindow();
        uint pid;
        GetWindowThreadProcessId(hwnd, out pid);
        Process p = Process.GetProcessById((int)pid);

        CommandLine = GetMainModuleFilepath((int)pid);

    catch (Exception ex)
    {
        ErrorLog.ErrorLog.Log(ex);
        return "Explorer";
    }
}

 public static string GetMainModuleFilepath(int processId)
    {
        try
        {
            wmiQueryString = "SELECT * FROM Win32_Process WHERE ProcessId = " + processId;
            using (searcher = new ManagementObjectSearcher(wmiQueryString))
            {
                using (results = searcher.Get())
                {


                    mo = results.Cast<ManagementObject>().FirstOrDefault();
                    if (mo != null)
                    {
                        return ((object)mo["CommandLine"]).ToString();
                    }
                }
            }
            //Process testProcess = Process.GetProcessById(processId);
            return null;
        }
        catch (Exception ex)
        {
            ErrorLog.ErrorLog.Log(ex);
            return null;
        }
    }

Here I get ProcessID and it's working. But I want I to find the Application Name and ID.

How can I get Running Application names with ID and how to pass Id to `Win32_Process Table.

I added win32_proceess for getting processid but we trace the application Id

Upvotes: 1

Views: 9895

Answers (2)

Sagiv b.g
Sagiv b.g

Reputation: 31024

Voted for Jonathan's but would like to add another way (as long as you're not using click once)

System.AppDomain.CurrentDomain.FriendlyName

Upvotes: 0

Jonathan Camilleri
Jonathan Camilleri

Reputation: 631

You can get the application id and name using a method of the process class:

System.Diagnostics.Process p = System.Diagnostics.Process.GetCurrentProcess();
int id = p.Id;
string name = p.ProcessName;

Upvotes: 6

Related Questions