c# - 更改 ComboBox 边框颜色 - SelectedIndex 更改时闪烁

标签 c# .net winforms combobox

我只是想知道在 Windows 窗体中,当组合框更改时,我是否可以在组合框的边框周围创建一条红线?就像一闪而过的红色然后又消失只是为了表明它已经改变了。捕获用户的眼球什么的。我将提供屏幕来表示我想要的内容。

如果可能的话,请告诉我在哪里可以找到它以获得一些相关信息。

无边框 enter image description here 改变时边框闪烁 enter image description here 一两秒后边框再次消失 enter image description here

最佳答案

Anytime the combobox changes, I want to flash a border to indicate it has changed.

主要思想是使用计时器并在某些时候绘制边框。您可以使用不同的解决方案绘制边框。例如,您可以(1)ComboBox 上绘制边框,或者(2) 您可以在Parent 上绘制边框组合框

在我提出的答案中,我创建了一个 MyComboBox 并添加了一个 FlashHotBorder 方法,可以调用该方法来闪烁边框。我还添加了一个 HotBorderColor 属性,可用于设置边框颜色。

组合框闪烁边框

要为 ComboBox 绘制边框,您可以处理 WM_Paint ComboBox 的消息并为控件绘制边框。然后要闪烁边框,您需要使用计时器并打开和关闭边框一段时间:

enter image description here

我的组合框代码

我创建了一个 FlashHotBorder 方法,您可以在 SelectedIndexChanged 事件中调用它。此外,如果您总是希望在选定索引更改时闪烁边框,您可以在 OnSelectedIndexChanged 中调用它。我更喜欢在事件处理程序中调用它。这是实现:

using System.Drawing;
using System.Windows.Forms;
public class MyComboBox : ComboBox
{
    int flash = 0;
    private const int WM_PAINT = 0xF;
    private int buttonWidth = SystemInformation.HorizontalScrollBarArrowWidth;
    public Color HotBorderColor { get; set; }
    private bool DrawBorder { get; set; }
    Timer timer;
    public MyComboBox()
    {
        this.HotBorderColor = Color.Red;
        timer = new Timer() { Interval = 100 };
        timer.Tick += new System.EventHandler(timer_Tick);
    }
    protected override void WndProc(ref Message m)
    {
        base.WndProc(ref m);
        if (m.Msg == WM_PAINT && this.DrawBorder)
            using (var g = Graphics.FromHwnd(this.Handle))
            using (var p = new Pen(this.HotBorderColor))
                g.DrawRectangle(p, 0, 0, this.Width - 1, this.Height - 1);
    }
    public void FlashHotBorder()
    {
        flash = 0;
        timer.Start();
    }
    void timer_Tick(object sender, System.EventArgs e)
    {
        if (flash < 10)
        {
            flash++;
            this.DrawBorder = !this.DrawBorder;
            this.Invalidate();
        }
        else
        {
            timer.Stop();
            flash = 0;
            DrawBorder = false;
        }
    }
    protected override void Dispose(bool disposing)
    {
        if (disposing) { timer.Dispose(); }
        base.Dispose(disposing);
    }
}

然后将此事件处理程序用于要闪烁的每个组合的 SelectedIndexChanged 事件就足够了:

private void myComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    var combo = sender as FlatCombo;
    if (combo != null)
        combo.FlashHotBorder();
}

关于c# - 更改 ComboBox 边框颜色 - SelectedIndex 更改时闪烁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39053998/

相关文章:

c# - 在 Windows 上编译 C# .net 3.5 控制台应用程序是否有任何免费、小型、快速的东西?

c# - 如何转义名称为 SQL 保留关键字的表?

.net - C++/CLI .NET 可以使用资源 .resx 文件进行本地化吗?

vb.net - 表单位置 VB.net

C# WebBrowser CSS 悬停样式不起作用(尽管配置了浏览器仿真)

c# - 如何在 Xamarin Forms PCL 中使用 native Android ImageView?

c# - 登录用户声明的两种方式 - 哪种方式更好?

.net - 打印后缩小的图像模糊

c# - 如何对终结器进行单元测试?

c# - 如何在多用户文件管理系统中锁定文件