Icon.FromHandle: should I Dispose it, or call DestroyIcon?

后端 未结 3 1270
执念已碎
执念已碎 2020-12-20 17:06

I use Win32 SHGetFileInfo to get a handle to the icon belonging to a certain file. There are a lot of descriptions how to do this, also on stackoverflow, for instance: Get i

3条回答
  •  既然无缘
    2020-12-20 18:03

    I have had NO END of grief in this area - I've been trying to animate a form's icon (and consequently the one in the task bar) without it leaking resources.

    When I disposed of the icon (as suggested on MSDN) resources leaked, when I used "DestroyIcon" all subsequent updates failed. This code below shows everything in the correct order.

    API Declaration:

    [System.Runtime.InteropServices.DllImport("user32.dll", CharSet = CharSet.Auto)]
    extern static bool DestroyIcon(IntPtr handle);
    

    FINALLY the solution:

    IntPtr iconHandle = dynamicBitmap.GetHicon();
    Icon tempManagedRes = Icon.FromHandle(iconHandle);
    this.Icon = (Icon)tempManagedRes.Clone();
    tempManagedRes.Dispose();
    DestroyIcon(iconHandle);
    

    Also posted in this question: Win32.DestroyIcon vs. Icon.Dispose

提交回复
热议问题