microsoft-ui-xaml: Window.Activate does not activate and bring window to foreground in WinUI3 if window is in background but not minimized

Describe the bug

If Activate is called on a Window which is in the background of other windows, that window is not activated and brought to the foreground. If the window is minimized it works correctly.

Steps to reproduce the bug

Call Activate on a Window when it is in the backround of other windows.

Expected behavior

No response

Screenshots

No response

NuGet package version

WinUI 3 - Windows App SDK 1.1.4

Windows app type

  • UWP
  • Win32

Device form factor

Desktop

Windows version

Windows 10 (21H2): Build 19044

Additional context

No response

About this issue

  • Original URL
  • State: open
  • Created 4 years ago
  • Reactions: 10
  • Comments: 39 (14 by maintainers)

Most upvoted comments

What is happening now to this issue? Is there any plan going ahead?

Thanks for sample app. I debugged it. Turns out AppInstance.Activated event is not firing and that’s why your window is not coming forward.

If you hook this code to any other event’s firing like button clicked, it starts working. So Window activation is working as expected. image.

So, you can debug AppInstance code to see why it is not working. Closing the issue as it is a no repro.

This worked for me (I needed my app to be single instanced too and if user tried to run app again, already running instance’s window get activated)

This worked for me

[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

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

public enum ShowWindowCommands : int
{
	Hide = 0,
	ShowNormal = 1,
	ShowMinimized = 2,
	ShowMaximized = 3,
	Maximize = 3,
	ShowNormalNoActivate = 4,
	Show = 5,
	Minimize = 6,
	ShowMinNoActivate = 7,
	ShowNoActivate = 8,
	Restore = 9,
	ShowDefault = 10,
	ForceMinimized = 11
}

in app.Xaml.cs

protected override async void OnLaunched(LaunchActivatedEventArgs args)
{
	// Get the activation args
	var appArgs = AppInstance.GetCurrent().GetActivatedEventArgs();
	
	// Get or register the main instance
	var mainInstance = AppInstance.FindOrRegisterForKey("My.App");
	// If the main instance isn't this current instance
	
	if (!mainInstance.IsCurrent)
		{
			var activatedEventArgs = AppInstance.GetCurrent().GetActivatedEventArgs();
			await mainInstance.RedirectActivationToAsync(activatedEventArgs);
			Process.GetCurrentProcess().Kill();
			return;
		}
	// Otherwise, register for activation redirection
	AppInstance.GetCurrent().Activated += AppActivated;
}

private void AppActivated(object sender, AppActivationArguments e)
{
	IntPtr hWnd = WindowNative.GetWindowHandle(_mainWindow);
	//this line causing a delay in reactivating main window, it needed to restore window if it was minimized
	ShowWindow(hWnd, (int)NativeMethods.ShowWindowCommands.ShowNormal);
	//this method will bring main window to front
	SetForegroundWindow(hWnd);
}        

This is not fixed in 1.2! Running code like this

// Wire up the activated event handler.
keyInstance.Activated += async (sender, e) =>
{
  // When activated, activate the main window and bring it to the foreground.
  await _mainWindow.DispatcherQueue.EnqueueAsync(() => _mainWindow.Activate());
  //NativeMethods.SetForegroundWindow(_mainWindow.GetWindowHandle());
};

outside the debugger, does not bring the window to the foreground. Only once the native call is uncommented the window is brought to the foreground!

IMHO this is exactly how Activate should always have behaved and is documented: image

Some update : i have found the root issue and the fix. Now remains is the internal discussion over the fix. Here is some explanation of why it happpens :

This is due to the fact Window.Activate() internally calls SetActiveWindow since its inception (source) .
WPF on the other hand, calls SetForegroundWindow(). Hence, this issue is only for winui and not WPF. Now, which behavior is correct ? WPF is the established one but prone to focus stealing behavior. WinUI is more controlled but there are legitimate reasons like this where it should be moving focus.

, WinUI could start calling SetForegroundWindow too but it would be a breaking change. We are currently assessing the impact on backward compatibility and then we will do the fix. Hope this provides some clarity.

Thanks. It is in the list of bugs we have for fixing. Looking into it. Will update once I have something

This is still an issue in Windows App SDK 1.3.2 (1.3.230602002)

My apologies. I was not launching the second instance. Now I am able to get the repro done. We are investigating this and I will keep the issue open until you validate the fix.

Exactly where the bug hit me too. Had to call SetForegroundWindow. Please fix this.

I did this as a temporary solution.

In App.xaml.cs

protected async override void OnLaunched(Microsoft.UI.Xaml.LaunchActivatedEventArgs args)
{
	var mainInstance = Microsoft.Windows.AppLifecycle.AppInstance.FindOrRegisterForKey("main");
	var activatedEventArgs = Microsoft.Windows.AppLifecycle.AppInstance.GetCurrent().GetActivatedEventArgs();

	if (!mainInstance.IsCurrent)
	{
   
		await mainInstance.RedirectActivationToAsync(activatedEventArgs);
		System.Diagnostics.Process.GetCurrentProcess().Kill();
		return;
	}
	m_window = new MainWindow();
	m_window.Activate();
	mainInstance.Activated += MainInstance_Activated;
}
private void MainInstance_Activated(object sender, Microsoft.Windows.AppLifecycle.AppActivationArguments e)
{
	General.WinPresenter.Minimize();
	General.WinPresenter.Restore();
}

In MainWindow:

public MainWindow()
{
    this.InitializeComponent();
    General.WndHnd = WinRT.Interop.WindowNative.GetWindowHandle(this);
}
private void WinLoaded()
{
	AppWindow CurWin;
	WindowId WinID = Win32Interop.GetWindowIdFromWindow(General.WndHnd);
	CurWin = AppWindow.GetFromWindowId(WinID);

	General.WinPresenter = CurWin.Presenter as OverlappedPresenter;
}

common class in the project

internal class General
{
	public static IntPtr WndHnd;
	public static Microsoft.UI.Windowing.OverlappedPresenter WinPresenter;
}

Does the explorer team using WinUi3 also just work around bugs like this? I would get really mad if i was on that team and long-standing bugs like this are still open.

Is there any plan to address this? We’re nearing six months since a fix was identified for this and there doesn’t seem to have been any movement since then. Could we at least get the documentation updated with a remark describing the problem and linking back here so others don’t lose time trying to figure out why windows aren’t coming to the foreground when activated?

Any progress here? =)

