检查什么在Powershell中关闭了Windows窗体 [英] Checking what closed your Windows Form in Powershell

查看:85
本文介绍了检查什么在Powershell中关闭了Windows窗体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想知道是否有一种方法可以检查哪个事件关闭了窗口,几乎可以单击顶部的红色x $ form.Close()被称为?

Was wondering if there is a way to check what event closed the window, pretty much either clicking the red x in the top corner or if $form.Close() was called?

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

Each will automatically initiate the $form.Add_Closing({}) if I have it in my script, but I wanted to know which way of closing the window did this.

推荐答案

.CloseReason 属性反映枚举值 UserClosing .

The FormClosing event argument object's .CloseReason property doesn't allow you to distinguish between the .Close() method having been called on the form and the user closing the form via the title bar / window system menu / pressing Alt+F4 - all these cases equally result in the .CloseReason property reflecting enumeration value UserClosing.

但是,您可以通过检查调用堆栈中的 Reza Aghaei关于该主题的有用的C#答案来采用该技术.调用 .Close()方法:

However, you can adapt the technique from Reza Aghaei's helpful C# answer on the subject, by inspecting the call stack for a call to a .Close() method:

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()调用与标题栏/ Alt + F4 ).

If you run this code and try various methods of closing the form, a message indicating the method used should print (.Close() call vs. title bar / Alt+F4).

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

Note that closing the form via buttons assigned to the form's .CancelButton and .SubmitButton properties that don't have explicit $form.Close() calls still causes .Close() to be called behind the scenes.

请注意,该代码需要PowerShell v5 +,但可以适应早期版本.

Note that the code requires PowerShell v5+, but it can be adapted to earlier versions.

这篇关于检查什么在Powershell中关闭了Windows窗体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