如何用c#获取在windows上运行的程序的名称

本文关键字:运行 程序 windows 何用 获取 | 更新日期: 2023-09-27 18:09:47

我想要一个函数,给我一个程序的名称(如msPaint或notepad),当我使用记事本,这个函数返回" notepad ",当我使用msPaint,这个函数返回"msPaint"。

如何用c#获取在windows上运行的程序的名称

使用Process.GetProcesses();方法可以获得所有正在运行的应用程序,如果您想要当前活动窗口,则使用GetForegroundWindow()GetWindowText()

例如点击这里

您可以使用Process类。它有一个Modules属性,列出了所有加载的模块。

列出控制台的所有进程和模块:

Process[] processes = Process.GetProcesses();
    foreach(Process process in processes) {
    Console.WriteLine("PID:  " + process.Id);
    Console.WriteLine("Name: " + process.Name);
    Console.WriteLine("Modules:");
    foreach(ProcessModule module in process.Modules) {
        Console.WriteLine(module.FileName);
    }

或者这样做

[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
private static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
public static void Main()
{
    int chars = 256;
    StringBuilder buff = new StringBuilder(chars);
    while (true)
    {
        // Obtain the handle of the active window.
        IntPtr handle = GetForegroundWindow();
        // Update the controls.
        if (GetWindowModuleFileName(handle, buff, chars) > 0)
        {
            Console.WriteLine(buff.ToString());
            Console.WriteLine(handle.ToString());
        }
        Thread.Sleep(1000);
    }
}

From:如何从c#中获得进程窗口类名?

    int pidToSearch = 316;
    //Init a condition indicating that you want to search by process id.
    var condition = new PropertyCondition(AutomationElementIdentifiers.ProcessIdProperty, 
        pidToSearch);
    //Find the automation element matching the criteria
    AutomationElement element = AutomationElement.RootElement.FindFirst(
        TreeScope.Children, condition);
    //get the classname
    var className = element.Current.ClassName;

我不知道你是如何调用这些程序的。如果您通过Process运行这些程序,则可以通过ProcessName获取。

的例子:

        Process tp = Process.Start(@"notepad.exe", "temp");
        string s = tp.ProcessName;