0
votes

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
Did you try setting keyboard focus? It seems a bit obvious, but... - Andy
Thanks I hadn't tried that. Unfortunately no it didn't work. I'll add it to the question. - Sean O'Neil

1 Answers

3
votes

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