gpt4 book ai didi

c# - 鼠标进入/离开Form和Button子事件问题

转载 作者:太空狗 更新时间:2023-10-29 23:42:39 25 4
gpt4 key购买 nike

有一个在鼠标离开事件时淡出的程序。

但问题是当鼠标进入像 Button 这样的窗体的子级时,它会触发鼠标离开事件。所以我设置了这段代码。

private void Form1_MouseLeave(object sender, EventArgs e)
{
if (this.ClientRectangle.Contains(this.PointToClient(Cursor.Position)))
{
this.Opacity = 1.0;
}
else
{
int loopctr = 0;

for (loopctr = 100; loopctr >= 5; loopctr -= 10)
{
this.Opacity = loopctr / 99.0;
this.Refresh();
Thread.Sleep(100);
}
}
}

但现在的问题是表单经常不会触发鼠标离开事件,看起来是因为按钮太靠近表单边缘以至于它永远不会注册鼠标离开表单边界,可能是因为鼠标光标是为了快速并在它离开时跳过表格。

关于如何处理这个有什么建议吗?

最佳答案

这是一个简单的实用程序类来执行此操作,首先像这样在您的表单中使用它:

partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
new FadeForm(this, TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(0.25), 0.05);
}
}

然后将此代码添加到您的项目中:

class FadeForm
{
readonly Form _top;
readonly Timer _timer;
readonly TimeSpan _delayToFade;
readonly double _fadeAmount;

Control _lastControl;
DateTime _lastActivity;

public FadeForm(Form ctrl, TimeSpan delayToFade, TimeSpan delaySpeed, double fadeAmount)
{
_top = ctrl;
_delayToFade = delayToFade;
_fadeAmount = fadeAmount;
_lastActivity = DateTime.Now;

WatchControl(_top);

_timer = new Timer();
_timer.Interval = (int)delaySpeed.TotalMilliseconds;
_timer.Enabled = true;
_timer.Tick += new EventHandler(Tick);
}

void Tick(object sender, EventArgs e)
{
if (_lastControl != null || (DateTime.Now - _lastActivity) < _delayToFade)
{
if (_top.Opacity != 1)
_top.Opacity = 1;
}
else
{
double newvalue = _top.Opacity -= _fadeAmount;
if (newvalue > 0.0)
_top.Opacity = newvalue;
else
_top.Close();
}
}

void WatchControl(Control c)
{
c.MouseEnter += new EventHandler(MouseEnter);
c.MouseLeave += new EventHandler(MouseLeave);
}

void MouseEnter(object sender, EventArgs e)
{
_lastControl = sender as Control;
}

void MouseLeave(object sender, EventArgs e)
{
_lastControl = null;
_lastActivity = DateTime.Now;
}
}

关于c# - 鼠标进入/离开Form和Button子事件问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1460508/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com