Search code examples
c#visual-studioenvdte

How can I get IWpfTextView for EnvDte.ActiveDocument?


I am trying to manipulate the Visual Studio Text Editor scrollbar values. The problem is that I have only the dte.ActiveDocument and it is not possible to do it from there.

My extension is loaded only once when VS starts and I capture dte.Events.CommandEvents. At some point I want to change the scrollbar values for the ActiveDocument. To do this I need IWpfTextView or ITextView. Do you have any idea how can I get an instance of that object?

internal class MyExtension
    {
        private CommandEvents commandEvents;

        private DTE dte;

        public MyExtension(DTE dte)
        {
            this.dte = dte;
            commandEvents = dte.Events.CommandEvents;
            commandEvents.BeforeExecute += commandEvents_BeforeExecute;
        }

        void commandEvents_BeforeExecute(string Guid, int ID, object CustomIn, object CustomOut, ref bool CancelDefault)
        {
            var doc = dte.ActiveDocument
            // CHANGE SCROLLBAR VALUES HERE
        }
    }

Solution

  • I found a way to do this. In the main class of the extension I get SVsTextManager

    public sealed class MyExtensionPackage : Package
    {
        protected override void Initialize()
        {
            DTE dte = (DTE)base.GetService(typeof(DTE));
            var txtMgr = (IVsTextManager)base.GetService(typeof(SVsTextManager));
            plugin = new MyExtension(dte, txtMgr);
            base.Initialize();
        }
    }
    
    internal class MyExtension
        {
            private CommandEvents commandEvents;
    
            private DTE dte;
            private IVsTextManager txtMngr;
    
            public MyExtension(DTE dte, IVsTextManager txtMngr)
            {
                this.txtMngr = txtMngr;
                this.dte = dte;
                commandEvents = dte.Events.CommandEvents;
                commandEvents.BeforeExecute += commandEvents_BeforeExecute;
            }
    
            void commandEvents_BeforeExecute(string Guid, int ID, object CustomIn, object CustomOut, ref bool CancelDefault)
            {
                var doc = dte.ActiveDocument
    
                IVsTextView textViewCurrent;
                txtMngr.GetActiveView(1, null, out textViewCurrent);
                int a, b, c, verticalScrollPosition;
    
                var scrollInfo = textViewCurrent.GetScrollInfo(1, out a, out b, out c, out verticalScrollPosition);
                textViewCurrent.SetScrollPosition(1, verticalScrollPosition);
            }
        }