简体   繁体   中英

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

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;

投票支持乔纳森(Jonathan),但想添加另一种方式(只要您不使用一次单击即可)

System.AppDomain.CurrentDomain.FriendlyName

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