来自Windows 7服务的GetForegroundWindow

Neh*_*eha 0 c++ windows-7

我正在使用来自服务的GetForegroundWindow(),因为我想监视焦点的窗口,但由于交互式用户问题,该函数在Windows 7上返回null.有什么方法可以让我在服务中获得专注的窗口吗?

HWINSTA hWinStaUser = OpenWindowStation(_T("WinSta0"), FALSE, MAXIMUM_ALLOWED); 
    if (SetProcessWindowStation(hWinStaUser)) 
    {
        /* -- Open user's desktop "Default". -- */
        HDESK hDeskUser = OpenInputDesktop(0,FALSE,MAXIMUM_ALLOWED);
        //HDESK hDeskUser = OpenDesktop(_T("Default"), 0, FALSE, MAXIMUM_ALLOWED);
        /* -- Set thread desktop to "Default". -- */ 
        if (SetThreadDesktop(hDeskUser)) 
        {   
            HWND hwndActiveWin = GetForegroundWindow();

            int  idActive      = GetWindowThreadProcessId(hwndActiveWin, NULL);
            if ( AttachThreadInput(GetCurrentThreadId(), idActive, TRUE) )
            {
                HWND  hwndFocused = GetFocus ();    // focused control within the active window, i.e. focus throughout the screen
                if(hwndFocused != NULL)
                {
                    DWORD dwProcessID = 0;      
                    GetWindowThreadProcessId(hwndFocused, &dwProcessID);
                    processPid = dwProcessID;
                }               
                AttachThreadInput(GetCurrentThreadId(), idActive, FALSE);       
            }           
        }
Run Code Online (Sandbox Code Playgroud)

And*_*hko 5

你需要了解问题本身.由于安全风险,服务无法与桌面交互,并且因为可能有许多桌面(许多登录用户).GetForegroundWindow()是与桌面的交互.没有简单的解决方法.复杂的一个涉及单独的进程作为Windows应用程序(而不是服务)运行并与您的服务进行通信.