Anil Kocabiyik
Anil Kocabiyik

Reputation: 1188

Close application when mouse leaves form

I try to use mouse leave event handler but i can not work it.

private void Form1_MouseLeave(object sender, EventArgs e)
{
    this.Close();            
}

I don't want to fade. It should be closed immediately when the mouse cursor goes out of the form screen.

Upvotes: 0

Views: 1996

Answers (5)

Jodrell
Jodrell

Reputation: 35716

I made a little test program to recreate your problem.

namespace OddFormTest
{
    using System;
    using System.Windows.Forms;

    public class OddForm : Form
    {
        public OddForm()
        {
            this.Leave += Leaver;
        }

        [STAThread]
        internal static void Main()
        {
            Application.Run(new OddForm);
        }

        private void Leave(object sender, EventArgs e)
        {
            this.Close()
        }
    }
}

As you infer in the question. The Leave event doesn't fire after you leave your application.

Upvotes: 0

heralight
heralight

Reputation: 957

If you have several forms I prefer Application.Exit().

Form.Close() only works for a single form application.

Upvotes: 1

KKS
KKS

Reputation: 3630

  1. If there is only one form in that application you are using, then Application.Exit will close the application itself.

  2. If there is one more form that you are navigating to from the main form, then in the new form, use Form2.Close(), this will take you to the back to the main application that you are using.

  3. If you want to close both of them, then first give Form2.Close() and then give Application.Exit(). That would suffice.

Upvotes: 0

LarsTech
LarsTech

Reputation: 81610

The MouseLeave event will fire if the mouse enters a child control, which is probably not what you want.

Try using a timer:

private System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
private bool mouseEntered = false;

public Form1() {
  InitializeComponent();

  timer.Tick += timer_Tick;
  timer.Start();
}

protected override void OnMouseEnter(EventArgs e) {
  mouseEntered = true;
  base.OnMouseEnter(e);
}

void timer_Tick(object sender, EventArgs e) {
  if (mouseEntered && !this.Bounds.Contains(Cursor.Position)) {
    this.Close();
  }
}

Upvotes: 2

user1947960
user1947960

Reputation: 308

To close the whole application use

Environment.Exit(0);

Upvotes: 2

Related Questions