小编典典

将System.Drawing.Icon转换为System.Media.ImageSource

c#

我在与图标手柄相对应的不受管/受管边界上整理了一个IntPtr。通过FromHandle()方法将其转换为Icon很简单,直到最近它还是令人满意的。

基本上,由于我一直在播放MTA /
STA舞蹈以防止宿主WinForm破坏应用程序的主(WPF原始)UI太脆弱,因此我一直在进行足够的线程怪异操作。因此WinForm必须开始。

那么,如何获得Icon的ImageSource版本?

注意,我尝试了ImageSourceConverter无济于事。

顺便说一句,我可以获取 某些 但不是全部图标的基础资源,它们通常存在于应用程序的程序集之外(实际上,它们通常存在于非​​托管dll中)。


阅读 715

收藏
2020-05-19

共1个答案

小编典典

尝试这个:

Icon img;

Bitmap bitmap = img.ToBitmap();
IntPtr hBitmap = bitmap.GetHbitmap();

ImageSource wpfBitmap =
     Imaging.CreateBitmapSourceFromHBitmap(
          hBitmap, IntPtr.Zero, Int32Rect.Empty, 
          BitmapSizeOptions.FromEmptyOptions());

更新 :纳入亚历克斯的建议,并将其作为扩展方法:

internal static class IconUtilities
{
    [DllImport("gdi32.dll", SetLastError = true)]
    private static extern bool DeleteObject(IntPtr hObject);

    public static ImageSource ToImageSource(this Icon icon)
    {            
        Bitmap bitmap = icon.ToBitmap();
        IntPtr hBitmap = bitmap.GetHbitmap();

        ImageSource wpfBitmap = Imaging.CreateBitmapSourceFromHBitmap(
            hBitmap,
            IntPtr.Zero,
            Int32Rect.Empty,
            BitmapSizeOptions.FromEmptyOptions());

        if (!DeleteObject(hBitmap))
        {
            throw new Win32Exception();
        }

        return wpfBitmap;
    }
}

然后,您可以执行以下操作:

ImageSource wpfBitmap = img.ToImageSource();
2020-05-19