Question

I want to intercept key events in vs. I searched many articles for help, and this article inspired me. What I have done is:

  1. create a new class and implement "IVsTextManagerEvents" interface to register every textview.

    public void OnRegisterView(IVsTextView pView)
    {
        CommandFilter filter = new CommandFilter();
        IOleCommandTarget nextCommandTarget;
        pView.AddCommandFilter(filter, out nextCommandTarget);
        filter.NextCommandTarget = nextCommandTarget;
    }
    
  2. add new class "CommandFilter" which implement IOleCommandTarget , in which we can intercept olecommand from vs

    public class CommandFilter : IOleCommandTarget
    {    
    
        public IOleCommandTarget NextCommandTarget
        {
            get; 
            set;
        }
    
        public int QueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText)
        {
            NextCommandTarget.QueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText);
            return VSConstants.S_OK;
        }
    
        public int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
        {
            if (pguidCmdGroup == typeof(VSConstants.VSStd2KCmdID).GUID)
            {
                switch (nCmdID)
                {
                    case (uint)VSConstants.VSStd2KCmdID.RETURN:
                        MessageBox.Show("enter");
                        break;
                }
            }
    
            NextCommandTarget.Exec(pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut);
    
            return VSConstants.S_OK;
        }
    }
    
  3. we need to advise IVsTextManagerEvents in Initialize

    protected override void Initialize()
    {
        base.Initialize();
    
        IConnectionPointContainer textManager = (IConnectionPointContainer)GetService(typeof(SVsTextManager));
        Guid interfaceGuid = typeof(IVsTextManagerEvents).GUID;
        textManager.FindConnectionPoint(ref interfaceGuid, out tmConnectionPoint);
        tmConnectionPoint.Advise(new TextManagerEventSink(), out tmConnectionCookie);
    }
    

after above prepare, we can now intercept key events. you can see a message box after you stroke key "enter".

My question is, after I have done above

  1. I can't save the document, that means when I stroked ctrl+S, nothing happened.
  2. You can see obvious delay, when I key in words. It seems my package take a long time to handle something, but as you can see above, I didn't at all.
Était-ce utile?

La solution

It seems I have found the answer!

Not:

NextCommandTarget.Exec(pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut);

return VSConstants.S_OK;

But:

return NextCommandTarget.Exec(pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top