PowerShell WPF UI detect key combination - wpf

I am writing a UI to run in WinPE. I have everything working so far and am trying to make it so the user cannot close the window. I have made it full screen and disabled the close (X) button, but the user can still press Alt+F4 to close the UI. I have been able to make it so that if the user hits F8 the UI is in front so the user cannot Alt+Tab to it. I have read so many ways to do this but nothing covers it for PowerShell I am not sure how to implement it in the script. It is not running in a Runspace.
Here is what I have tried:
$altF4Pressed = {
[System.Windows.Input.KeyEventArgs]$Alt = $args[1]
if ( ($Alt.Key -eq 'System') -or ($Alt.Key -eq 'F4') ) {
if ($_.CloseReason -eq 'UserClosing') {
$UI.Cancel = $true
}
}
}
$null = $UI.add_KeyDown($altF4Pressed)
I have also read to do this (Disabling Alt+F4 in a Powershell form), but this does not work.
#disable closing window using Alt+F4
$UI_KeyDown = [System.Windows.Forms.KeyEventHandler]{
#Event Argument: $_ = [System.Windows.Forms.KeyEventArgs]
if ($_.Alt -eq $true -and $_.KeyCode -eq 'F4') {
$script:altF4Pressed = $true;
}
}
$UI_Closing = [System.Windows.Forms.FormClosingEventHandler]{
#Event Argument: $_ = [System.Windows.Forms.FormClosingEventArgs]
if ($script:altF4Pressed)
{
if ($_.CloseReason -eq 'UserClosing') {
$_.Cancel = $true
$script:altF4Pressed = $false;
}
}
Else{
[System.Windows.Forms.Application]::Exit();
# Stop-Process $pid
}
}
$UI.Add_Closing({$UI_Closing})
$UI.add_KeyDown({$UI_KeyDown})
I have also tried to do this:
$UI.Add_KeyDown({
$key = $_.Key
If ([System.Windows.Input.Keyboard]::IsKeyDown("RightAlt") -OR [System.Windows.Input.Keyboard]::IsKeyDown("LeftAlt")) {
Switch ($Key) {
"F4" {
$script:altF4Pressed = $true;
write-host "Alt+f4 was pressed"
}
}
}
})
It detects the first keyboard press, but not the next one while the other is pressed. I think I need to use a Keybinding event instead, just not sure how to implement that in Powershell at the App level (not input level). I read you can add a keybinding to XAML code itself, but how do that with Powershell to detect the key combination (Alt+F4) when the UI presents itself?

You don't have a replicate-able example and I don't want to write one just for this, but I think this may be of assistance.
$altF4Pressed = {
[System.Windows.Input.KeyEventArgs]$Alt = $args[1]
if ( ($Alt.Key -eq 'System') -or ($Alt.Key -eq 'F4') ) {
if ($_.CloseReason -eq 'UserClosing') {
$UI.Cancel = $true
$Alt.Handled = $true
}
}
}
$null = $UI.add_KeyDown([System.Windows.Input.KeyEventHandler]::new($altF4Pressed))
Also IIRC for WPF, you'll want to use System.Windows.Input not System.Windows.Forms, so the second snippet you posted may actually work if you change the namespace.

I found the detection of keys with forms or WPF to be well above my skill level. However, I was able to accomplish the same task with a different approach. I needed to do this with an install script in Windows 10.
What I did was disable both left/right alt keys and F4 during the time the script was running and revert the changes, delete the key, after completed.
With WinPE's registry getting "reset" on each reboot it's your call if you want to diable the change after you make it.
# Disable Left & Right ALT keys and F4
Set-ItemProperty -path "HKLM:\SYSTEM\CurrentControlSet\Control\Keyboard Layout" -name "Scancode Map" -Value ([byte[]](0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x3e,0x00,0x00,0x00,0x38,0x00,0x00,0x00,0x38,0xe0,0x00,0x00,0x00,0x00))
To re-enable Alt + F4 simply delete the "Scancode Map" registry value and reboot again.
I found the answer here: http://www.edugeek.net/forums/windows-server-2008-r2/121900-disable-alt-f4.html

Related

Powershell GUI Freezing, even with runspace

