MonadからVB.NETのコードを実行(2)

MonadからVB.NETのコードを実行 - PowerShell Memoでは、

例えば、Beta2のMonadではSTAスレッドで実行が必要なオブジェクトは動作しませんが、
VBCodeProviderを利用してVB.NETのコードを書けば、実現できるわけです。

と書きましたが、その具体例を紹介します。


System.Windows.Forms.ClipboardはSTAスレッドで実行が必要なため、Clipboardを利用してクリップボードにはアクセスできません。
参考:http://winscript.s41.xrea.com/mt/archives/2005/09/post_5.html


その解決方法としてNewsGroupで「VBCodeProviderを利用してクリップボードへアクセスするサンプル」が紹介されています。
http://www.microsoft.com/communities/newsgroups/list/en-us/default.aspx?&query=STA&lang=en&cr=us&guid=&sloc=en-us&dg=microsoft.public.windows.server.scripting&p=1&tid=17a38787-44ee-427f-852e-66c9c290b65d

$provider = new-object Microsoft.VisualBasic.VBCodeProvider 
$params = new-object System.CodeDom.Compiler.CompilerParameters 
$params.GenerateInMemory = $True 
$refs = 
"System.dll","Microsoft.VisualBasic.dll","System.Data.DLL", `
"System.management.dll","System.DirectoryServices.dll" 
$params.ReferencedAssemblies.AddRange($refs) 

# VB.NET EXAMPLE 
$txtCode = @' 

Imports Microsoft.VisualBasic 
Imports System 
Imports System.Threading 

Public Class mow 

Sub Main() 
Dim newThread As Thread = New Thread(AddressOf ThreadMethod) 
newThread.ApartmentState = ApartmentState.STA 
newThread.Start() 
End Sub 

Shared Sub ThreadMethod() 
dim Comp as new Microsoft.VisualBasic.Devices.computer 
comp.clipboard.setText("hello Clip") 
End Sub 

End Class 


'@ 

$results = $provider.CompileAssemblyFromSource($params, $txtCode) 
$mAssembly = $results.CompiledAssembly 
$i = $mAssembly.CreateInstance("mow") 
$r = $i.main() 

また、上記サンプル作者のページでは、ClipboardクラスをSTAスレッドで利用するようにラップしたDLLを通して、MSHからクリップボードを操作する方法も紹介されています。
/\/\o\/\/ PowerShelled: MSH Clipboard part 2 (of 3 ?)