Frage

I'm a starting programmer on school and we have to do a big project and I have a problem with 1 of my Forms closing, specifically an own made Form "Closing event".

 private void sluitenToolStripMenuItem_Click(object sender, EventArgs e)
    {
        if (MessageBox.Show("Het programma wordt hiermee gesloten.\nBent u zeker dat u wilt sluiten en uitloggen?",
            "Waarschuwing , u staat op het moment het programma te sluiten",MessageBoxButtons.YesNo, 
            MessageBoxIcon.Exclamation) == DialogResult.Yes)
        {
            Application.Exit();
        }
    }

    private void window_Closing(object sender, FormClosingEventArgs e)
    {
        if(MessageBox.Show("Bent u zeker dat u wilt uitloggen?","Waarschuwing , u staat op het moment uit te loggen",
             MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
        {

            loginForm.Show();
        }
        else
        {
            e.Cancel = true;
        }

Now my problem is when I'm using sluitenToolStripMenuItem_Click and I press the yes button it will close my application which will trigger the window_Closing event. But I only want the window_Closing event to happen when my user clicks te big red X in the right top corner and not when the user clicks on my toolstrip item. Thanks in advance
Also if anyone has any tips on making a good GUI that would be nice ;) (I'm from Belgium so sorry for the dutch in my code )

War es hilfreich?

Lösung

You can keep a variable to store the status from where the event hasbeen generated.

bool ClosedFromMenu = false;
private void sluitenToolStripMenuItem_Click(object sender, EventArgs e)
{
    if (MessageBox.Show("Het programma wordt hiermee gesloten.\nBent u zeker dat u wilt sluiten en uitloggen?",
        "Waarschuwing , u staat op het moment het programma te sluiten",MessageBoxButtons.YesNo, 
        MessageBoxIcon.Exclamation) == DialogResult.Yes)
    {
        ClosedFromMenu = true;
        Application.Exit();
    }
}

private void window_Closing(object sender, FormClosingEventArgs e)
{
   if(!ClosedFromMenu)
   {
    if(MessageBox.Show("Bent u zeker dat u wilt uitloggen?","Waarschuwing , u staat op het moment uit te loggen",
         MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
    {

        loginForm.Show();
    }
    else
    {
        e.Cancel = true;
    }
   }
}

Andere Tipps

In your FormClosing event you can check the sender or the e.CloseReason.

For example following code within FormClosing event handler:

if (e.CloseReason != CloseReason.UserClosing)
{
    //......
}

Will not be executed if you pressed the Alt+F4 or clicked the [X] button.

http://msdn.microsoft.com/en-us/library/system.windows.forms.closereason%28v=vs.110%29.aspx

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top