Is there a way to programmatically install ApartmentState in STA?

I am working on a GUI in PowerShell, where I threw errors when I clicked certain combo boxes.

After the error has been reset, I can delete the combobox list and see its contents, but if I moved to another combox on the same datagridview, I would get the same initial error before I could see the drop-down list.

I posted this on the TechNet PowerShell forums and got the answer that I needed to run my GUI in a single-threaded apartment (STA). PowerShell works by default in MTA, but you can overwrite it (in version 2.0) with the -STA switch when invoking powershell.exe .

However, my GUI just calls the default PowerShell application (in MTA mode) , so my question is: is there a way to programmatically set the apartment property from my GUI / script?

If not, my next attempt would be to detect the state of the apartment and try to restart my GUI from the initial boot of my gi with something like:

 powershell.exe -STA myguiprog.ps1 

Edit:

So my solution works:

 if ([threading.thread]::CurrentThread.GetApartmentState() -eq "MTA") { & $env:SystemRoot\system32\WindowsPowerShell\v1.0\powershell.exe -sta $MyInvocation.ScriptName } 
+6
source share
2 answers

If you have pscx installed, you can use Invoke-Apartment -Apartment STA -Expression { .... } .

If not, check out WPF and PowerShell - Part 1 (Hello World and Welcome to the Week of WPF) , where James creates space with STA. Another source might be Asynchronicity in PowerShell .

Or a few old posts about the custom threaded separate apartment cmdlet in PowerShell V1 .

+7
source

You can "just use Invoke-Apartment" - rather glib's answer, given that it does not come with Powershell. Also, the developer should not assume that the code they write will always be on the machine, where the owner took the time to install pscx.

The job of starting Powershell will work if you want to change the source environment. I use PS ISE exclusively, so redriving my code from PS is changing my experience. I also don't like hard coding, where I think the PS lives. One day, Microsoft may change V1.0 (rather a windowsill to continue using it for V2 and V3!), So you really have to programmatically find what the user started and used. Also pass all the parameters that were passed to you. To make matters worse, when I go to Start / Accessories / Powershell, I have four options for starting PS. The coded workaround makes you choose which I might not have chosen.

+1
source

Source: https://habr.com/ru/post/890634/


All Articles