Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
395 views
in Technique[技术] by (71.8m points)

c# - Automating Visual Studio instance from separate process

Is there a way to write an application that can connect to a running instance of Visual Studio and issue commands to it? For example, could I write a WPF app with a button that, when clicked, issues a "Build.BuildSolution" command to an already-open instance of Visual Studio, causing it to start a build?

I'm sure I could use SendKeys to send Ctrl+Shift+B, but I want to know if there's a way to write to an actual API to automate Visual Studio, and invoke commands by name.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here's a C# program that connects to a running Visual Studio and issues a Build command. The DTE.9 part means "Visual Studio 2008" - use DTE.8 for VS 2005, or DTE.10 for VS 2010.

using System;
using System.Runtime.InteropServices;
using EnvDTE80;

namespace SORemoteBuild
{
    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            // Get an instance of the currently running Visual Studio IDE.
            EnvDTE80.DTE2 dte2;
            dte2 = (EnvDTE80.DTE2)System.Runtime.InteropServices.Marshal.
                                      GetActiveObject("VisualStudio.DTE.9.0");
            dte2.Solution.SolutionBuild.Build(true);
        }
    }

    public class MessageFilter : IOleMessageFilter
    {
        // ... Continues at http://msdn.microsoft.com/en-us/library/ms228772.aspx

(The nonsense with STAThread and MessageFilter is "due to threading contention issues between external multi-threaded applications and Visual Studio", whatever that means. Pasting in the code from http://msdn.microsoft.com/en-us/library/ms228772.aspx makes it work.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...