I'm trying to set the icon of my window to match the one that is visible in file explorer. And doing it was a success, but when I closed the window (and after it disappears) i got an error window that my application is stopped working (I was debugging it). Here is my code:
using (Bitmap icon = Icon.ExtractAssociatedIcon(Assembly.GetExecutingAssembly().Location).ToBitmap())
{
unsafe
{
BitmapData data = icon.LockBits(new Rectangle(0, 0, icon.Width, icon.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
byte* ptr = (byte*)data.Scan0;
int size = data.Width * data.Height * 4;
byte[] pixels = new byte[size];
for (int i = 0; i < size; i++)
{
pixels[i] = ptr[i];
}
//Swap chanels.
for (int i = 0; i < size / 4; i++)
{
byte t = pixels[i * 4 + 0];
pixels[i * 4 + 0] = pixels[i * 4 + 2];
pixels[i * 4 + 2] = t;
}
SetIcon((uint)icon.Width, (uint)icon.Height, pixels);
icon.UnlockBits(data);
}
}
If I comment out that whole code block, everything is fine. It happens even if the SetIcon line is commented out.
Here is the error report in that window:
Problem signature:
Problem Event Name: APPCRASH
Application Name: AppName.vshost.exe
Application Version: 10.0.30319.1
Application Timestamp: 4ba2084b
Fault Module Name: StackHash_d340
Fault Module Version: 6.1.7600.16385
Fault Module Timestamp: 4a5bdb3b
Exception Code: c0000374
Exception Offset: 000cdcbb
OS Version: 6.1.7600.2.0.0.256.1
Locale ID: 1038
Additional Information 1: d340
Additional Information 2: d340cfbcf5d2a1596ea02401d3971e0b
Additional Information 3: f1b1
Additional Information 4: f1b10f8b730cb6e83e0c8b6ce5c965b2
I would be happy even if the only thing you can help me is show a way to load it from a png file using C#. To do so I misses a method that is available in C++ if I remember well.