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

社会主义新天地 提交于 2019-12-03 10:57:45
Don Fouts

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.

Dennis

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!