首页 > 解决方案 > 如何在不停止进程的情况下正确关闭记事本++窗口?

问题描述

我想正确关闭记事本++的窗口,但它不起作用。请问有什么解决方案?

这是我的代码:

$pathcoalaclient="C:\Program Files\Notepad++\notepad++.exe"
    
     $process=Start-Process -FilePath  $pathcoalaclient -Verb RunAs -PassThru   
       Start-Sleep -s 5
        $process.CloseMainWindow()

这是我的输出:

True

标签: powershell

解决方案


  • 不幸的是,返回的事实并不能保证窗口实际关闭并且目标进程退出- 它只是告诉您.CloseMainWindow()$true请求关闭的 Windows 消息是否已成功发送

  • 实际上,在您的情况下,窗口不会关闭,因为您已Notpad++.exe提升的会话()中启动。看起来,大概与权限有关,然后是无效的。Start-Process-Verb RunAs.CloseMainWindow()

    • 但是,如果可以接受,考虑到数据丢失的风险- 您可以回退到以
      Stop-Process终止
      强制终止)该过程。

一个工作示例:

# Note: I'm using Notepad.exe for simplicity here.
$pathcoalaclient = "Notepad.exe"
    
$process = Start-Process -FilePath $pathcoalaclient -Verb RunAs -PassThru   
Start-Sleep -Seconds 5


# Call .CloseMainWindow() but note that return value $true
# isn't a reliable indicator for whether the window actually closed.
# NOTE: If you KNOW that the process was created WITH ELEVATION
#       - as in this case - you can skip this call altogether.
$requestSuccessfullySent = $process.CloseMainWindow()

if ($requestSuccessfullySent) {
  # The process may or may not exit.
  # Wait a reasonable amount of time to see if it does.
  # Note: If the request to close couldn't even be sent - this could be 
  #       due to application hanging, currently showing a *modal* dialog, 
  #       or being in the process of / already having exited - 
  #       there is no strict need to wait, although you still may choose to, 
  #       in order to minimize the risk of data loss.
  $process | Wait-Process -Timeout 3 -ErrorAction Ignore    
}

# Take additional action, if the process did *not* exit.
if (-not $process.HasExited) {
  Write-Warning "The $($process.Name) process did not exit on its own within the timeout period."
  # !! IF it is acceptable,
  # !! you can *kill* the process now, but note that this can 
  # !! result in *data loss*
  Write-Warning "Killing the $($process.Name) process..."
  $process | Stop-Process -Force
}

请注意,无条件终止,即它总是强制终止进程,有数据丢失的风险。至少在未来(PowerShell 7.2 后)可能提供优雅终止是GitHub 问题 #13664主题。Stop-Process


推荐阅读