c# - 单击控件并使其变暗

标签 c# .net winforms windows-themes

在 Windows 中,当您单击桌面上的图标时,该图标会变暗并带有基于您当前使用的 Windows 主题的阴影。

我有一个显示图像的自定义控件。我希望具有与 Windows 图标单击相同的功能。如何通过选择我的自定义控件在 WinForms 中获得相同的结果?

最佳答案

自 Windows XP 以来,Windows 为选定的图标实现了 alpha 混合。如果您想获得相似的外观,您必须使用 alpha 混合绘制图像:

public static void DrawBlendImage(Graphics canvas, Image source, Color blendColor, float blendLevel, int x, int y)
{
  Rectangle SourceBounds = new Rectangle(x, y, source.Width, source.Height);

  ColorMatrix MaskMatrix = new ColorMatrix();
  MaskMatrix.Matrix00 = 0f;
  MaskMatrix.Matrix11 = 0f;
  MaskMatrix.Matrix22 = 0f;
  MaskMatrix.Matrix40 = (float)blendColor.R / byte.MaxValue;
  MaskMatrix.Matrix41 = (float)blendColor.G / byte.MaxValue;
  MaskMatrix.Matrix42 = (float)blendColor.B / byte.MaxValue;
  ImageAttributes MaskAttributes = new ImageAttributes();
  MaskAttributes.SetColorMatrix(MaskMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

  ColorMatrix TransparentMatrix = new ColorMatrix();
  TransparentMatrix.Matrix33 = blendLevel;
  ImageAttributes TransparentAttributes = new ImageAttributes();
  TransparentAttributes.SetColorMatrix(TransparentMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

  canvas.DrawImage(source, SourceBounds, 0, 0, source.Width, source.Height, GraphicsUnit.Pixel, MaskAttributes);
  canvas.DrawImage(source, SourceBounds, 0, 0, source.Width, source.Height, GraphicsUnit.Pixel, TransparentAttributes);
}

在您的情况下,您可以使用 SystemColors.Highlight 作为 blendColor。

关于c# - 单击控件并使其变暗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/927321/

相关文章:

c# - 使用 C# 和反射对类的属性进行单元测试

c# - ASP.NET MVC 自定义 Controller 目录

c# - 等到我的 BackgroundWorker 完成才能打开新的 BackgroundWorker

c# - 更改 Void 名称? (等于 Private Sub NameOfSub() )

c# - Entity Framework 4.3 - TPH 映射和迁移错误

.net - 在 ClientWebSocket 中设置 "User-Agent"HTTP header

c# - 计算 ScrollBar 滚动百分比;滚动条的高度 "bar"?

c# - 如何根据用户输入生成范围不同的数字

c# - 使项目在多个 .NET 版本之间保持同步

.net - Tumblr C# 访问 token oauth_signature 与预期值不匹配 401 错误