I am successfully instantiating/automating Visual Studio using the following code:
System.Type t = System.Type.GetTypeFromProgID("VisualStudio.DTE.9.0");
object obj = Activator.CreateInstance(t, true);
dte = (DTE)obj;
Solution sln = dte.Solution;
sln.Open(SolutionFile);
System.Threading.Thread.Sleep(1000);
//Do stuff with the solution
Notice the Thread.Sleep(1000)
call? If I don't include that, the code tries to bug the instance before it's ready and I get an exception:
the message filter indicated that the application is busy.
Rather than wait exactly n seconds, is there a way to poll this object for readiness?
While the solutions here are creative they either won't completely fix the problem or are very cumbersome to use. You should just register a message filter as Microsoft recommends.
Code copied here for convenience (replace
VisualStudio.DTE.10.0
with whatever version of VS you want to open), just pay attention to decorate theMain
method withSTAThread
attribute, message filtering won't work without it and it is skipped in original MSDN solution.I haven't had much luck with the IVSSolutionEvents technique (though I didn't try the code exactly as above). Instead, I created a small function to help me retry the call. I know that isn't particularly beautiful, but it is simple to call and it works!
Here's a link to my answer to another, similar question: https://stackoverflow.com/a/8565990/1106459
(It also helps with 'server busy' errors when calling other EnvDTE functions as well as opening and closing the solution.)
As a solution to this issue you can register to an event that notifies when the solution load is done.
This is a sample of class that lets you listen to events on solution loading:
Usage example: