如何为一组控件创建悬停效果?

How can a hover effect be created for a grouping of controls?(如何为一组控件创建悬停效果?)
本文介绍了如何为一组控件创建悬停效果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

This seems so simple but I just can't seem to figure it out.

See the image below:

It is a panel with 5 labels on it.

The behavior I want is that if the mouse enters the box (anywhere), the background color changes (for ex: AliceBlue instead of White). The problem is in Windows Forms, the transparency is wierd among other problems. If I set the background of the panel on mouse enter, the labels all still have white backgrounds and so I have white blocks around the labels. Etc.

I am sure others have run into this problem. And I'm sure it's simple. I just can't get it.

解决方案

BackColor is an 'ambient' property. It doesn't work right because you set the labels' BackColor explicitly. Right-click the BackColor property of the labels and click Reset so it is no longer shown in bold. Changing the panel's BackColor will now automatically change the labels' BackColor as well.

This however still doesn't solve your problem. The panel's MouseLeave event will fire when you move the mouse across one of the labels. There is no clean solution for this in Winforms, subscribing all the labels and the panel's MouseEnter/Leave events doesn't eliminate corner cases. Like when the user very quickly moves the mouse from a label that's close to the edge of the panel. You'll get the MouseLeave for the label but not the MouseEnter + Leave for the panel.

The only good fix for this is a timer or the Application.Idle event. Like this:

public partial class Form1 : Form {
    public Form1() {
        InitializeComponent();
        Application.Idle += Application_Idle;
    }
    protected override void OnFormClosed(FormClosedEventArgs e) {
        Application.Idle -= Application_Idle;
        base.OnFormClosed(e);
    }
    void Application_Idle(object sender, EventArgs e) {
        var pos = panel1.PointToClient(Cursor.Position);
        if (panel1.DisplayRectangle.Contains(pos)) panel1.BackColor = Color.Red;
        else panel1.BackColor = this.BackColor;
    }
}

这篇关于如何为一组控件创建悬停效果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
quot;Overflowquot; compiler error with -9223372036854775808L(编译器错误-9223372036854775808L(Q;溢出Q))
Visual Studio 2010 ReportViewer Assembly References(Visual Studio 2010 ReportViewer程序集引用)
Weird behaviour when I open a reportviewer in WPF(在WPF中打开报表查看器时出现奇怪的行为)