问题
I want to intercept key events in vs. I searched many articles for help, and this article inspired me. What I have done is:
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; }
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; } }
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
- I can't save the document, that means when I stroked ctrl+S, nothing happened.
- 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.
回答1:
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);
来源:https://stackoverflow.com/questions/8544203/issues-after-i-add-a-command-filter-to-textview