Automating Visual Studio instance from separate pr

2019-01-27 03:35发布

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.

2条回答
Ridiculous、
2楼-- · 2019-01-27 03:37

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.)

查看更多
姐就是有狂的资本
3楼-- · 2019-01-27 03:53

If you are just trying to automate builds/packaging of your apps, you should look into MSBuild -- it is Microsoft's build engine that lets you script automation of most of the functions of Visual Studio.

查看更多
登录 后发表回答