I am creating a powershell script with a GUI, that copies user profiles from a selected source disk to a destination disk. I've created the GUI in XAML, with VS Community 2019.
The script works like this : you select the source disk, the destination disk, the user profile and the folders you want to copy. When you press the button "Start", it calls a function called Backup_data, where a runspace is created. In this runspace, there's just a litte Copy-Item, with as arguments what you've selected.
The script works fine, all the wanted items are correctly copied. The problem is that the GUI is freezing during the copy (no "not responding" message or whatever, it's just completly freezed ; can't click anywhere, can't move the window). I've seen that using runspaces would fix this problem, but it doesn't to me. Am I missing something ?
Here's the function Backup_Data:
Function BackupData {
##CREATE RUNSPACE
$PowerShell = [powershell]::Create()
[void]$PowerShell.AddScript( {
Param ($global:ReturnedDiskSource, $global:SelectedUser, $global:SelectedFolders, $global:ReturnedDiskDestination)
##SCRIPT BLOCK
foreach ($item in $global:SelectedFolders) {
Copy-Item -Path "$global:ReturnedDiskSource\Users\$global:SelectedUser\$item" -Destination "$global:ReturnedDiskDestination\Users\$global:SelectedUser\$item" -Force -Recurse
}
}).AddArgument($global:ReturnedDiskSource).AddArgument($global:SelectedUser).AddArgument($global:SelectedFolders).AddArgument($global:ReturnedDiskDestination)
#Invoke the command
$PowerShell.Invoke()
$PowerShell.Dispose()
}
The PowerShell SDK's PowerShell.Invoke() method is synchronous and therefore by design blocks while the script in the other runspace (thread) runs.
You must use the asynchronous PowerShell.BeginInvoke() method instead.
Simple example without WPF in the picture (see the bottom section for a WPF solution):
$ps = [powershell]::Create()
# Add the script and invoke it *asynchronously*
$asyncResult = $ps.AddScript({ Start-Sleep 3; 'done' }).BeginInvoke()
# Wait in a loop and check periodically if the script has completed.
Write-Host -NoNewline 'Doing other things..'
while (-not $asyncResult.IsCompleted) {
Write-Host -NoNewline .
Start-Sleep 1
}
Write-Host
# Get the script's success output.
"result: " + $ps.EndInvoke($asyncResult)
$ps.Dispose()
Note that there's a simpler alternative to using the PowerShell SDK: the ThreadJob module's Start-ThreadJob cmdlet, a thread-based alternative to the child-process-based regular background jobs started with Start-Job, that is compatible with all the other *-Job cmdlets.
Start-ThreadJob comes with PowerShell [Core] 7+, and can be installed from the PowerShell Gallery in Windows PowerShell (Install-Module ThreadJob).
# Requires module ThreadJob (preinstalled in v6+)
# Start the thread job, always asynchronously.
$threadJob = Start-ThreadJob { Start-Sleep 3; 'done' }
# Wait in a loop and check periodically if the job has terminated.
Write-Host -NoNewline 'Doing other things..'
while ($threadJob.State -notin 'Completed', 'Failed') {
Write-Host -NoNewline .
Start-Sleep 1
}
Write-Host
# Get the job's success output.
"result: " + ($threadJob | Receive-Job -Wait -AutoRemoveJob)
Complete example with WPF:
If, as in your case, the code needs to run from an event handler attached to a control in a WPF window, more work is needed, because Start-Sleep can not be used, since it blocks processing of GUI events and therefore freezes the window.
Unlike WinForms, which has a built-in method for processing pending GUI events on demand ([System.Windows.Forms.Application]::DoEvents(), WPF has no equivalent method, but it can be added manually, as shown in the DispatcherFrame documentation.
The following example:
Creates a window with two background-operation-launching buttons and corresponding status text boxes.
Uses the button-click event handlers to launch the background operations via Start-ThreadJob:
Note: Start-Job would work too, but that would run the code in a child process rather than a thread, which is much slower and has other important ramifications.
It also wouldn't be hard to adapt the example to use of the PowerShell SDK ([powershell]), but thread jobs are more PowerShell-idiomatic and are easier to manage, via the regular *-Job cmdlets.
Displays the WPF window non-modally and enters a custom event loop:
A custom DoEvents()-like function, DoWpfEvents, adapted from the DispatcherFrame documentation is called in each loop operation for GUI event processing.
Note: For WinForms code, you could simply call [System.Windows.Forms.Application]::DoEvents().
Additionally, the progress of the background thread jobs is monitored and output received is appended to the job-specific status text box. Completed jobs are cleaned up.
Note: Just as it would if you invoked the window modally (with .ShowModal()), the foreground thread and therefore the console session is blocked while the window is being displayed. The simplest way to avoid this is to run the code in a hidden child process instead; assuming that the code is in script wpfDemo.ps1:
# In PowerShell [Core] 7+, use `pwsh` instead of `powershell`
Start-Process -WindowStyle Hidden powershell '-noprofile -file wpfDemo.ps1'
You could also do this via the SDK, which would be faster, but it's much more verbose and cumbersome:
$runspace = [runspacefactory]::CreateRunspace() $runspace.ApartmentState = 'STA'; $runspace.Open(); $ps = [powershell]::Create(); $ps.Runspace = $runspace; $null = $ps.AddScript((Get-Content -Raw wpfDemo.ps1)).BeginInvoke()
Screenshot:
This sample screen shot shows one completed background operation, and one ongoing one (running them in parallel is supported); note how the button that launched the ongoing operation is disabled for the duration of the operation, to prevent re-entry:
Source code:
using namespace System.Windows
using namespace System.Windows.Threading
# Load WPF assemblies.
Add-Type -AssemblyName PresentationCore, PresentationFramework
# Define the XAML document, containing a pair of background-operation-launching
# buttons plus associated status text boxes.
[xml] $xaml = #"
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Test"
Title="MainWindow" Height="220" Width="600">
<Grid>
<TextBox x:Name="Status1" Height="140" Width="280" Margin="10,10" TextWrapping="Wrap" VerticalAlignment="Top" HorizontalAlignment="Left" AcceptsReturn="True" AcceptsTab="True" Padding="4" VerticalScrollBarVisibility="Auto" />
<TextBox x:Name="Status2" Height="140" Width="280" Margin="10,10" TextWrapping="Wrap" VerticalAlignment="Top" HorizontalAlignment="Right" AcceptsReturn="True" AcceptsTab="True" Padding="4" VerticalScrollBarVisibility="Auto" />
<Button x:Name="DoThing1" Content="Do Thing 1" HorizontalAlignment="Left" VerticalAlignment="Bottom" Width="100" Height="22" Margin="10,5" IsDefault="True" />
<Button x:Name="DoThing2" Content="Do Thing 2" HorizontalAlignment="Right" VerticalAlignment="Bottom" Width="100" Height="22" Margin="10,5" />
</Grid>
</Window>
"#
# Parse the XAML, which returns a [System.Windows.Window] instance.
$Window = [Markup.XamlReader]::Load((New-Object System.Xml.XmlNodeReader $xaml))
# Save the window's relevant controls in PowerShell variables.
# Background-operation-launching buttons.
$btns = $Window.FindName('DoThing1'), $Window.FindName('DoThing2')
# Use a [hashtable] to map the buttons to the associated status text boxes.
$txtBoxes = #{
$btns[0] = $Window.FindName('Status1')
$btns[1] = $Window.FindName('Status2')
}
# Use a [hashtable] to map the buttons to the associated background
# operations, defined as script blocks to be passed to Start-ThreadJob later.
# The sample operations here run for a few seconds,
# emitting '.' every second and a message on completion.
$scriptBlocks = #{
$btns[0] =
{
1..3 | ForEach-Object { '.'; Start-Sleep 1 }
'Thing 1 is done.'
}
$btns[1] =
{
1..2 | ForEach-Object { '.'; Start-Sleep 1 }
'Thing 2 is done.'
}
}
# Attach the button-click event handlers that
# launch the background operations (thread jobs).
foreach ($btn in $btns) {
$btn.Add_Click({
# Temporarily disable this button to prevent re-entry.
$this.IsEnabled = $false
# Show a status message in the associated text box.
$txtBoxes[$this].Text = "Started thing $($this.Name -replace '\D') at $(Get-Date -Format T)."
# Asynchronously start a background thread job named for this button.
# Note: Would work with Start-Job too, but that runs the code in *child process*,
# which is much slower and has other implications.
$null = Start-ThreadJob -Name $this.Name $scriptBlocks[$this]
})
}
# Define a custom DoEvents()-like function that processes GUI WPF events and can be
# called in a custom event loop in the foreground thread.
# Adapted from: https://learn.microsoft.com/en-us/dotnet/api/system.windows.threading.dispatcherframe
function DoWpfEvents {
[DispatcherFrame] $frame = [DispatcherFrame]::new($True)
$null = [Dispatcher]::CurrentDispatcher.BeginInvoke(
'Background',
[DispatcherOperationCallback] {
param([object] $f)
($f -as [DispatcherFrame]).Continue = $false
return $null
},
$frame)
[Dispatcher]::PushFrame($frame)
}
# Finally, display the window NON-modally...
$Window.Show()
$null = $Windows.Activate() # Ensures that the window gets the focus.
# ... and enter a custom event loop based on calling the custom .DoEvents() method
while ($Window.IsVisible) {
# Process GUI events.
DoWpfEvents
# Process pending background (thread) jobs, if any.
Get-Job | ForEach-Object {
# Get the originating button via the job name.
$btn = $Window.FindName($_.Name)
# Get the corresponding status text box.
$txtBox = $txtBoxes[$btn]
# Test if the job has terminated.
$completed = $_.State -in 'Completed', 'Failed', 'Stopped'
# Append any new results to the respective status text boxes.
# Note the use of redirection *>&1 to capture ALL streams, notably including the error stream.
if ($data = Receive-Job $_ *>&1) {
$txtBox.Text += "`n" + ($data -join "`n")
}
# Clean up, if the job is completed.
if ($completed) {
Remove-Job $_
$btn.IsEnabled = $true # re-enable the button.
$txtBox.Text += "`nJob terminated on: $(Get-Date -Format T); status: $($_.State)."
}
}
# Note: If there are no GUI events pending, this loop will cycle very rapidly.
# To mitigate this, we *also* sleep a little, but short enough to still keep
# the GUI responsive.
Start-Sleep -Milliseconds 50
}
# Window was closed; clean up:
# If the window was closed before all jobs completed,
# get the incomplete jobs' remaining output, wait for them to finish, and delete them.
Get-Job | Receive-Job -Wait -AutoRemoveJob
I've been searching for a solution all day and I've finally found one, so I'm gonna post it there for those who have the same problem.
First, check this article : https://smsagent.blog/2015/09/07/powershell-tip-utilizing-runspaces-for-responsive-wpf-gui-applications/
It's well explained and shows you how to correctly use runspaces with a WPF GUI. You just have to replace your $Window variable by $Synchhash.Window :
$syncHash = [hashtable]::Synchronized(#{})
$reader = (New-Object System.Xml.XmlNodeReader $xaml)
$syncHash.window = [Windows.Markup.XamlReader]::Load( $reader )
Insert a runspace function with your code :
function RunspaceBackupData {
$Runspace = [runspacefactory]::CreateRunspace()
$Runspace.ApartmentState = "STA"
$Runspace.ThreadOptions = "ReuseThread"
$Runspace.Open()
$Runspace.SessionStateProxy.SetVariable("syncHash",$syncHash)
$Runspace.SessionStateProxy.SetVariable("SelectedFolders",$global:SelectedFolders)
$Runspace.SessionStateProxy.SetVariable("SelectedUser",$global:SelectedUser)
$Runspace.SessionStateProxy.SetVariable("ReturnedDiskSource",$global:ReturnedDiskSource)
$Runspace.SessionStateProxy.SetVariable("ReturnedDiskDestination",$global:ReturnedDiskDestination)
$code = {
foreach ($item in $global:SelectedFolders) {
copy-item -Path "$global:ReturnedDiskSource\Users\$global:SelectedUser\$item" -Destination "$global:ReturnedDiskDestination\Users\$global:SelectedUser\$item" -Force -Recurse
}
}
$PSinstance = [powershell]::Create().AddScript($Code)
$PSinstance.Runspace = $Runspace
$job = $PSinstance.BeginInvoke()
}
And call it in the event-handler you want with the parameters you've indicated :
$var_btnStart.Add_Click( {
RunspaceBackupData -syncHash $syncHash -SelectedFolders $global:SelectedFolders -SelectedUser $global:SelectedUser -ReturnedDiskSource $global:ReturnedDiskSource -ReturnedDiskDestination $global:ReturnedDiskDestination
})
Don't forget to end your runspace :
$syncHash.window.ShowDialog()
$Runspace.Close()
$Runspace.Dispose()

Powershell -notin array won't trigger if statement

I've recently begun to create a powershell script including a GUI.
To prevent the GUI from freezing I've created a background job in which my function "xyz" runs...
I want to capture a specific window title. If this window closes the if should be fired.
Now my problem with this script is the following:
If I run the script without putting it in the background job it does notice the if statement and returns the value I want to have.
If I run the script and put the task into the background job this job won't stop and won't recognize the if statement.
Does someone have a solution for this problem?
Function xyz {
$global:TitleArray = #("Termius - Hosts","Some Window Title","...")
$global:WindowClosed = $false
$global:TitleArray | Out-Host
$global:Job = start-job -Name FindGame {
Do {
(Get-Process | Where-Object {$_.MainWindowTitle -ne ""} | Select-Object MainWindowTitle) | % {
if($_.MainWindowTitle -in $global:TitleArray){
$global:WindowFound = $true
$global:FoundWindowName = $_.MainWindowTitle
do {
$WindowArray = #()
(Get-Process | Where-Object {$_.MainWindowTitle -ne ""} | Select-Object MainWindowTitle) | % {
$WindowArray += $_.MainWindowTitle
}
if($global:FoundWindowName -notin $WindowArray){
$global:WindowClosed = $true
}
Sleep 1
} while ($global:WindowClosed -ne $true)
}
if($global:WindowClosed){
$Global:FoundWindowName | Out-Host
exit
}
Sleep 1
}
} while ($true)
}
}
xyz
PowerShell jobs (of type PSJob) run in a separate process, so they have no access whatsoever to your calling program's environment, not even variables in the Global scope.
To get information into the job, you should define a param() block in the job's script block, and then use the -ArgumentList parameter of Start-Job to send in values. Do note that this will be a one time passing in of values.
To return data from the job, you just send it out through the pipeline as usual, and to access the data you'll need to use Get-Job to determine whether the job "has additional data", and if it does, you use Receive-Job to retrieve that data.
Unfortunately all this means that you still need your main thread to be managing the background job, defeating the purpose.
You might look into Register-ObjectEvent instead, and pair that with some kind of .Net object that can raise events. It appears that these do run in-process, but more than that, they can fire based on events you might actually be interested in without managing a loop.
So at its simplest, and maybe just to get acquainted you can look at a timer example where a timer object fires the event on an interval:
$timer = new-object timers.timer
$action = {write-host "Timer Elapse Event: $(get-date -Format ‘HH:mm:ss’)"}
$timer.Interval = 3000 #3 seconds
Register-ObjectEvent -InputObject $timer -EventName elapsed –SourceIdentifier thetimer -Action $action
$timer.start()
#to stop run
$timer.stop()
#cleanup
Unregister-Event thetimer
But the examples on the Microsoft page even include monitoring a Process Creation Event from WMI, so that and/or and process exit event(?) might be worth looking into.

Using Windows Forms Locks up PowerShell ISE minutes after script has terminated

I have an interesting issue here. I'm creating a calendar picker for use when we create accounts. It works fine and is still in progress but I have noticed that when I run the script in powershell ISE, after a few minutes it locks up (I am able to edit and save the code for a few minutes prior to that). There is nothing in the event log. I get a dialog box saying that powershell is non responsive. Memory usage seems normal as well. I do not know what is happening.
This occurs no matter how I run Powershell ISE (Run as Administrator, Run as another account, and normal ISE) I am running windows 8.1.
A coworker suggested it may be the apartment model, so I've tried STA and MTA, but the problem occurs either way. It does not happen when the same code is run from the console host.
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
$objForm = New-Object Windows.Forms.Form
$objForm.Text = "Select a Date"
$objForm.Size = New-Object Drawing.Size #(490,250)
$objForm.StartPosition = "CenterScreen"
$objForm.KeyPreview = $True
$objForm.Add_KeyDown({
if ($_.KeyCode -eq "Enter")
{
$script:dtmDate=$objCalendar.SelectionStart
$objForm.Close()
}
})
$objForm.Add_KeyDown({
if ($_.KeyCode -eq "Escape")
{
$objForm.Close()
}
})
$objCalendar = New-Object System.Windows.Forms.MonthCalendar
$objCalendar.Text = "Start"
$objCalendar.ShowTodayCircle = $False
$objCalendar.MaxSelectionCount = 1
$objForm.Controls.Add($objCalendar)
$objForm.Topmost = $True
$objForm.Add_Shown({$objForm.Activate()})
[void] $objForm.ShowDialog()
if ($dtmDate)
{
Write-Host "Date selected: $dtmDate"
}
$objForm.Dispose()
In Response to #The Unique Paul Smith
function Find-CalenderDateTest {
[CmdletBinding()]
param(
[Parameter(
Mandatory=$false
)]
[ValidateSet('long','short','powerpoint')]
[ValidateNotNullOrEmpty()]
[string]
$DateFormat
)
Begin{
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
$objForm = New-Object Windows.Forms.Form
$objForm.Text = "Select a Date"
$objForm.Size = New-Object Drawing.Size #(243,250)
$objForm.StartPosition = "CenterScreen"
$objForm.KeyPreview = $True
$dtmDate = $null
$objForm.Add_KeyDown( {
if ($_.KeyCode -eq "Enter")
{
$dtmDate=$objCalendar.SelectionStart
$objForm.Close()
}
})
$objForm.Add_KeyDown({
if ($_.KeyCode -eq "Escape")
{
$objForm.Close()
}
})
#region OK Button
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Size(20,175)
$OKButton.Size = New-Object System.Drawing.Size(75,23)
$OKButton.Text = "OK"
# Got rid of the Click event for OK Button, and instead just assigned its DialogResult property to OK.
$OKButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$objForm.Controls.Add($OKButton)
# Setting the form's AcceptButton property causes it to automatically intercept the Enter keystroke and
# treat it as clicking the OK button (without having to write your own KeyDown events).
$objForm.AcceptButton = $OKButton
#endregion
#region Cancel Button
$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Size(80,175)
$CancelButton.Size = New-Object System.Drawing.Size(75,23)
$CancelButton.Text = "Cancel"
# Got rid of the Click event for Cancel Button, and instead just assigned its DialogResult property to Cancel.
$CancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$objForm.Controls.Add($CancelButton)
# Setting the form's CancelButton property causes it to automatically intercept the Escape keystroke and
# treat it as clicking the OK button (without having to write your own KeyDown events).
$objForm.CancelButton = $CancelButton
#endregion
$objCalendar = New-Object System.Windows.Forms.MonthCalendar
$objCalendar.ShowTodayCircle = $False
$objCalendar.MaxSelectionCount = 1
$objForm.Controls.Add($objCalendar)
$objForm.Topmost = $True
$objForm.Add_Shown({$objForm.Activate()})
$Results = $objForm.ShowDialog()
}
Process{}
End{
if ($Results -eq "OK")
{
$objCalendar.SelectionStart
}
$objForm.Dispose()
}
}
The error is MTA/STA
Don't use
$form.showDialog()
Use
[system.windows.forms.application]::run($form)
instead
and it works fine every time
Another way is to put it in another thread:
$code
{
//form code here
$form.showDialog()
}
$newThread = [Powershell]::Create()
$newThread.AddScript($code)
$handle = $newThread.BeginInvoke()
Provide variables from the calling script:
$newThread.Runspace.SessionStateProxy.SetVariable("variablenname",value)
before the BeginInvoke use variablenname without $...
It's a long shot but the problem might be that powershell is not closing the $objForm object correctly, leaving it running in memory while the ISE waits for input after the script has terminated. If you check your taskmanager, is the form still running in the background? You could also try adding 'Remove-Variable objForm' (no $) after the dispose() and see if that helps.
More information: https://technet.microsoft.com/en-us/library/ff730962.aspx
As I say, it's a long shot.
I was using combobox.items.add:
$configCombo.Items.Add($wks)
and I looked up how to keep the keys from printing to the console - and changed the add to:
[void]$configCombo.Items.Add($wks)
Since then I have added the void - I have been running it in ISE and it has not hung since.
Ran into this issue too. Generally occurs when I lock my workstation and return. After a bit of poking about and googleing, I found this
https://support.microsoft.com/en-us/help/943139/windows-forms-application-freezes-when-system-settings-are-changed-or, which seems like the issue at hand.
Issue
The application will not respond and the UI thread will hang in an
Invoke call while handling the OnUserPreferenceChanged notification
Cause
This occurs if a control is created on a thread which doesn't pump
messages and the UI thread receives a WM_SETTINGCHANGE message.
Resolution
Applications should never leave Control objects on threads without an
active message pump. If Controls cannot be created on the main UI
thread, they should be created on a dedicated secondary UI thread and
Disposed as soon as they are no longer needed.
I had the same issue, but the solution is: Always clean up right after the form is done.
In this case:
$objForm.Dispose()
Up to now (a few hours) I didn't have that issue again. Previously it locked up after > 10 Minutes.

Is there a way to send events to the parent job when using Start-WPFJob?

I would like to launch a non-blocking UI from a parent Powershell script and receive UI messages like button clicks from the child job. I have this kind of messaging working using WinForms, but I prefer to use ShowUI because of how much less code it takes to create a basic UI. Unfortunately, though, I haven't found a way to send messages back to the parent job using ShowUI.
[Works] Forwarding Events When Using Start-Job
Using Start-Job, forwarding events from a child to a parent job is rather straightforward. Here is an example:
$pj = Start-Job -Name "PlainJob" -ScriptBlock {
Register-EngineEvent -SourceIdentifier PlainJobEvent -Forward
New-Event -SourceIdentifier PlainJobEvent -MessageData 'My Message'
}
Wait-Event | select SourceIdentifier, MessageData | Format-List
As expected, it prints out:
SourceIdentifier : PlainJobEvent
MessageData : My Message
[Does Not Work] Forwarding Events When Using Start-WPFJob
Using Start-WPFJob, on the other hand, does not seem to forward events from the child to the parent. Consider this example:
Import-Module ShowUI
$wj = Start-WPFJob -ScriptBlock {
Register-EngineEvent -SourceIdentifier MySource -Forward
New-Button "Button" -On_Click {
New-Event -SourceIdentifier MySource -MessageData 'MyMessage'
}
}
Wait-Event | select SourceIdentifier, MessageData | Format-List
Running this example produces this window:
Clicking on the button, however, does not yield an event in the parent job.
Why doesn't the Start-WPFJob example yield events to the parent job?
Is there some other way to use ShowUI to produce a button in a non-blocking manner and receive events from it?
I can't get engineevents to forward properly so far (actually, I can't even get them to do anything, as far as I can tell), I think your best bet is to run the WPFJob, and instead of New-Event, update the $Window UIValue, and then from your main runspace, instead of Wait-Event, use Update-WPFJob in a loop.
I would stick this function into the module (actually, I will add it for the 1.5 release that's in source control but not released yet):
function Add-UIValue {
param(
[Parameter(ValueFromPipeline=$true)]
[Windows.FrameworkElement]
$Ui,
[PSObject]
$Value
)
process {
if ($psBoundParameters.ContainsKey('Value')) {
Set-UIValue $UI (#(Get-UIValue $UI -IgnoreChildControls) + #($Value))
} else {
Set-UIValue -Ui $ui
}
}
}
And then, something like this:
$job = Start-WPFJob {
Window {
Grid -Rows "1*", "Auto" {
New-ListBox -Row 0 -Name LB -Items (Get-ChildItem ~ -dir)
Button "Send" -Row 1 -On_Click { Add-UIValue $Window $LB.SelectedItem }
}
} -SizeToContent "Width" -MinHeight 800
}
Every time you click, would add the selected item to the UI output (if you run that window without the job and click the button a couple of times, then close the window, you'll get two outputs).
Then you can do something like this in the host instead of Wait-Event:
do {
Update-WPFJob -Job $job -Command { Get-UIValue $Window -IgnoreChildControls } -OutVariable Output
Start-Sleep -Mil 300
} while (!$Output)

PowerShell: Job Event Action with Form not executed

If I run the following code, the Event Action is executed:
$Job = Start-Job {'abc'}
Register-ObjectEvent -InputObject $Job -EventName StateChanged `
-Action {
Start-Sleep -Seconds 1
Write-Host '*Event-Action*'
}
The string 'Event-Action' is displayed.
If I use a Form and start the above code by clicking a button,
the Event Action is not executed:
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$Form1 = New-Object Windows.Forms.Form
$Form1.Add_Shown({
$Form1.Activate()
})
$Button1 = New-Object System.Windows.Forms.Button
$Button1.Text = 'Test'
$Form1.Controls.Add($Button1)
$Button1.Add_Click({
Write-Host 'Test-Button was clicked'
$Job = Start-Job {'abc'}
Register-ObjectEvent -InputObject $Job -EventName StateChanged `
-Action {
Start-Sleep -Seconds 1
Write-Host '*Event-Action*'
}
})
$Form1.ShowDialog()
Only when I click the button again, the first Event Action is executed.
With the third click the second Event Action is executed and so on.
If I do multiple clicks in rapid succession, the result is unpredictable.
Furthermore when I close the form with the button in the upper right corner,
the last "open" Event Action is executed.
Note: For testing PowerShell ISE is to be preferred, because PS Console displays
the string only under certain circumstances.
Can someone please give me a clue what's going on here?
Thanks in advance!
nimizen.
Thanks for your explanation, but I don't really understand, why the StateChanged event is not fired or visible to the main script until there is some action with the Form. I'd appreciate another attempt to explain it to me.
What I want to accomplish is a kind of multithreading with PowerShell and Forms.
My plan is the following:
'
The script shows a Form to the user.
The user does some input and clicks a button.
Based on the user's input a set of Jobs are started with Start-Job and a StateChanged event is registered for each job.
While the Jobs are running, the user can perform any action on the Form (including stop the Jobs via a button) and the Form is repainted when necessary.
The script reacts to any events which are fired by the Form or its child controls.
Also the script reacts to each job's StateChanged event.
When a StateChanged event occurs, the state of each job is inspected, and if all jobs have the state 'Completed', the jobs' results are fetched with Receive-Job and displayed to the user.
'
All this works fine except that the StateChanged event is not visible to the main script.
The above is still my favorite solution and if you have any idea how to implement this, please let me know.
Otherwise I'll most likely resort to a workaround, which at least gives the user a multithreading feeling. It is illustrated in the following example:
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$Form1 = New-Object Windows.Forms.Form
$Form1.Add_Shown({
$Form1.Activate()
})
$Button1 = New-Object System.Windows.Forms.Button
$Button1.Text = 'Test'
$Form1.Controls.Add($Button1)
$Button1.Add_Click({
$Form1.Focus()
Write-Host 'Test-Button was clicked'
$Job = Start-Job {Start-Sleep -Seconds 1; 'abc'}
Do {
Start-Sleep -Milliseconds 100
Write-Host 'JobState: ' $Job.State
[System.Windows.Forms.Application]::DoEvents()
}
Until ($Job.State -eq 'Completed')
Write-Host '*Action*'
})
$Form1.ShowDialog()
There are a lot of (StackOverflow) questions and answers about this ‘enduring mystique’ of combining form (or WPF) events with .NET events (like EngineEvents, ObjectEvents and WmiEvents) in PowerShell:
Do Jobs really work in background in powershell?
WPF events not working in Powershell - Carousel like feature in multi-threaded script
is it possible to control WMI events though runspace and the main form?
Is there a way to send events to the parent job when using Start-WPFJob?
Update WPF DataGrid ItemSource from Another Thread in PowerShell
They are all come down two one point: even there are multiple threads setup, there are two different 'listeners' in one thread. When your script is ready to receive form events (using ShowDialog or DoEvents) it can’t listen to .NET events at the same time. And visa versa: if script is open for .NET events while processing commands (like Start-Sleep or specifically listen for .NET events using commands like Wait-Event or Wait-Job), your form will not be able to listen to form events. Meaning that either the .NET events or the form events are being queued simply because your form is in the same thread as the .NET listener(s) your trying to create.
As with the nimizen example, with looks to be correct at the first glans, your form will be irresponsive to all other form events (button clicks) at the moment you’re checking the backgroundworker’s state and you have to click the button over and over again to find out whether it is still ‘*Doing Stuff’. To work around this, you might consider to combine the DoEvents method in a loop while you continuously checking the backgroundworker’s state but that doesn’t look to be a good way either, see: Use of Application.DoEvents()
So the only way out (I see) is to have one thread to trigger the form in the other thread which I think can only be done with using [runspacefactory]::CreateRunspace() as it is able to synchronize a form control between the treats and with that directly trigger a form event (as e.g. TextChanged).
(if there in another way, I eager to learn how and see a working example.)
Form example:
Function Start-Worker {
$SyncHash = [hashtable]::Synchronized(#{TextBox = $TextBox})
$Runspace = [runspacefactory]::CreateRunspace()
$Runspace.ThreadOptions = "UseNewThread" # Also Consider: ReuseThread
$Runspace.Open()
$Runspace.SessionStateProxy.SetVariable("SyncHash", $SyncHash)
$Worker = [PowerShell]::Create().AddScript({
$ThreadID = [appdomain]::GetCurrentThreadId()
$SyncHash.TextBox.Text = "Thread $ThreadID has started"
for($Progress = 0; $Progress -le 100; $Progress += 10) {
$SyncHash.TextBox.Text = "Thread $ThreadID at $Progress%"
Start-Sleep 1 # Some background work
}
$SyncHash.TextBox.Text = "Thread $ThreadID has finnished"
})
$Worker.Runspace = $Runspace
$Worker.BeginInvoke()
}
[Void][System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$Form = New-Object Windows.Forms.Form
$TextBox = New-Object Windows.Forms.TextBox
$TextBox.Visible = $False
$TextBox.Add_TextChanged({Write-Host $TextBox.Text})
$Form.Controls.Add($TextBox)
$Button = New-Object System.Windows.Forms.Button
$Button.Text = "Start worker"
$Button.Add_Click({Start-Worker})
$Form.Controls.Add($Button)
$Form.ShowDialog()
For a WPF example, see: Write PowerShell Output (as it happens) to WPF UI Control
The state property of Powershell jobs is read-only; this means that you can't configure the job state to be anything before you actually start the job. When you're monitoring for the statechanged event, it doesn't fire until the click event comes around again and the state is 'seen' to change from 'running' to 'completed' at which point your script block executes. This is also the reason why the scriptblock executes when closing the form.
The following script removes the need to monitor the event and instead monitors the state. I assume you want to fire the on 'statechanged' code when the state is 'running'.
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$Form1 = New-Object Windows.Forms.Form
$Form1.Add_Shown({
$Form1.Activate()
})
$Button1 = New-Object System.Windows.Forms.Button
$Button1.Text = 'Test'
$Form1.Controls.Add($Button1)
$Button1.Add_Click({
$this.Enabled = $false
Write-Host $Job.State " - (Before job started)"
$Job = Start-Job {'abc'}
Write-Host $Job.State " - (After job started)"
If ($Job.State -eq 'Running') {
Start-Sleep -Seconds 1
Write-Host '*Doing Stuff*'
}
Write-Host $Job.State " - (After IF scriptblock finished)"
[System.Windows.Forms.Application]::DoEvents()
$this.Enabled = $true
})
$Form1.ShowDialog()
In addition, note the lines:
$this.Enabled = $false
[System.Windows.Forms.Application]::DoEvents()
$this.Enabled = $true
These lines ensure the button doesn't queue click events. You can obviously remove the 'write-host' lines, I've left those in so you can see how the state changes as the script executes.
Hope this helps.

Resources