Search code examples
.netpowershellsta

Is there a way to programmatically set the ApartmentState to STA?


I'm working on a GUI in PowerShell where I was throwing errors when certain comboboxes were clicked.

After the error was thrown, I could drop the combobox list down and see it's contents, but if I shifted 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 in the TechNet PowerShell forums and got the answer that I needed to run my GUI in single threaded apartment (STA). PowerShell, by default, runs in MTA but you can overwrite this (in v2.0) by using the -STA switch when calling powershell.exe.

However, my GUI simply invokes the default PowerShell application (in MTA mode) so my question is, is there a way to programmatically set the apartmentstate from inside of my GUI/script?

If not, my next attempt would be to detect the apartment state and try to re-kick off my GUI from the initial load of my gui with something like:

powershell.exe -STA myguiprog.ps1

Edit:

So my workaround DOES work:

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

Solution

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

    If not, have a look at WPF & PowerShell – Part 1 ( Hello World & Welcome to the Week of WPF ) where James creates runspace with STA. Another source might be Asynchronicity in PowerShell.

    Or some older posts about custom cmdlet Single Threaded Apartment in PowerShell V1.