question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

WinUI 3 Unpackaged app crashed when open the context menu

See original GitHub issue

Describe the bug

My WinUI 3 Unpackaged app crashed when i right clicked on the tray icon.

I did not add a icon file, but i think it doesn’t matter, because the sample works perfectly after i delete its icon file and related statements in xaml code.

There wasn’t any exception message shown after the crash. The only message i got is the exit code : 3221226107 (0xc000027b).

Steps to reproduce the bug

  1. Install the NuGet package.
  2. Add these codes: In MainWindow.xaml
<Window xmlns:controls="using:AutoDL.Controls">
    <Grid>
        <!--Other Codes-->
        <controls:TrayIconContextMenu/>
    </Grid>
</Window>

In TrayIconContextMenu.xaml

<UserControl
    x:Class="AutoDL.Controls.TrayIconContextMenu"
    xmlns:tb="using:H.NotifyIcon">

    <UserControl.Resources>
        <XamlUICommand
            x:Key="ShowHideWindowCommand"
            ExecuteRequested="ShowHideWindowCommand_ExecuteRequested"
            Label="Show/Hide Window"
            Description="Show/Hide Window">
            <XamlUICommand.IconSource>
                <SymbolIconSource Symbol="OpenPane"/>
            </XamlUICommand.IconSource>
            <XamlUICommand.KeyboardAccelerators>
                <KeyboardAccelerator
                    Key="S"
                    Modifiers="Control"
                />
            </XamlUICommand.KeyboardAccelerators>
        </XamlUICommand>
        <XamlUICommand
            x:Key="ExitApplicationCommand"
            ExecuteRequested="ExitApplicationCommand_ExecuteRequested"
            Label="Exit"
            Description="Exit">
            <XamlUICommand.IconSource>
                <SymbolIconSource Symbol="ClosePane" />
            </XamlUICommand.IconSource>
            <XamlUICommand.KeyboardAccelerators>
                <KeyboardAccelerator
                    Key="E"
                    Modifiers="Control"
                />
            </XamlUICommand.KeyboardAccelerators>
        </XamlUICommand>
        <MenuFlyout
            x:Key="TrayContextFlyout"
            AreOpenCloseAnimationsEnabled="False">
            <MenuFlyoutItem Command="{StaticResource ShowHideWindowCommand}" />
            <MenuFlyoutSeparator />
            <MenuFlyoutItem Command="{StaticResource ExitApplicationCommand}" />
        </MenuFlyout>
    </UserControl.Resources>

    <tb:TaskbarIcon
        x:Name="TrayIcon"
        ToolTipText="AutoDL"
        ContextFlyout="{StaticResource TrayContextFlyout}"
        NoLeftClickDelay="True"
        ContextMenuMode="SecondWindow"
        LeftClickCommand="{StaticResource ShowHideWindowCommand}"
    />
</UserControl>

In TrayIconContextMenu.cs

public sealed partial class TrayIconContextMenu : UserControl
    {
        public TrayIconContextMenu()
        {
            this.InitializeComponent();
        }

        public void ShowHideWindowCommand_ExecuteRequested(object? _, ExecuteRequestedEventArgs args)
        {
            var window = UIHelper.MainWindow;
            if (window == null)
            {
                return;
            }

            if (window.Visible)
            {
                window.Hide();
            }
            else
            {
                window.Show();
            }
        }

        public void ExitApplicationCommand_ExecuteRequested(object? _, ExecuteRequestedEventArgs args)
        {
            TrayIcon.Dispose();
            UIHelper.MainWindow.Close();
        }
    }
  1. Run the app.
  2. Right click on the tray icon.

Expected behavior

It should show a fluent design context menu after i right clicked it.

Screenshots

No response

NuGet package version

2.0.64

Platform

WinUI

IDE

Visual Studio 2022

Windows Version

Windows 11

WindowsAppSDK Version

1.1

WindowsAppSDK Type

Unpackaged

Manifest

No response

Additional context

No response

Issue Analytics

  • State:closed
  • Created a year ago
  • Reactions:1
  • Comments:9 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
xiaoli8848commented, Aug 29, 2022

Now I know the reason for this exception. My app calls utility class code on the Activated event to set the app background to the Mica material. After I delete the relevant code, the menu will appear normally after right-clicking the tray icon. These are the relevant codes:

using System.Runtime.InteropServices;
using Windows.System;
using Microsoft.UI;
using Microsoft.UI.Composition;
using Microsoft.UI.Composition.SystemBackdrops;
using Microsoft.UI.Windowing;
using WinRT;
using WinRT.Interop;

namespace AutoDL.Utilities;

public static class UIHelper
{
    public const int ICON_BIG = 1;
    public const int ICON_SMALL = 0;
    public const int WA_ACTIVE = 0x01;
    public const int WA_INACTIVE = 0x00;
    public const int WM_ACTIVATE = 0x0006;
    public const int WM_SETICON = 0x0080;

    private static WindowsSystemDispatcherQueueHelper m_wsdqHelper; // See separate sample below for implementation
    private static MicaController m_micaController;
    private static SystemBackdropConfiguration m_configurationSource;

