You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中可靠地将窗口标题映射到可执行文件名?

动态映射窗口标题到对应可执行文件名(C#实现)

目前通过硬编码窗口标题关键字的方式映射可执行文件名,这种方式需要手动维护标题与可执行文件的对应关系,扩展性差——比如遇到带前缀的窗口标题(如"Process - Microsoft Visual Studio")时,必须新增判断逻辑才能匹配到对应的devenv。

当前实现代码:

public string GetWindowTitle(IntPtr window)
{
    StringBuilder title = new StringBuilder(10000);
    if (GetWindowText(window, title, 10000) > 0)
    {
        return title.ToString();
    }
    return "";
}

public string GetGeneralName(string windowTitle)
{
    if (windowTitle.Contains("Microsoft Visual Studio"))
    {
        return "devenv";
    }
    if (windowTitle.Contains("Brave"))
    {
        return "brave";
    }
    if (windowTitle.Contains("Google Chrome"))
    {
        return "chrome";
    }
    if (windowTitle.Contains("Visual Studio Code"))
    {
        return "Code";
    }
    return "";
}

解决方案:通过窗口句柄直接关联进程获取可执行文件

不需要依赖窗口标题,直接通过窗口句柄获取对应进程ID,再从进程信息中提取可执行文件名,彻底摆脱硬编码的限制。

实现步骤:

  1. 导入Windows API获取窗口关联的进程ID
  2. 通过进程ID获取进程对象,提取主模块的可执行文件名

代码实现:

// 导入Windows API
[DllImport("user32.dll")]
private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);

public string GetExecutableNameFromWindow(IntPtr windowHandle)
{
    GetWindowThreadProcessId(windowHandle, out uint processId);
    if (processId == 0)
        return string.Empty;

    try
    {
        using (var process = Process.GetProcessById((int)processId))
        {
            // 获取不带路径的完整可执行文件名(如devenv.exe、brave.exe)
            return Path.GetFileName(process.MainModule.FileName);
            // 若需不带后缀的名称,替换为:
            // return Path.GetFileNameWithoutExtension(process.MainModule.FileName);
        }
    }
    catch (ArgumentException)
    {
        // 进程已退出或无效
        return string.Empty;
    }
    catch (InvalidOperationException)
    {
        // 无权限访问进程主模块
        return string.Empty;
    }
}

优势说明:

  • 无需维护窗口标题映射表,自动适配所有运行中的窗口
  • 可灵活选择返回带后缀或不带后缀的文件名
  • 加入异常处理,避免进程已退出或权限问题导致的崩溃

内容的提问来源于stack exchange,提问作者CodeCrafter20

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 01:45:01