Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

This article is a Private article. Only a writer and users who know the URL can access it.
Please change open range to public in publish setting if you want to share this article with other users.

WPF タイトルバーのアイコンを非表示にする方法

0
Posted at

はじめに

通常のプロパティでは、タイトルバーのアイコンだけをピンポイントで非表示化することはできないので、その対応です。

環境

  • Visual Studio Community 2022
  • .NET 8.0

ソース

Win32 API を使用します。

WindowIconRemover.cs
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;

namespace Utilities;

/// <summary>
/// ウィンドウのアイコンを非表示にする機能を提供します。
/// </summary>
public static class WindowIconRemover
{
    [DllImport("user32.dll")]
    private static extern int GetWindowLong(IntPtr hwnd, int index);

    [DllImport("user32.dll")]
    private static extern int SetWindowLong(IntPtr hwnd, int index, int newStyle);

    [DllImport("user32.dll")]
    private static extern bool SetWindowPos(IntPtr hwnd, IntPtr hwndInsertAfter, int x, int y, int width, int height, uint flags);

    private const int GWL_EXSTYLE = -20;
    private const int WS_EX_DLGMODALFRAME = 0x0001;
    private const uint SWP_FLAGS = 0x0027;

    /// <summary>
    /// 指定したウィンドウのアイコンを非表示にします。
    /// </summary>
    /// <param name="window">アイコンを非表示にする <see cref="Window"/> オブジェクト。</param>
    public static void Apply(Window window)
    {
        // ウィンドウハンドルを取得する。
        var hwnd = new WindowInteropHelper(window).Handle;
        if (hwnd == IntPtr.Zero)
        {
            window.SourceInitialized += (s, e) => Apply(window);
            return;
        }

        // 現在のウィンドウスタイルを取得する。
        var exStyle = GetWindowLong(hwnd, GWL_EXSTYLE);

        // 変更したスタイルをウィンドウに適用する。
        _ = SetWindowLong(hwnd, GWL_EXSTYLE, exStyle | WS_EX_DLGMODALFRAME);

        // ウィンドウを再描画する。
        SetWindowPos(hwnd, IntPtr.Zero, 0, 0, 0, 0, SWP_FLAGS);
    }
}

使い方

MainWindow の OnSourceInitialized イベントで適用します。

MainWindow.cs
protected override void OnSourceInitialized(EventArgs e)
{
    base.OnSourceInitialized(e);
    WindowIconRemover.Apply(this);
}

おわりに

たまに使うと思います。

0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?