0

In Windows 11, The following code is able to run and get the main window handle of winver.exe:

public IntPtr Start()
    {
        IntPtr id = 0;
        using (Process process = Process.Start("c:\\Windows\\System32\\winver.exe"))
        {
            
            for (int i = 0; i < 10 && id == 0; i++)
            {
                Thread.Sleep(200);
                try
                {
                    process.WaitForInputIdle();
                } catch { }
                process.Refresh();
                id = process.MainWindowHandle;
            }

            return id;
        }

        return 0;
    }

However changing 'winver.exe' for 'calc.exe', 'notepad.exe' or any store download application will result on a window handle of 0, which I assume is related to those being UWP apps (but I'm far from being an expert in anything Windows related).

Is there any way to run and fetch the main window handle of a UWP app from C#?

Víctor Romero
  • 5,107
  • 2
  • 22
  • 32
  • UWP applications are not part of the Windows Runtime; they don't have a concept of a window handle. They are purposely designed to be platform agnostic, and run inside a container application (Desktop Bridge). – Claies Mar 16 '23 at 20:07
  • https://stackoverflow.com/questions/32360149/name-of-process-for-active-window-in-windows-8-10/32513438#32513438 – Hans Passant Mar 16 '23 at 20:46

1 Answers1

0

You can launch your UWP apps through URI, and get the window handle with GetForegroundWindow.

I used two methods to start the UWP app, the first using LaunchUriAsync, and the second using Process to start. To launch a protocol from C# the Process object with UseShellExecute=true. You cannot launch UWP with Explorer.exe as the process.

//first way
[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();

bool result = await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-windows-store://navigatetopage/?Id=Gaming"));
var handle1 = GetForegroundWindow();

//second way
Process process = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.UseShellExecute = true;
startInfo.FileName = @"ms-windows-store://navigatetopage/?Id=Gaming";
process.StartInfo = startInfo;
process.Start();
Thread.Sleep(2000);
var handle2 = GetForegroundWindow();
Junjie Zhu - MSFT
  • 2,086
  • 1
  • 2
  • 6