Is it possible to manage WMI events though space and main form?

I am trying to create a background worker that will scan for USB device changes.

I find it difficult to work with WMI audit events outside of the workspace. Basically, when I close the window (AKA form), I would like to cancel Wait-Event

. But I can't control this from the run side, so it gets stuck. Is it possible?

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

      

+2
powershell winforms


source to share


No one has answered this question yet

See similar questions:

1
PowerShell: Work in progress event action

or similar:

125
Centering controls on a form in .NET (Winforms)?
50
How do I create an event in Usercontrol and handle it in the main form?
20
Is it possible to reset a space in PowerShell ISE?
7
Winforms: first intercept mouse event on main form, not on controls
4
Event passing with multiple powershell scripts
2
MVC controller with Runspace impersonation
1
Is it possible to create a Powershell space delimited by a folder
0
Couldn't find event log using Runspaces in Powershell
0
event between main form and child control
-2
accessing "Main Form" controls using a component script attached to the main form



All Articles
Loading...
X
Show
Funny
Dev
Pics