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

时间:2009-09-22 14:42:32

标签: c# winforms forms button events

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

但问题是当鼠标像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);
        }
    }
}

但现在的问题是表单通常不会触发鼠标离开事件,看起来是因为按钮非常靠近表单边缘,它从不注册表示鼠标离开表单边界,可能是因为鼠标光标是快速的,并在它离开时跳过表格。

关于如何处理此事的任何建议?

2 个答案:

答案 0 :(得分:2)

这是一个简单的实用程序类,首先在你的表单中使用它:

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;
    }
}

答案 1 :(得分:0)

尝试使用表单的非活动事件