簡體   English   中英

如何在WinForm C#中獲取當前正在運行的應用程序名稱和ID?

[英]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;
        }
    }

在這里,我獲得了ProcessID ,它正在工作。 但是我想找到應用程序名稱和ID。

如何獲取帶有ID運行應用程序名稱,以及如何將Id傳遞到Win32_Process表。

我添加了win32_proceess以獲取processid,但我們跟蹤應用程序ID

您可以使用流程類的方法獲取應用程序ID和名稱:

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

投票支持喬納森(Jonathan),但想添加另一種方式(只要您不使用一次單擊即可)

System.AppDomain.CurrentDomain.FriendlyName

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM