Name of process for active window in Windows 8/10

前端 未结 4 1049
南方客
南方客 2020-12-02 15:06

The following sample has reliably returned the name of the process that is associated with the active window, but does not work with the newer modern/universal apps because

4条回答
  •  春和景丽
    2020-12-02 15:35

    Here is a small console app application that continuously (so you can test it easily selecting different windows on your desktop) display information about the current foreground window process and store process, if any.

    Apps can have a window hierarchy that can span multiple processes. What I do here is search the first sub window that has the 'Windows.UI.Core.CoreWindow' class name.

    This app uses the UIAutomation API (and also smart pointers, smart BSTRs and smart VARIANTs provided by the #import directive). I suppose you can do the same with standard Windows SDK, but I find the UIAutomation used this way quite elegant.

    #include "stdafx.h"
    #import "UIAutomationCore.dll"
    using namespace UIAutomationClient;
    
    int main()
    {
        // initialize COM, needed for UIA
        CoInitialize(NULL);
    
        // initialize main UIA class
        IUIAutomationPtr pUIA(__uuidof(CUIAutomation));
    
        do
        {
            // get the Automation element for the foreground window
            IUIAutomationElementPtr foregroundWindow = pUIA->ElementFromHandle(GetForegroundWindow());
            wprintf(L"pid:%i\n", foregroundWindow->CurrentProcessId);
    
            // prepare a [class name = 'Windows.UI.Core.CoreWindow'] condition
            _variant_t prop = L"Windows.UI.Core.CoreWindow";
            IUIAutomationConditionPtr condition = pUIA->CreatePropertyCondition(UIA_ClassNamePropertyId, prop);
    
            // get the first element (window hopefully) that satisfies this condition
            IUIAutomationElementPtr coreWindow = foregroundWindow->FindFirst(TreeScope::TreeScope_Children, condition);
            if (coreWindow)
            {
                // get the process id property for that window
                wprintf(L"store pid:%i\n", coreWindow->CurrentProcessId);
            }
    
            Sleep(1000);
        } while (TRUE);
    
    cleanup:
        CoUninitialize();
        return 0;
    }
    

提交回复
热议问题