[英]Start Visual Studio programmatically; C# equivalent of VB's CreateObject(“VisualStudio.DTE.8.0”)
我可以從VBScript啟動一個新的隱藏Visual Studio進程,並通過以下方式以編程方式驅動它:
Set DTE = CreateObject("VisualStudio.DTE.8.0")
DTE.DoStuff()
我如何在C#中做到這一點? ( 編輯:使用正確的類型,而不是該VBScript代碼使用的通用COM對象。)
我試過這個:
using EnvDTE;
...
DTE dte = new DTE();
但我得到“檢索CLSID {3C9CFE1E-389F-4118-9FAD-365385190329}組件的COM類工廠失敗”。
我找到了答案(感謝Sebastiaan Megens讓我走上正軌):
[STAThread]
static void Main(string[] args)
{
System.Type t = System.Type.GetTypeFromProgID("VisualStudio.DTE.8.0", true);
DTE2 dte = (EnvDTE80.DTE2)System.Activator.CreateInstance(t, true);
// See http://msdn.microsoft.com/en-us/library/ms228772.aspx for the
// code for MessageFilter - just paste it in.
MessageFilter.Register();
dte.DoStuff();
dte.Quit();
}
public class MessageFilter : IOleMessageFilter
{
... Continues at http://msdn.microsoft.com/en-us/library/ms228772.aspx
(STAThread和MessageFilter的廢話是“由於外部多線程應用程序和Visual Studio之間的線程爭用問題”,無論這意味着什么。粘貼在http://msdn.microsoft.com/en-us/library/的代碼中ms228772.aspx使它工作。)
我不知道如何啟動Visual Studio的新實例,但我通過調用使用現有實例:
EnvDTE.DTE dte = (EnvDTE.DTE)System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE.8.0");
也許創建一個新實例是類似的? 希望這個對你有幫助。
問候,
Sebastiaan
用於VB的CreateObject的Microsoft源代碼。
<HostProtection(Resources:=HostProtectionResource.ExternalProcessMgmt)> _
<SecurityPermissionAttribute(SecurityAction.Demand, Flags:=SecurityPermissionFlag.UnmanagedCode)> _
Public Function CreateObject(ByVal ProgId As String, Optional ByVal ServerName As String = "") As Object
'Creates local or remote COM2 objects. Should not be used to create COM+ objects.
'Applications that need to be STA should set STA either on their Sub Main via STAThreadAttribute
'or through Thread.CurrentThread.ApartmentState - the VB runtime will not change this.
'DO NOT SET THREAD STATE - Thread.CurrentThread.ApartmentState = ApartmentState.STA
Dim t As Type
If ProgId.Length = 0 Then
Throw VbMakeException(vbErrors.CantCreateObject)
End If
If ServerName Is Nothing OrElse ServerName.Length = 0 Then
ServerName = Nothing
Else
'Does the ServerName match the MachineName?
If String.Compare(Environment.MachineName, ServerName, StringComparison.OrdinalIgnoreCase) = 0 Then
ServerName = Nothing
End If
End If
Try
If ServerName Is Nothing Then
t = Type.GetTypeFromProgID(ProgId)
Else
t = Type.GetTypeFromProgID(ProgId, ServerName, True)
End If
Return System.Activator.CreateInstance(t)
Catch e As COMException
If e.ErrorCode = &H800706BA Then
'&H800706BA = The RPC Server is unavailable
Throw VbMakeException(vbErrors.ServerNotFound)
Else
Throw VbMakeException(vbErrors.CantCreateObject)
End If
Catch ex As StackOverflowException
Throw ex
Catch ex As OutOfMemoryException
Throw ex
Catch ex As System.Threading.ThreadAbortException
Throw ex
Catch e As Exception
Throw VbMakeException(vbErrors.CantCreateObject)
End Try
End Function
簡單回答:在VB中編寫,編譯,用Reflector打開它,並在c#模式下反編譯!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.