有没有一种方法以编程设定的ApartmentState到STA?方法、ApartmentState、STA

由网友(千疮百孔不如一枪痛快)分享简介:所以,我的工作在PowerShell中的GUI当某些组合框被点击,我被扔的错误。被抛出的错误后,我可能会下降在下拉列表下来,看它的内容,但如果我转移到另一个COMBOX在同一DataGridView的,我会得到相同的初始错误之前,我可以看到下拉列表。 我在TechNet PowerShell的论坛登载,并获得我需要在单...

所以,我的工作在PowerShell中的GUI当某些组合框被点击,我被扔的错误。被抛出的错误后,我可能会下降在下拉列表下来,看它的内容,但如果我转移到另一个COMBOX在同一DataGridView的,我会得到相同的初始错误之前,我可以看到下拉列表。

我在TechNet PowerShell的论坛登载,并获得我需要在单线程单元(STA)运行我的图形用户界面的答案。 PowerShell中,默认情况下,运行在MTA,但你可以调用 powershell.exe 。

不过,我的GUI简单地调用默认的PowerShell的应用程序(在MTA模式)的的所以我的问题是,有没有办法以编程方式从我的GUI /脚本里面设置的ApartmentState?的

如果没有,我的下一个尝试是将检测单元状态,并尝试重新踢了我的图形用户界面,从我的GUI的inital负载是这样的:

  powershell.exe -Sta myguiprog.ps1
 

任何帮助是AP preciated ...

编辑:

所以,我的变通办法工作:

 如果([threading.thread] :: CurrentThread.GetApartmentState()当量MTA){
    &放大器; $ ENV:SYSTEMROOT  SYSTEM32  WindowsPowerShell  V1.0  powershell.exe -Sta $ MyInvocation.ScriptName
}
 
Vscode server 一个移动设备上编程 多人编程的解决方法 附新手教程

解决方案

如果您有 pscx 安装,你可以使用调用-公寓-Apartment STA -Ex pression {...}

如果没有,看看WPF &放大器; PowerShell的 - 第1部分(的Hello World&功放;欢迎WPF的周),其中詹姆斯与STA创建运行空间。另有消息可能会在PowerShell中 异步性。

或者有关自定义cmdlet的一些旧的帖子Single螺纹公寓在PowerShell中V1 。

So 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 programatically 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 inital load of my gui with something like:

powershell.exe -STA myguiprog.ps1

Any help is appreciated...

Edit:

So my workaround DOES work:

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

解决方案

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.