在 Powershell 中检查关闭 Windows 窗体的内容

aho*_*sek 2 forms powershell winforms

想知道是否有办法检查关闭窗口的事件,几乎可以单击顶角的红色 x或是否$form.Close()被调用?

$form.Add_Closing({})如果我的脚本中有它,每个都会自动启动,但我想知道关闭窗口的方式是什么。

mkl*_*nt0 5

FormClosing事件争论对象的.CloseReason属性不会让你的区分.Close()方法已经被称为形式和用户通过标题栏/窗口的系统菜单关闭窗体上/冲压Alt+F4-所有这些情况下同样导致.CloseReason物业反映枚举值UserClosing

但是,您可以通过检查调用堆栈中的方法调用来调整Reza Aghaei对这个主题的有用 C# 回答中的技术.Close()

using assembly System.Windows.Forms
using namespace System.Windows.Forms
using namespace System.Drawing

# Create a sample form.
$form = [Form] @{
    ClientSize      = [Point]::new(400,100)
    Text            = 'Closing Demo'
}    

# Create a button and add it to the form.
$form.Controls.AddRange(@(
    ($btnClose = [Button] @{
        Text              = 'Close'
        Location          = [Point]::new(160, 60)
    })
))

# Make the button call $form.Close() when clicked.
$btnClose.add_Click({
  $form.Close()
})

# The event handler called when the form is closing.
$form.add_Closing({
  # Look for a call to a `.Close()` method on the call stack.
  if ([System.Diagnostics.StackTrace]::new().GetFrames().GetMethod().Name -ccontains 'Close') {
    Write-Host 'Closed with .Close() method.'
  } else {
    Write-Host 'Closed via title bar / Alt+F4.'
  }
})

$null = $form.ShowDialog() # Show the form modally.
$form.Dispose()            # Dispose of the form.
Run Code Online (Sandbox Code Playgroud)

如果您运行此代码并尝试关闭表单的各种方法,则应打印一条指示所使用方法的消息(.Close()调用与标题栏 / Alt+F4)。

笔记:

  • 通过分配给没有显式调用的窗体.CancelButton.SubmitButton属性的按钮关闭窗体$form.Close()仍然会导致.Close()在幕后调用。

  • 该代码需要 PowerShell v5+,但它可以适应更早的版本。