winforms 在代码中将位图设置为文件的图标

lpwwtiir  于 7个月前  发布在  其他
关注(0)|答案(1)|浏览(49)

我尝试为C#中的文件设置自定义图标,我将其作为位图。我已经遵循了各种来源中提供的示例和建议,但我遇到了以下代码的问题:

using Microsoft.Win32;
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.InteropServices;

class Program
{
    static void Main()
    {
        // Specify the file path
        string filePath = @"C:\Path\To\Your\File.txt";

        // Create a Bitmap representing your custom icon
        Bitmap customIconBitmap = new Bitmap("YourCustomIcon.bmp"); // Replace with your actual bitmap file

        // Convert the custom icon to an Icon
        Icon customIcon;
        using (MemoryStream stream = new MemoryStream())
        {
            customIconBitmap.Save(stream, ImageFormat.Png); // Use the appropriate format for your icon
            customIcon = new Icon(stream);
        }

        // Verify that the file exists
        if (!File.Exists(filePath))
        {
            Console.WriteLine("File does not exist.");
            return;
        }

        // Get the handle to the in-memory icon
        IntPtr iconHandle = customIcon.Handle;

        // Open the file with write access to modify its icon
        using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Write))
        {
            // Set the new icon to the file
            SetFileIcon(fileStream.SafeFileHandle.DangerousGetHandle(), iconHandle);
        }

        // Notify the system about the changes
        SHChangeNotify(0x08000000, 0x0000, IntPtr.Zero, IntPtr.Zero);

        Console.WriteLine("File icon changed successfully!");
    }

    // Declare the SHChangeNotify function from the Shell32.dll
    [DllImport("Shell32.dll")]
    public static extern void SHChangeNotify(long wEventId, uint uFlags, IntPtr dwItem1, IntPtr dwItem2);

    // Declare the SetFileIcon function from the Shell32.dll
    [DllImport("Shell32.dll", SetLastError = true)]
    public static extern int SetFileIcon(IntPtr hFile, IntPtr hIcon);
}

字符串
详细信息:
我在C#代码中有一个表示为Bitmap的自定义图标。我尝试使用MemoryStream将Bitmap转换为Icon,但它导致了上述ArgumentException。我尝试将图标关联的文件确实存在。我已经检查了自定义图标使用的图像格式(在我的情况下为Image.Png)。请求帮助:
我很感激任何关于如何正确地将位图设置为C#文件图标的见解或指导。如果有替代方法或对我的代码的更正,请分享它们。谢谢!

nzrxty8p

nzrxty8p1#

一般来说,没有办法设置在Windows中为单个文件显示的图标。

相关问题