Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/redis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Winforms 是否可以通过运行空间和主窗体控制WMI事件?_Winforms_Powershell - Fatal编程技术网

Winforms 是否可以通过运行空间和主窗体控制WMI事件?

Winforms 是否可以通过运行空间和主窗体控制WMI事件?,winforms,powershell,Winforms,Powershell,我正在尝试创建一个后台工作程序,它将扫描USB设备中的更改 我很难在运行空间之外控制WMI事件。 基本上,当我关闭窗口(也称为“表单”)时,我想取消等待事件。但我无法在运行空间外控制它,所以它卡住了。 可能吗 Add-Type -AssemblyName System.Windows.Forms Add-Type -AssemblyName System.Drawing $form1 = New-Object System.Windows.Forms.Form $form1.Text = "My

我正在尝试创建一个后台工作程序,它将扫描USB设备中的更改

我很难在运行空间之外控制WMI事件。 基本上,当我关闭窗口(也称为“表单”)时,我想取消
等待事件
。但我无法在运行空间外控制它,所以它卡住了。 可能吗

Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
$form1 = New-Object System.Windows.Forms.Form
$form1.Text = "My PowerShell Form"
$form1.Name = "form1"
$form1.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 1400
$System_Drawing_Size.Height = 600
$form1.ClientSize = $System_Drawing_Size

$Global:x = [Hashtable]::Synchronized(@{})
$x.Host = $Host
$x.Flag = $true

$rs = [RunspaceFactory]::CreateRunspace()
$rs.ApartmentState, $rs.ThreadOptions = "STA", "ReUseThread"
$rs.Open()
$rs.SessionStateProxy.SetVariable("x",$x)
$cmd = [PowerShell]::Create().AddScript({
    Register-WmiEvent -Class Win32_DeviceChangeEvent -SourceIdentifier volumeChange
    do {
        $retEvent = Wait-Event -SourceIdentifier volumeChange
        Remove-Event -SourceIdentifier volumeChange
    } while ($x.Flag) #Loop until next event

    Unregister-Event -SourceIdentifier volumeChange
})
$cmd.Runspace = $rs
$handle = $cmd.BeginInvoke()

$OnClosing = {
    $x.Flag = $false
    $x.Host.UI.WriteVerboseLine($x.Flag)

    $cmd.EndInvoke($handle)
}

$InitialFormWindowState = $form1.WindowState
#Init the OnLoad event to correct the initial state of the form
$form1.Add_Load($OnLoadForm_StateCorrection)
$form1.Add_Closing($OnClosing)
$form1.ShowDialog() | Out-Null
您可以使用
$cmd.Stop()
命令请求停止管道。AFAIK,
等待事件
正确响应管道停止请求。