0

my program has event onClosing - just hide it. But also i need to implement closing of programm - try to use context menu of task bar notification item.

code:

    private void FormMainForm_FormClosing(object sender, FormClosingEventArgs e)
    {
        //canceling closing form
        e.Cancel = true;
        //hide form 
        this.WindowState = FormWindowState.Minimized;
    }

    private void toolStripMenuItem1_Click(object sender, EventArgs e)
    {
        //hide icon from tray
        notifyIcon.Visible = false;
        //get current process
        Process proc = Process.GetCurrentProcess();
        //kill it and close programm
        proc.Kill();
    }

but also read a little bit, that kill() terminate all work and "kill" the process, think it can be not normal way to close programm - some data can be destroyed or not stored

also try to use proc.closeMainWindow(); and proc.Close() - but no effect on programm - all windows closed, but process still running.

Question: are .kill() it's a correct way to close programm, or ther is some another way to do it?

hbk
  • 10,908
  • 11
  • 91
  • 124

1 Answers1

5

You could just call .Close() in your menuitem click and set a boolean flag so that the OnClose handler can check that flag and know that it should really close. That would be a lot safer than trying to kill your own process.

private bool onlyHideOnClose = true;

private void FormMainForm_FormClosing(object sender, FormClosingEventArgs e)
{
    if(this.onlyHideOnClose)
    {
        e.Cancel = true;
        this.WindowState = FormWindowState.Minimized;
    }
}

private void toolStripMenuItem1_Click(object sender, EventArgs e)
{
    this.onlyHideOnClose = false;
    this.Close();
}
nvoigt
  • 75,013
  • 26
  • 93
  • 142