views:

277

answers:

2

have a program that fades out on mouse leave event.

but the problem is when the mouse goes in to a child of the form like a Button, it triggers the mouse leave event. so i set up this code.

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

but the problem now is that the form often does not trigger the mouse leave event, looks to be because the buttons are so close to the form edges that it never registrer that the mouse left the form boundaries, probably because the mouse cursor is to fast and skips over the form when it leaves.

any suggestions on how to handel this?

+1  A: 

Here is a simple utility class to do this, first use it in your form like this:

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

Then add this code to your project:

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;
 }
}
csharptest.net
A: 

Try deactive event of form instead

MikeG
I think this only fires when some other window becomes active - not when the mouse leaves the form.
ChrisF