在C#中调用WinAPI更改窗口图标,可以通过以下步骤实现:
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr SetClassLongPtr(IntPtr hWnd, int nIndex, IntPtr dwNewLong);
private const int GCLP_HICON = -14;
private const int ICON_SMALL = 0;
private const int ICON_BIG = 1;
Icon icon = new Icon("path_to_icon_file.ico");
IntPtr hWnd = Process.GetCurrentProcess().MainWindowHandle;
SetClassLongPtr(hWnd, GCLP_HICON + ICON_SMALL, icon.Handle);
SetClassLongPtr(hWnd, GCLP_HICON + ICON_BIG, icon.Handle);
完整的代码示例:
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Drawing;
public class Program
{
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr SetClassLongPtr(IntPtr hWnd, int nIndex, IntPtr dwNewLong);
private const int GCLP_HICON = -14;
private const int ICON_SMALL = 0;
private const int ICON_BIG = 1;
public static void Main()
{
Icon icon = new Icon("path_to_icon_file.ico");
IntPtr hWnd = Process.GetCurrentProcess().MainWindowHandle;
SetClassLongPtr(hWnd, GCLP_HICON + ICON_SMALL, icon.Handle);
SetClassLongPtr(hWnd, GCLP_HICON + ICON_BIG, icon.Handle);
}
}
请注意,上述代码中的"path_to_icon_file.ico"应替换为实际的图标文件路径。此外,该代码仅适用于当前进程的主窗口,如果需要更改其他窗口的图标,需要获取相应窗口的句柄。
这是一个使用C#调用WinAPI更改窗口图标的基本示例。在实际应用中,可以根据具体需求进行扩展和优化。
领取专属 10元无门槛券
手把手带您无忧上云