Вопрос

I want to hide my application in system tray when I click the Form Closing button(clasic red X button). I provided with this code;

    private void Ana_FormClosing(object sender, FormClosingEventArgs e) 
    {            
        e.Cancel = true; 
        this.Hide();          
    }

So, the application is stil running in the system tray. I have added a ContextMenuStrip and when I right click on mouse ContextMenuStrip a Close button comes up but when I click that Close button the application is still running. I want to terminate the application when I click that Close button. Here is my code:

   private void kapatToolStripMenuItem_Click(object sender, EventArgs e) //Close
   {
        DialogResult ext;
        ext = MessageBox.Show("Çıkmak İstediğinizden Emin misiniz?", "Onay", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

        if (ext == DialogResult.Yes)
        {
            Application.Exit();                
        }       
    }

    private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
    {
        this.Show();                      
    }
Это было полезно?

Решение

Calling Application.Exit() will actually attempt to close all your forms, and because your FormClosing is hard coded to be cancelled, then it cannot complete the task.

One option with your current structure would be to create an AllowClose flag. This could be a property of the Form, or it could be a global static value.

For example:

//in your form
public bool AllowClose {get;set;}

private void Ana_FormClosing(object sender, FormClosingEventArgs e) 
{
    if(!AllowClose)
    {            
        e.Cancel = true; 
        this.Hide();  
    }        
}

//in your context menu event
private void kapatToolStripMenuItem_Click(object sender, EventArgs e) //Close
{

    DialogResult ext;
    ext = MessageBox.Show("Çıkmak İstediğinizden Emin misiniz?", "Onay", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
    if (ext == DialogResult.Yes)
    {
        this.AllowClose = true;
        Application.Exit();
    }       
}

Другие советы

Try this,

bool isClosing = false;


 private void Ana_FormClosing(object sender, FormClosingEventArgs e) 
    {            
        if(!isClosing)
        {
           e.Cancel = true; 
           this.Hide();          
        }
    }




private void kapatToolStripMenuItem_Click(object sender, EventArgs e) //Close
    {
        DialogResult ext;
        isClosing = true;

        ext = MessageBox.Show("Çıkmak İstediğinizden Emin misiniz?", "Onay", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
        if (ext == DialogResult.Yes)
        {
            Application.Exit();

        }       
    }
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top