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

前端 未结 2 693
迷失自我
迷失自我 2021-01-02 21:20

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

相关标签:
2条回答
  • 2021-01-02 21:54

    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.

    0 讨论(0)
  • 2021-01-02 21:55

    You can 'just use Invoke-Apartment' is rather a glib answer considering it does not come with Powershell. Nor should a developer assume code they wrote will always be on a machine where the owner took the time to install pscx.

    The work-around to launch Powershell works if you are willing to alter the original environment. I use the PS ISE exclusively, so redriving my code from PS changes my experience. I also dislike hard coding where I think PS lives. One day Microsoft might change V1.0 (rather sill to keep using it for V2 and V3!) so you should really programmatically find what the user started and use that. As well as pass any parameters that were passed to you. To make the problem worse, when I go to Start/Accessories/Powershell - I have four choices of PS to run. The coded workaround forces a choice I may not have chosen.

    0 讨论(0)
提交回复
热议问题