How Can My Win32 App Steal Focus From My UWP App?

徘徊边缘 提交于 2019-12-10 11:58:28

问题


I've tried the following code:

[DllImport("user32.dll")]
private static extern int ShowWindow(IntPtr hwnd, int nCmdShow);

[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);

[DllImport("user32.dll")]
private static extern IntPtr SetFocus(IntPtr hwnd);

void TakeFocus()
{
    var process = Process.GetProcessesByName("myProcess").FirstOrDefault();
    if (process != null)
    {
        // Tried each of the following:
        ShowWindow(process.MainWindowHandle, 1);
        ShowWindow(process.MainWindowHandle, 3);
        ShowWindow(process.MainWindowHandle, 9);
        ShowWindow(process.MainWindowHandle, 5);
        SetFocus(process.MainWindowHandle);
        SetForegroundWindow(process.MainWindowHandle);
    }
}

I have a WPF companion app which runs in the background while a UWP app is running in the foreground. They communicate via WebSocket. I'm trying to create a method in the WPF app so it (or any other window) can steal focus from an activated UWP app, sending it into suspended state. Nothing I try seems to work, and there's no way to programatically make a UWP app suspend itself AFAIK without using the Launcher class (not an option for me, unless there's a way to call it without actually launching something-I haven't been able to do this). Normally I would assume it can't be done but I've seen programs that do it. Steam Big Picture Mode, for example, will steal focus from a UWP app when it is launched from a background process.


回答1:


The supported way of suspending a UWP programmatically is available in the Spring 2018 update for Windows 10. It's already available in Insider builds/SDKs. This is the API to call:

https://docs.microsoft.com/en-us/uwp/api/windows.system.appresourcegroupinfo.startsuspendasync#Windows_System_AppResourceGroupInfo_StartSuspendAsync

IList<AppDiagnosticInfo> infos = await AppDiagnosticInfo.RequestInfoForAppAsync();
IList<AppResourceGroupInfo> resourceInfos = infos[0].GetResourceGroups();
await resourceInfos[0].StartSuspendAsync();

Here is a trivial sample app: https://1drv.ms/u/s!AovTwKUMywTNoYQ3PrmBfZIGXmbULA



来源:https://stackoverflow.com/questions/49541592/how-can-my-win32-app-steal-focus-from-my-uwp-app

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!