首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在C#中调用winapi更改窗口图标

在C#中调用WinAPI更改窗口图标,可以通过以下步骤实现:

  1. 首先,需要引入System.Runtime.InteropServices命名空间,以便使用DllImport特性来调用WinAPI函数。
  2. 使用DllImport特性声明user32.dll库中的SetClassLongPtr函数,该函数用于设置窗口类的属性。
代码语言:txt
复制
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr SetClassLongPtr(IntPtr hWnd, int nIndex, IntPtr dwNewLong);
  1. 定义SetClassLongPtr函数的常量参数。
代码语言:txt
复制
private const int GCLP_HICON = -14;
private const int ICON_SMALL = 0;
private const int ICON_BIG = 1;
  1. 创建一个Icon对象,用于表示要设置的窗口图标。
代码语言:txt
复制
Icon icon = new Icon("path_to_icon_file.ico");
  1. 获取窗口句柄。
代码语言:txt
复制
IntPtr hWnd = Process.GetCurrentProcess().MainWindowHandle;
  1. 调用SetClassLongPtr函数来设置窗口类的属性,将图标应用到窗口。
代码语言:txt
复制
SetClassLongPtr(hWnd, GCLP_HICON + ICON_SMALL, icon.Handle);
SetClassLongPtr(hWnd, GCLP_HICON + ICON_BIG, icon.Handle);

完整的代码示例:

代码语言:txt
复制
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更改窗口图标的基本示例。在实际应用中,可以根据具体需求进行扩展和优化。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券