// Create an HICON handle from an icon. // "DeleteObject" must be called on it when no longer needed. IntPtr HandleFromIcon(Icon icon) { Frame frame = ToolkitManager.GetImageFrame(icon); Win32.Api.ICONINFO iconInfo = new System.Drawing.Win32.Api.ICONINFO(); iconInfo.fIcon = true; // Hotspot is always the middle for an icon. iconInfo.xHotspot = iconInfo.yHotspot = 0; // Create the mono bitmap mask using CreateBitmap rather than CreateDIBitmap, its faster. // CreateBitmap expects the mask data to be word aligned, not int aligned and the mask is inverted. int frameBytes = (frame.Width + 7) / 8; int newStride = (frameBytes + 1) & ~1; byte[] inverseMask = new byte[frame.Height * newStride]; int prevOldPos = 0; int prevNewPos = 0; for (int y = 0; y < frame.Height; y++) { int oldPos = prevOldPos; int newPos = prevNewPos; for (int b = 0; b < frameBytes; b++) { inverseMask[newPos++] = (byte)~frame.Mask[oldPos++]; } prevOldPos += frame.MaskStride; prevNewPos += newStride; } iconInfo.hbmMask = Win32.Api.CreateBitmap(frame.Width, frame.Height, 1, 1, inverseMask); iconInfo.hbmColor = HandleFromBitmap(frame, true); IntPtr iconHandle = Win32.Api.CreateIconIndirect(ref iconInfo); Win32.Api.DeleteObject(iconInfo.hbmMask); Win32.Api.DeleteObject(iconInfo.hbmColor); return(iconHandle); }
// Create an HICON handle from an icon. // "DeleteObject" must be called on it when no longer needed. IntPtr HandleFromIcon(Icon icon) { Frame frame = ToolkitManager.GetImageFrame(icon); Win32.Api.ICONINFO iconInfo = new System.Drawing.Win32.Api.ICONINFO(); iconInfo.fIcon = true; // Hotspot is always the middle for an icon. iconInfo.xHotspot = iconInfo.yHotspot = 0; // Create the mono bitmap mask using CreateBitmap rather than CreateDIBitmap, its faster. // CreateBitmap expects the mask data to be word aligned, not int aligned and the mask is inverted. int frameBytes = (frame.Width + 7) / 8; int newStride = (frameBytes + 1) & ~ 1; byte[] inverseMask = new byte[frame.Height * newStride]; int prevOldPos = 0; int prevNewPos = 0; for (int y = 0; y < frame.Height; y++) { int oldPos = prevOldPos; int newPos = prevNewPos; for (int b = 0; b < frameBytes; b++) inverseMask[newPos++] = (byte)~frame.Mask[oldPos++]; prevOldPos += frame.MaskStride; prevNewPos += newStride; } iconInfo.hbmMask = Win32.Api.CreateBitmap(frame.Width, frame.Height, 1, 1, inverseMask); iconInfo.hbmColor = HandleFromBitmap(frame, true); IntPtr iconHandle = Win32.Api.CreateIconIndirect(ref iconInfo); Win32.Api.DeleteObject(iconInfo.hbmMask); Win32.Api.DeleteObject(iconInfo.hbmColor); return iconHandle; }