forms - 在 Powershell 中检查是什么关闭了 Windows 窗体

标签 forms winforms powershell

想知道是否有一种方法可以检查是什么事件关闭了窗口,几乎可以点击右上角的红色 x 或者 $form.Close() 被调用了吗?

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

最佳答案

FormClosing event参数对象的 .CloseReason 属性不允许您区分在表单上调用的 .Close() 方法和用户通过标题栏关闭表单/窗口系统菜单/按 Alt+F4 - 所有这些情况同样导致 .CloseReason property反射(reflect)枚举值 UserClosing .

但是,您可以采用 Reza Aghaei's helpful C# answer 中的技术在这个问题上,通过检查调用堆栈以调用 .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.

如果您运行此代码并尝试各种关闭表单的方法,将显示一条指示所用方法的消息(.Close() call vs. title bar/Alt+F4).

注意:

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

  • 代码需要 PowerShell v5+,但可以适配到更早的版本。

关于forms - 在 Powershell 中检查是什么关闭了 Windows 窗体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59036628/

相关文章:

c# - 如何交换 NumericUpDown 控件上的箭头按钮功能?

powershell - 在文本文件中交换 last.first 到 first.last

javascript - 在php中使用ajax提交multipart/form-data为null

forms - 如何在 JSP 操作中设置文本字段值

c# - 筛选 TreeView 节点的最佳方式

powershell - Docker Run 命令挂起

powershell - 在 Azure AD 组中搜索多个字符串

javascript - 如何获取表单的 onSubmit 事件?

regex - HTML5 验证模式例如 : 13-124132424

c# - Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0 中存储了哪些文件?