问题描述
我使用的ToolStrip
的数量为ToolStripButton
s.
I am using a ToolStrip
with a number of ToolStripButton
s.
我希望能够闪烁其中一个按钮来引起用户的注意.
What I would like is to be able to flash one of the buttons to get the user's attention.
例如,如果他们已更改信息并需要单击保存按钮.
For example, if they have made changes to information and need to click the Save button.
如果这是一个普通按钮,我可以使用Timer
并定期更改BackColor
来执行此操作,但这不适用于ToolStrip
.
If this were a normal button I could do this using a Timer
and periodically changing the BackColor
however this doesn't work with a ToolStrip
.
我可以创建一个Renderer子类并将其分配给ToolStrip
,但这似乎仅在特定情况下使用-即它是事件驱动的.
I could create a Renderer subclass and assign it to the ToolStrip
but this appears to only get used in specific situations - i.e. it's event driven.
有人有什么想法吗?
推荐答案
好吧,只需使用自定义渲染器即可更改按钮背景的颜色.带有一个使它闪烁的计时器.将新类添加到您的项目中,然后粘贴以下代码:
Well, just use a custom renderer so you can change the color of the button's background. With a timer that blinks it. Add a new class to your project and paste this code:
using System;
using System.Drawing;
using System.Collections.Generic;
using System.Windows.Forms;
class BlinkingButtonRenderer : ToolStripProfessionalRenderer {
public BlinkingButtonRenderer(ToolStrip strip) {
this.strip = strip;
this.strip.Renderer = this;
this.strip.Disposed += new EventHandler(strip_Disposed);
this.blinkTimer = new Timer { Interval = 500 };
this.blinkTimer.Tick += delegate { blink = !blink; strip.Invalidate(); };
}
public void BlinkButton(ToolStripButton button, bool enable) {
if (!enable) blinkButtons.Remove(button);
else blinkButtons.Add(button);
blinkTimer.Enabled = blinkButtons.Count > 0;
strip.Invalidate();
}
protected override void OnRenderButtonBackground(ToolStripItemRenderEventArgs e) {
var btn = e.Item as ToolStripButton;
if (blink && btn != null && blinkButtons.Contains(btn)) {
Rectangle bounds = new Rectangle(Point.Empty, e.Item.Size);
e.Graphics.FillRectangle(Brushes.Black, bounds);
}
else base.OnRenderButtonBackground(e);
}
private void strip_Disposed(object sender, EventArgs e) {
blinkTimer.Dispose();
}
private List<ToolStripItem> blinkButtons = new List<ToolStripItem>();
private bool blink;
private Timer blinkTimer;
private ToolStrip strip;
}
带有包含按钮的工具条的表单中的用法示例:
Sample usage in a form with a Toolstrip containing a button:
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
blinker = new BlinkingButtonRenderer(toolStrip1);
}
private void toolStripButton1_Click(object sender, EventArgs e) {
blink = !blink;
blinker.BlinkButton(toolStripButton1, blink);
}
private bool blink;
private BlinkingButtonRenderer blinker;
}
这篇关于闪烁的工具条按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!