private static void SetIconicBitmap(Form f, Icon ico, Size sz, bool bThumbnail) { Image img = null; Bitmap bmp = null; IntPtr hBmp = IntPtr.Zero; try { IntPtr hWnd = f.Handle; if (hWnd == IntPtr.Zero) { Debug.Assert(false); return; } img = UIUtil.ExtractVistaIcon(ico); if (img == null) { img = ico.ToBitmap(); } if (img == null) { Debug.Assert(false); return; } int sw = sz.Width, sh = sz.Height; if (sw <= 0) { Debug.Assert(false); sw = 200; } // Default Windows 7 if (sh <= 0) { Debug.Assert(false); sh = 109; } // Default Windows 7 int iImgW = Math.Min(img.Width, 128); int iImgH = Math.Min(img.Height, 128); int iImgWMax = (sw * 4) / 6; int iImgHMax = (sh * 4) / 6; if (iImgW > iImgWMax) { float fRatio = (float)iImgWMax / (float)iImgW; iImgW = iImgWMax; iImgH = (int)((float)iImgH * fRatio); } if (iImgH > iImgHMax) { float fRatio = (float)iImgHMax / (float)iImgH; iImgW = (int)((float)iImgW * fRatio); iImgH = iImgHMax; } if ((iImgW <= 0) || (iImgH <= 0)) { Debug.Assert(false); return; } if (iImgW > sw) { Debug.Assert(false); iImgW = sw; } if (iImgH > sh) { Debug.Assert(false); iImgH = sh; } int iImgX = (sw - iImgW) / 2; int iImgY = (sh - iImgH) / 2; // 32-bit color depth required by API bmp = new Bitmap(sw, sh, PixelFormat.Format32bppArgb); using (Graphics g = Graphics.FromImage(bmp)) { Color clr = AppDefs.ColorControlDisabled; g.Clear(clr); using (LinearGradientBrush br = new LinearGradientBrush( new Point(0, 0), new Point(sw, sh), UIUtil.LightenColor( clr, 0.25), UIUtil.DarkenColor(clr, 0.25))) { g.FillRectangle(br, 0, 0, sw, sh); } // *After* drawing the gradient (otherwise border bug) g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.SmoothingMode = SmoothingMode.HighQuality; RectangleF rSource = new RectangleF(0.0f, 0.0f, img.Width, img.Height); RectangleF rDest = new RectangleF(iImgX, iImgY, iImgW, iImgH); GfxUtil.AdjustScaleRects(ref rSource, ref rDest); // g.DrawImage(img, iImgX, iImgY, iImgW, iImgH); g.DrawImage(img, rDest, rSource, GraphicsUnit.Pixel); } hBmp = bmp.GetHbitmap(); if (bThumbnail) { DwmSetIconicThumbnail(hWnd, hBmp, DWM_SIT_DISPLAYFRAME); } else { DwmSetIconicLivePreviewBitmap(hWnd, hBmp, IntPtr.Zero, DWM_SIT_DISPLAYFRAME); } } catch (Exception) { Debug.Assert(!WinUtil.IsAtLeastWindows7); } finally { if (hBmp != IntPtr.Zero) { try { NativeMethods.DeleteObject(hBmp); } catch (Exception) { Debug.Assert(false); } } if (bmp != null) { bmp.Dispose(); } if (img != null) { img.Dispose(); } } }