【问题标题】:Alert user about the running process during installation在安装过程中提醒用户正在运行的进程
【发布时间】:2026-01-17 04:05:02
【问题描述】:
protected override void OnBeforeInstall(IDictionary savedState)
{
    base.OnBeforeInstall(savedState);
    DialogResult result = DialogResult.None;
    if (isExcelIsRunning())
    {
        result = MessageBox.Show("Excel is still running. Please save your work and close Excel, and then click \"Retry\" button to continue with installation.", "", MessageBoxButtons.RetryCancel, MessageBoxIcon.Warning);
    }
    while (result == DialogResult.Retry)
    {
        if (!isExcelIsRunning())
        {
            break;
        }
    }
}


//check if excel is currently running
private bool isExcelIsRunning()
{
    bool flag = false;
    Process[] xlProc = Process.GetProcessesByName("excel");
    if (xlProc != null)
        flag = true;
    return flag;
}

以上是我将要用于我的安装程序类的代码。

我想在这里实现的是,我需要安装程序在安装过程中检查 Excel 当前是否正在运行。如果它正在运行,那么在安装开始时应该会弹出一条消息,提醒用户关闭 Excel,并且安装程序应该暂停,直到在进程列表中不再找到 Excel 实例。

回到代码,我不认为while 块是完全正确的,因为如果同时 Excel 仍在运行,它可能会在用户单击“重试”按钮后导致无限循环。

那么更好的方法是什么?有人可以看看上面的代码,看看我可以改进吗?

【问题讨论】:

  • 为什么excel不能运行?
  • 因为是Excel插件安装程序,我觉得安装插件的时候如果能有一个干净的环境就好了。
  • 这是有道理的。尽管这里的问题是您可能应该使用 excel 运行进行测试。毕竟,在您的预安装检查之后,没有什么可以阻止用户再次启动它。

标签: c# .net windows-installer


【解决方案1】:

我认为你的代码应该是这样的:

while(isExcelRunning())
{
    var result = MessageBox.Show("Excel is still running. Please save your work and close Excel, and then click \"Retry\" button to continue with installation.", "", MessageBoxButtons.RetryCancel, MessageBoxIcon.Warning);
    if (result != DialogResult.Retry)
    {
         //Handle Cancel
         break;
    }
}

这将继续循环显示警报,直到 Excel 退出,或者他们按下取消,在此您可以做任何您需要做的事情;然后我们退出循环(或者你可以完全退出方法)。

这里的关键是重复显示警报,直到 Excel 消失或他们选择取消。如果需要根据响应在循环后做一些代码;也许是这样的:

var userHasCancelled = false;
while(!userHasCancelled && isExcelRunning())
{
    var result = MessageBox.Show("Excel is still running. Please save your work and close Excel, and then click \"Retry\" button to continue with installation.", "", MessageBoxButtons.RetryCancel, MessageBoxIcon.Warning);
    if (result != DialogResult.Retry)
    {
         userHasCancelled = true;
    }
}
if (userHasCancelled)
{
    //User cancelled...
}
else
{
    //Continue.
}

【讨论】:

  • 非常感谢 vcsjones。我觉得你的回答很有帮助。
  • @vcjones 哦,只是一个快速的后续问题,如果用户选择“取消”,我是否想退出整个安装。我应该在这里做什么?我可以将值“取消”传递给安装程序吗?
  • @woodykiddy 我对制作安装程序知之甚少;但你应该提出另一个问题,其他人可能知道。