gbk*_*gbk 0 c# kill process winforms
我的程序有事件onClosing- 只是隐藏它.但我还需要实现程序的关闭 - 尝试使用任务栏通知项的上下文菜单.
码:
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();
}
Run Code Online (Sandbox Code Playgroud)
但也读了一下,kill()终止所有工作并"杀死"进程,认为关闭程序可能不正常 - 某些数据可能被破坏或未被存储
还尝试使用proc.closeMainWindow();和proc.Close()-但PROGRAMM没有影响-关闭所有窗口,但过程仍在运行.
问题:.kill()这是关闭程序的正确方法,还是另一种方法呢?
您可以.Close()在menuitem中调用click并设置一个布尔标志,以便OnClose处理程序可以检查该标志并知道它应该真正关闭.这比试图杀死你自己的进程要安全得多.
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();
}
Run Code Online (Sandbox Code Playgroud)