有没有办法以编程方式将ApartmentState设置为STA? [英] Is there a way to programmatically set the ApartmentState to STA?

查看:244
本文介绍了有没有办法以编程方式将ApartmentState设置为STA?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在PowerShell中的GUI上工作,单击某些组合框时会抛出错误.

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

引发错误后,我可以将组合框列表放下并查看其内容,但是如果我移到同一datagridview上的另一个combox,则在看到下拉列表之前会遇到相同的初始错误.

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.

我在TechNet PowerShell论坛上发布了此内容,并获得了在单线程单元(STA)中运行GUI所需的答案.默认情况下,PowerShell在MTA中运行,但是在调用powershell.exe时,可以使用-STA开关将其覆盖(在v2.0中).

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.

但是,我的GUI只是调用默认的PowerShell应用程序(在MTA模式下) 所以我的问题是,是否可以通过编程方式从我的GUI/脚本内部设置单元状态?

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?

如果没有,我的下一个尝试将是检测公寓状态,并尝试使用类似以下方法从GUI的初始加载中重新启动GUI:

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

所以我的解决方法可以起作用:

So my workaround DOES work:

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

推荐答案

如果已安装 pscx ,则您可以使用Invoke-Apartment -Apartment STA -Expression { .... }.

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

如果没有,请查看 PowerShell中的异步性.

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.

或有关自定义cmdlet的一些较旧的帖子

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

这篇关于有没有办法以编程方式将ApartmentState设置为STA?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