How do I write to the Visual Studio Output Window in My Custom Tool?

前端 未结 5 1680
我寻月下人不归
我寻月下人不归 2020-12-07 16:08

I am writing a custom tool and I currently have it doing what I want as far as functionality. I would like to be able to write to Visual Studio if something goes wrong. (In

5条回答
  •  南方客
    南方客 (楼主)
    2020-12-07 16:13

    There is another way using Marshal.GetActiveObject to grab a running DTE2 instance.

    First reference EnvDTE and envdte80. This currently works in VisualStudio 2012, I haven't tried the others yet.

    using System;
    using System.Runtime.InteropServices;
    using EnvDTE;
    using EnvDTE80;
    
    internal class VsOutputLogger
    {
        private static Lazy> _Logger = new Lazy>( () => GetWindow().OutputString );
    
        private static Action Logger
        {
            get { return _Logger.Value; }
        }
    
        public static void SetLogger( Action logger )
        {
            _Logger = new Lazy>( () => logger );
        }
    
        public static void Write( string format, params object[] args)
        {
            var message = string.Format( format, args );
            Write( message );
        }
    
        public static void Write( string message )
        {
            Logger( message + Environment.NewLine );
        }
    
        private static OutputWindowPane GetWindow()
        {
            var dte = (DTE2) Marshal.GetActiveObject( "VisualStudio.DTE" );
            return dte.ToolWindows.OutputWindow.ActivePane;
        }
    }
    

提交回复
热议问题