我创建了一个应用程序。我创建了一个按钮。点击按钮后,进程开始了。现在,当我按下应用程序的关闭('X')按钮时,应用程序关闭。我想要所有这是在点击一个按钮时发生的,即当我第一次点击该按钮时,它应该开始该过程&只要再次单击相同的按钮,该过程就应该关闭。
答案 0 :(得分:1)
在这里。评论在代码内。
using System.Diagnostics;
/// <summary>
/// Process started by our app
/// </summary>
Process process;
private void button1_Click(object sender, EventArgs e)
{
// Haven't been started yet or user closed it
if (process == null || process.HasExited)
{
// Do open
try
{
process = Process.Start("notepad.exe");
}
catch (Exception ex)
{
// Inform user about error
}
}
// It is started
else
{
// many a thing can go wrong here.
// Even something as simple as user closing the app himself
try
{
// Send app instruction to close itself
if (!process.CloseMainWindow())
{
// Unable to comply - has to be put to death
// Merciful people might give it a few retries
// before execution
process.Kill();
}
}
catch (Exception ex)
{
// Inform user about error
}
finally
{
// So the cycle of life can start again
process = null;
}
}
}
答案 1 :(得分:0)
如果应用程序已在运行,即第一次按下该按钮,则可以使用存储真值的标志。然后使用简单的if
条件来调用相应的函数。