It still exists in Windows App SDK 1.5.1 (1.5.240311000). The company project started using WinUI 3 last month. I ran into this problem today, and I solved it like this.

private static void OnActivated(object? sender, AppActivationArguments args)
{
    ExtendedActivationKind kind = args.Kind;
    LogInfo($"已存在程序,激活回调: 激活次数: {activationCount++} - {ArgsMessage(kind, args)}");
    //WindowHelper.MainWindow.Activate();
    WindowHelper.MainWindow.DispatcherQueue.EnqueueAsync(() =>
    {
        //设置窗口置顶
        if (JOJO.WinUI.WindowsApi.Win32Api.SetTopMost())
        {
            //将窗口提到前台
            JOJO.WinUI.WindowsApi.Win32Api.SetForegroundWindow();
        }
    });
}

Using the Win32 API: SetWindowPos SetForegroundWindow

    public static class Win32Api
    {
        public static MessageBoxResults MessageBox(string content, string title, MessageBoxButtons messageBoxButtons = MessageBoxButtons.Ok) => (MessageBoxResults)Windows.Win32.PInvoke.MessageBox(new Windows.Win32.Foundation.HWND(WindowHelper.GetWindowHandle()), content, title, (Windows.Win32.UI.WindowsAndMessaging.MESSAGEBOX_STYLE)messageBoxButtons);

        public static bool SetForegroundWindow() => Windows.Win32.PInvoke.SetForegroundWindow(new Windows.Win32.Foundation.HWND(WindowHelper.GetWindowHandle()));

        /// <summary>
        /// 置顶
        /// </summary>
        public static bool SetTopMost() => Windows.Win32.PInvoke.SetWindowPos(new Windows.Win32.Foundation.HWND(WindowHelper.GetWindowHandle()), new Windows.Win32.Foundation.HWND(new IntPtr(0)), 0, 0, 0, 0, Windows.Win32.UI.WindowsAndMessaging.SET_WINDOW_POS_FLAGS.SWP_NOMOVE | Windows.Win32.UI.WindowsAndMessaging.SET_WINDOW_POS_FLAGS.SWP_NOSIZE);
    }

Using NuGet Microsoft.Windows.CsWin32 CommunityToolkit.WinUI.Extensions

My English is not good.Hope it helps you.

I was hitting the same issue today as well. My goal is to activate/foreground the apps single-instanced window after the user clicks a toast notification of the same app (a pretty common scenario I would say). The SetForegroundWindow workaround posted above does not work if the debugger isn’t attached due to the reasons here.

An API which generally works is SwitchToThisWindow (they say “It may be altered…”, but it is used by Task Manager for ages…) (I used it for example in this test sample to set the main window to foreground with a Hotkey : MainWindow.xaml.cs)

IntPtr hWnd = WindowNative.GetWindowHandle(_mainWindow); //this line causing a delay in reactivating main window, it needed to restore window if it was minimized ShowWindow(hWnd, (int)NativeMethods.ShowWindowCommands.ShowNormal); //this method will bring main window to front SetForegroundWindow(hWnd);

Worked like a champ, thank you.

I will try it tomorrow and report back.