如何更改/删除WinUI 3中的窗口标题栏图标

问题描述 投票:0回答:2

是否可以更改 Windows 10 中的 Windows 标题栏图标。

我已经尝试过这些文档,但他们并没有真正提供任何帮助来完成它。它说只能在 Windows 11 中完成???提供 svg 图像应该是理想的解决方案。

svg winui-3 titlebar custom-titlebar
2个回答
1
投票

这是更改图标的最少代码。在我的 Win 10 上工作,但您需要将 *.svg 转换为 *.ico。

using Microsoft.UI;
using Microsoft.UI.Windowing;
using Microsoft.UI.Xaml;
using System;
using WinRT.Interop;

namespace TitleBarIconExample;

public sealed partial class MainWindow : Window
{
    public MainWindow()
    {
        this.InitializeComponent();

        if (AppWindowTitleBar.IsCustomizationSupported() is true)
        {
            IntPtr hWnd = WindowNative.GetWindowHandle(this);
            WindowId wndId = Win32Interop.GetWindowIdFromWindow(hWnd);
            AppWindow appWindow = AppWindow.GetFromWindowId(wndId);
            appWindow.SetIcon(@"Assets\WinUI.ico");
        }
    }
}

0
投票

这是一种解决方案,不需要资产中的物理文件,而只使用输出 .exe 的图标(如果有)。

首先,确保 .csproj 中有一个

ApplicationIcon
属性(也可以在项目的属性 UI 中设置):

<Project Sdk="Microsoft.NET.Sdk">
    <PropertyGroup>
      ...
        <ApplicationIcon>WinUI3App1.ico</ApplicationIcon>
      ...
    </PropertyGroup>
    ...
</Project>

exe 现在将在资源管理器中显示一个漂亮的图标:

enter image description here

然后在窗口构造函数中使用此代码:

public sealed partial class MainWindow : Window
{
    private OtherWindow _myOtherWindow;

    public MainWindow()
    {
        this.InitializeComponent();

        var exeHandle = GetModuleHandle(Path.GetFileName(Process.GetCurrentProcess().MainModule.FileName));
        var icon = LoadImage(exeHandle, IDI_APPLICATION, IMAGE_ICON, 16, 16, 0);
        AppWindow.SetIcon(Win32Interop.GetIconIdFromIcon(icon));
        // possibly call DestroyIcon after window has been closed
    }

    private const int IDI_APPLICATION = 32512;
    private const int IMAGE_ICON = 1;

    [DllImport("kernel32", CharSet = CharSet.Unicode)]
    private static extern nint GetModuleHandle(string lpModuleName);

    [DllImport("user32", CharSet = CharSet.Unicode)]
    private static extern nint LoadImage(nint hinst, nint name, int type, int cx, int cy, int fuLoad);

    // call this if/when you want to destroy the icon (window closed, etc.)
    [DllImport("user32")]
    private static extern bool DestroyIcon(nint hIcon);
}

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.