    public static IntPtr MainWindow_Handle = WindowNative.GetWindowHandle(MainWindow);

    public static WindowId MainWindow_ID = Win32Interop.GetWindowIdFromWindow(MainWindow_Handle);

    public static MainWindow MainWindow => (MainWindow)(Application.Current as App).m_window;

    public static AppWindow AppWindow => AppWindow.GetFromWindowId(Win32Interop.GetWindowIdFromWindow(WindowNative.GetWindowHandle(MainWindow)));

    public static App App => Application.Current as App;

    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, int wParam, IntPtr lParam);

    [DllImport("user32.dll")]
    public static extern IntPtr GetActiveWindow();

    public static bool TrySetMicaBackdrop()
    {
        if (!MicaController.IsSupported()) return false; // Mica is not supported on this system
        m_wsdqHelper = new WindowsSystemDispatcherQueueHelper();
        m_wsdqHelper.EnsureWindowsSystemDispatcherQueueController();

        // Hooking up the policy object
        m_configurationSource = new SystemBackdropConfiguration();
        MainWindow.Activated += Window_Activated;
        ((FrameworkElement)MainWindow.Content).ActualThemeChanged += Window_ThemeChanged;

        // Initial configuration state.
        m_configurationSource.IsInputActive = true;
        SetConfigurationSourceTheme();

        m_micaController = new MicaController();

        // Enable the system backdrop.
        // Note: Be sure to have "using WinRT;" to support the Window.As<...>() call.
        m_micaController.AddSystemBackdropTarget(((MainWindow)(Application.Current as App).m_window)
            .As<ICompositionSupportsSystemBackdrop>());
        m_micaController.SetSystemBackdropConfiguration(m_configurationSource);
        return true; // succeeded
    }

    private static void SetConfigurationSourceTheme()
    {
        switch (((FrameworkElement)MainWindow.Content).ActualTheme)
        {
            case ElementTheme.Dark:
                m_configurationSource.Theme = SystemBackdropTheme.Dark;
                break;
            case ElementTheme.Light:
                m_configurationSource.Theme = SystemBackdropTheme.Light;
                break;
            case ElementTheme.Default:
                m_configurationSource.Theme = SystemBackdropTheme.Default;
                break;
        }
    }

    private static void Window_ThemeChanged(FrameworkElement sender, object args)
    {
        if (m_configurationSource != null) SetConfigurationSourceTheme();
    }

    private static void Window_Activated(object sender, WindowActivatedEventArgs args)
    {
        m_configurationSource.IsInputActive = args.WindowActivationState != WindowActivationState.Deactivated;
    }
}

public class WindowsSystemDispatcherQueueHelper
{
    private object _mDispatcherQueueController;

    [DllImport("CoreMessaging.dll")]
    private static extern int CreateDispatcherQueueController([In] DispatcherQueueOptions options,
        [In] [Out] [MarshalAs(UnmanagedType.IUnknown)]
        ref object dispatcherQueueController);

    public void EnsureWindowsSystemDispatcherQueueController()
    {
        if (DispatcherQueue.GetForCurrentThread() != null)
            // one already exists, so we'll just use it.
            return;

        if (_mDispatcherQueueController == null)
        {
            DispatcherQueueOptions options;
            options.dwSize = Marshal.SizeOf(typeof(DispatcherQueueOptions));
            options.threadType = 2; // DQTYPE_THREAD_CURRENT
            options.apartmentType = 2; // DQTAT_COM_STA

            CreateDispatcherQueueController(options, ref _mDispatcherQueueController);
        }
    }

    [StructLayout(LayoutKind.Sequential)]
    private struct DispatcherQueueOptions
    {
        internal int dwSize;
        internal int threadType;
        internal int apartmentType;
    }
}
public MainWindow()
    {
        InitializeComponent();
        Activated += (_, _) =>
        {
            UIHelper.AppWindow.Resize(new SizeInt32(UIHelper.GetActualPixel(750), UIHelper.GetActualPixel(800)));
            UIHelper.TrySetMicaBackdrop();
        };
    }

The above code borrows the sample code in WinUI 3 Gallery.

0reactions
xiaoli8848commented, Aug 29, 2022

According to Microsoft Docs page, using Mica material requires Microsoft.WindowsAppSDK NuGet Package. This is more troublesome on non-WinUI projects that are not packaged.

Read more comments on GitHub >

github_iconTop Results From Across the Web

WinUI 3 App Runs on Development Machine, Crashes ...
I have a WinUI3/Windows App executable which runs fine on my development machine. After it's signed it can be installed on the development ......
Read more >
WinUI 3 app crashed when deployed to the store
Since I deploy my app to the store I think it goes under packaged. As far as I can see this issue only...
Read more >
We're the Windows Developer team, and we're back to talk ...
It sounds like a silly test but if you right click on the Start Button and hit 'Esc' when the context menu is...
Read more >
Fix Microsoft Store Crashing on Windows 10
In the search field, type in “WSReset.exe” and right-click on the application from the search results. Click Run as administrator from the context...
Read more >
Is the Windows Settings App Crashing? Try These Fixes
Click on the Windows icon on your taskbar and right-click on the Settings icon. · Choose App settings from the context menu. ·...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found