首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在C#中确定当前关注进程的名称

在 C# 中确定当前关注进程的名称,可以通过 Windows API GetWindowText 函数和 System.Diagnostics.Process 类来实现。以下是一个完整的示例代码,展示了如何在 C# 中获取当前运行的进程名称:

代码语言:csharp
复制
using System;
using System.Diagnostics;

class Program
{
    static void Main(string[] args)
    {
        // 获取当前进程的 ID
        Process[] processes = Process.GetProcessesByName("explorer");
        if (processes.Length > 0)
        {
            Console.WriteLine("Current Explorer process ID: " + processes[0].Id);
        }
        else
        {
            Console.WriteLine("No Explorer process is running.");
        }

        // 获取当前运行的 Explorer 进程的名称
        ProcessExplorer.MainWindowHandle

        // 使用 GetWindowText 获取 Explorer 进程的窗口标题
        IntPtr hWnd = Win32API.FindWindowEx(FindWindowExA(processes[0].MainWindowHandle, IntPtr.Zero, "Shell_TrayWnd", IntPtr.Zero), null, null);
        Win32API.GetWindowText(hWnd, processes[0].MainWindowTitle, System.Text.StringBuilder.MaxCreateSize);
        
        string explorerName = processes[0].MainWindowTitle;
        Console.WriteLine("Current Explorer window title: " + explorerName);
        Console.WriteLine("==========");

        // 使用 Process 类获取 Explorer 进程的路径(如果运行的是 Windows Explorer)
        processes = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(explorerName));
        if (processes.Length > 0)
        {
            Console.WriteLine("Path of the Explorer process executing Windows Explorer: " + processes[0].MainModule.FileName);
        }
    }
}

上述代码中,ProcessExplorer 类包含了需要用到的一些函数和属性(如 FindWindowsExGetWindowTextProcess 等),并且封装了大部分 Windows API 函数,方便直接调用。ProcessExplorer.MainWindowHandle 可以获取到当前运行 Explorer 的 MainWindowHandle,再调用 GetWindowText 获取 Explorer 进程的窗口标题,将其作为进程名称输出到控制台。 如果运行的是 Windows Explorer,还可以使用 Process 类直接获取启动 Windows Explorer 的 App.exe 路径。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

扫码

添加站长 进交流群

领取专属 10元无门槛券

手把手带您无忧上云

扫码加入开发者社群

相关资讯

热门标签

活动推荐

    运营活动

    活动名称
    广告关闭
    领券