C# Application.ApplicationExit creates need to click 'X' twice
I have created a WinForm in Visual Studio, and in its code it has a fair few functions. At this point its all working nicely. I then go and put
Application.ApplicationExit += new EventHandler开发者_运维百科(Application_ApplicationExit);
in the constructor function and when I go and click the little cross in the corner, I have to click it twice for it to close! I would put the code in here, but its 240 lines, so its kinda huge.. If you need to see it though, I can put it up.
Thanks in advance!
DronnocThe ApplicationExit event is automaticly called on clicking the cross. So there is actual no need to call it. What do you want to do on closing?
If you want some action between clicking the cross and shutdown, you have to call the FormClosing() event.
I have solved it peoples!
I had a ListBox on the page, and a function running when the SelectedIndex changed. When i closed the form, it passed a SelectedIndex of -1, and then closed the second time. So, in order to fix it, I simply put some simple verification of the value on the ListBox function.
Example:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
listBox1.SelectedIndexChanged += new EventHandler(listBox1_SelectedIndexChanged);
}
void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
becomes
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
listBox1.SelectedIndexChanged += new EventHandler(listBox1_SelectedIndexChanged);
}
void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if(listBox1.SelectedIndex == -1)
{
Application.Exit();
}
//Rest of the code goes here.
}
}
}
精彩评论