はじめに
通常のプロパティでは、タイトルバーのアイコンだけをピンポイントで非表示化することはできないので、その対応です。
環境
- 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);
}
おわりに
たまに使うと思います。