Connecting UWP apps hosted by ApplicationFrameHost to their real processes

前端 未结 4 1197
暗喜
暗喜 2021-02-08 00:30

I am working on an WPF application to monitor my activities on my computer. I use Process.GetProcesses() and some filtering to get the processes I am interested in

4条回答
  •  感情败类
    2021-02-08 01:03

    About the same code from Chris Johnsson except that I'm not using Process because it doesn't work very well on the UWP app.

    Code for start:

    new Timer(TimerCallback, null, 0, 1000);
    
    void TimerCallback(object state)
    {
        var process = new ProcessUtils.FindHostedProcess().Process;
        string name = string.Empty;
    
        if (process.IsPackaged)
        {
            var apps = process.GetAppDiagnosticInfos();
            if (apps.Count > 0)
                name = apps.First().AppInfo.DisplayInfo.DisplayName;
            else
                name = System.IO.Path.GetFileNameWithoutExtension(process.ExecutableFileName);
        }
        else
            name = System.IO.Path.GetFileNameWithoutExtension(process.ExecutableFileName);
    
        Debug.WriteLine(name);
    }
    

    And the FindHostedProcess class where I use ProcessDiagnosticInfo instead of Process

    public class FindHostedProcess
    {
        public ProcessDiagnosticInfo Process { get; private set; }
    
        public FindHostedProcess()
        {
            var foregroundProcessID = WinAPIFunctions.GetforegroundWindow();
            Process = ProcessDiagnosticInfo.TryGetForProcessId((uint)WinAPIFunctions.GetWindowProcessId(foregroundProcessID));
    
            // Get real process
            if (Process.ExecutableFileName == "ApplicationFrameHost.exe")
                WinAPIFunctions.EnumChildWindows(foregroundProcessID, ChildWindowCallback, IntPtr.Zero);
        }
    
        private bool ChildWindowCallback(IntPtr hwnd, IntPtr lparam)
        {
            var process = ProcessDiagnosticInfo.TryGetForProcessId((uint)WinAPIFunctions.GetWindowProcessId(hwnd));
    
            if (process.ExecutableFileName != "ApplicationFrameHost.exe")
                Process = process;
    
            return true;
        }
    }
    

    Finally reuse Chris Johnson's WinAPIFunctions class.

提交回复
热议问题