PowerShell Studio: Knowing when to use STA mode
- Written by David Corrales
- Last Updated: 14 April 2016
- Created: 09 March 2015
- Hits: 1183
Recently, on our forums, a user asked why certain controls didn’t function correctly or threw an error when he unchecked the STA option in PowerShell Studio.
STA (Single Threaded Apartment) and MTA (Multi-Threaded Apartment) determine how a process manages legacy COM objects and their communication with multiple threads. I will not go into the detail, but you need not concern yourself with the inner workings of COM objects, other than to remember that STA is required for some of the GUI controls to function correctly.
Which controls require STA?
The following controls require STA mode. Otherwise, they do not appear.
The following control features require STA mode.
- TextBox with AutoCompleteSource
- ComboBox with AutoCompleteSource
- DataGridView with Ctrl + C to copy text in cells.
- Form with TopMost property set to True.
Also, static methods of the Clipboard class require STA mode. For example:
[System.Windows.Forms.Clipboard]::SetText("Paste this text to the clipboard")
Packaging and STA mode:
Luckily, PowerShell Studio detects when your form includes an STA mode dependent control and runs it in STA mode. But, when you package a script, be sure to retain the STA mode settings.
Click Deploy and in the Packager section, click Settings and then Engine Settings.
Next, make sure that your Windows PowerShell scripts require STA when running. If you add the following comment to your script, PowerShell Studio and PrimalScript run the script in STA mode:
# %ForceSTA% = True
Starting in Windows PowerShell 3.0, the Windows PowerShell console runs in STA mode by default. If you are using Windows PowerShell 2.0, use the following command to start Windows PowerShell with the STA option:
Windows PowerShell ISE always runs in STA mode.
To determine whether a Windows PowerShell host program is running in STA mode, use this command to check the value of the ApartmentState property:
STA mode is not something you normally have to consider when writing scripts, but it is something that you should be aware of if you are creating GUIs tools. Most GUIs will run fine in MTA mode, but as a general rule, we recommended that you always run your GUI scripts in STA mode.
David Corrales is Senior Software Engineer at SAPIEN Technologies, Inc. Follow him on Twitter at @SAPIENDavid.