检查时如何更改 System.Windows.Forms.ToolStripButton 突出显示/背景颜色?
Posted
技术标签:
【中文标题】检查时如何更改 System.Windows.Forms.ToolStripButton 突出显示/背景颜色?【英文标题】:How to change System.Windows.Forms.ToolStripButton highlight/background color when checked? 【发布时间】:2010-01-19 21:18:56 【问题描述】:我有一个用作单选按钮的 ToolStripButton。选中时,按钮周围有蓝色轮廓,但没有背景颜色。用户还不清楚该按钮是否被选中,所以我想更改背景颜色以使选中状态更加可见。
当 Checked 属性设置为 true 时,如何更改高亮颜色?
这是一个代码sn-p:
this.hideInactiveVehiclesToolstripButton.CheckOnClick = true;
this.hideInactiveVehiclesToolstripButton.ForeColor = System.Drawing.Color.Blue;
this.hideInactiveVehiclesToolstripButton.AutoSize = false;
this.hideInactiveVehiclesToolstripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.hideInactiveVehiclesToolstripButton.Image = global::ClientUI.Properties.Resources.toggleInactive;
this.hideInactiveVehiclesToolstripButton.ImageTransparentColor = System.Drawing.Color.Black;
this.hideInactiveVehiclesToolstripButton.Name = "hideInactiveVehiclesToolstripButton";
this.hideInactiveVehiclesToolstripButton.Size = new System.Drawing.Size(48, 48);
this.hideInactiveVehiclesToolstripButton.Text = "Hide Inactive Vehicles";
this.hideInactiveVehiclesToolstripButton.Click +=new System.EventHandler(this.hideInactiveVehiclesToolstripButton_Click);
【问题讨论】:
【参考方案1】:您可以提供自己的工具条渲染器以按照您想要的方式绘制按钮的背景。此示例代码为选中的按钮提供了一个非常明显的黑色背景:
public partial class Form1 : Form
public Form1()
InitializeComponent();
toolStrip1.Renderer = new MyRenderer();
private class MyRenderer : ToolStripProfessionalRenderer
protected override void OnRenderButtonBackground(ToolStripItemRenderEventArgs e)
var btn = e.Item as ToolStripButton;
if (btn != null && btn.CheckOnClick && btn.Checked)
Rectangle bounds = new Rectangle(Point.Empty, e.Item.Size);
e.Graphics.FillRectangle(Brushes.Black, bounds);
else base.OnRenderButtonBackground(e);
【讨论】:
如果您不喜欢此示例中绘制的矩形的大小,如果您不想覆盖背景边框,则可能需要使用按钮的 ContentRectangle 属性。【参考方案2】:每个 toolStripButton 的事件点击
private void toolStripButton4_Click(object sender, EventArgs e)
toolStrip1.Items[0].BackColor = SystemColors.ActiveCaption;
toolStrip1.Items[1].BackColor = SystemColors.Control;
toolStrip1.Items[2].BackColor = SystemColors.Control;
toolStrip1.Items[3].BackColor = SystemColors.Control;
【讨论】:
【参考方案3】:这是 VB.net 代码
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
toolStrip1.Renderer = New MyRenderer()
End Sub
Public Class MyRenderer
Inherits ToolStripProfessionalRenderer
Protected Overrides Sub OnRenderButtonBackground(ByVal e As ToolStripItemRenderEventArgs)
Dim btn As ToolStripButton = e.Item
If (Not IsDBNull(btn) And btn.CheckOnClick And btn.Checked) Then
Dim bounds As Rectangle = New Rectangle(Point.Empty, e.Item.Size)
e.Graphics.FillRectangle(Brushes.Black, bounds)
End If
End Sub
End Class
【讨论】:
以上是关于检查时如何更改 System.Windows.Forms.ToolStripButton 突出显示/背景颜色?的主要内容,如果未能解决你的问题,请参考以下文章
每当打开我的应用程序时,您将如何检查 DATE 是不是已更改?迅速