c#如何检测Netflix是否正在运行

时间:2019-01-20 21:02:48

标签: c# netflix

我想检测Netflix是否正在运行。我正在使用Windows窗体应用程序。

Netflix是由流程WWAHost.exe托管的Metro应用程序。我使用以下代码:

Process[] ps = Process.GetProcessesByName("WWAHost");
foreach(var p in ps)
{
  if(p.MainWindowTitle == "Netflix")
  {
    return true;
  }
}

该代码在Netflix启动后的工作时间约为0.6秒。 0.6秒后,MainWindowTitle包含一个空字符串。这意味着只有在Netflix启动后才能检测到它。

更新:实际上,我的代码仅在Netflix最小化或开始播放时才起作用(0.6秒仅是开始播放的时间)。

这是一个错误吗?有解决这个问题的更好方法吗?

我的系统:Win10 1809,VS2015,.Net4.5.2

1 个答案:

答案 0 :(得分:4)

I didn't see this behaviour of the MainWindowTitle disappearing, but here is an alternative solution. If you look in TaskManager with the Netflix application running, we can see that yes it's running as wwahost.exe, but that's given a command line which easily identifies it as the Netflix app -ServerName:Netflix.App.wwa.

enter image description here

So, from your C# application you can extract the process command line using WMI (you need a reference to System.Management for this).

Here is an example:

class Program
{
    static void Main(string[] args)
    {
        var processes = Process
            .GetProcesses()
            .Where(a => a.IsNetflix());

        Console.ReadKey();
    }
}

static class Extensions
{
    public static bool IsNetflix(this Process process)
    {
        if (process.ProcessName.IndexOf("WWAHost", StringComparison.OrdinalIgnoreCase) == -1) return false;

        using (ManagementObjectSearcher searcher = new ManagementObjectSearcher($"SELECT CommandLine FROM Win32_Process WHERE ProcessId = {process.Id}"))
        using (ManagementObjectCollection objects = searcher.Get())
        {
            var managementObject = objects
                .Cast<ManagementBaseObject>()
                .SingleOrDefault();

            if (managementObject == null) return false;
            return managementObject["CommandLine"].ToString().IndexOf("netflix", StringComparison.OrdinalIgnoreCase) > -1;
        }
    }
}
相关问题