How to get IEditorOperations from IVsTextView?

2019-09-05 20:05发布

I'm developing my first Visual Studio (2015 Community) Command Menu and I'm trying to get access to IEditorOperations to delete text, send backspace etc. but I'm not sure how to. I can do:

var Service = Provider.GetService(typeof(IEditorOperationsFactoryService)) as IEditorOperationsFactoryService;
Service.GetEditorOperations(???);

I'm not sure what to pass in the ??? since I don't have access to an ITextView instead what I have is a IVsTExtView via:

IVsTextView View;
IVsTextManager Manager = (IVsTextManager)ServiceProvider.GetService(typeof(SVsTextManager));
int MustHaveFocus = 1;
Manager.GetActiveView(MustHaveFocus, null, out View);

When creating the Command Menu, VS generates a template for me with a private ctor creating the command service, binding it to the command set id etc. An overridden Initialize method, and a bunch of properties.

Any ideas?

EDIT: After help from Sergey, I managed to get a bit further. But now I get a null when I try to get the IEditorOperationsFactoryService, all the other values are valid.

static IEditorOperations GetEditorService(IServiceProvider Provider, IVsTextView VsView)
    {
        IEditorOperations Result;

        try
        {
            var Model = (IComponentModel)Provider.GetService(typeof(SComponentModel));
            var Editor = (IEditorOperationsFactoryService)Provider.GetService(typeof(IEditorOperationsFactoryService)); // returns null

            var Adaptor = Model.GetService<IVsEditorAdaptersFactoryService>();
            IWpfTextView TextView = Adaptor.GetWpfTextView(VsView);
            Result = Editor.GetEditorOperations(TextView);
        }
        catch (Exception e)
        {
            System.Windows.Forms.MessageBox.Show(e.ToString());
            Result = null;
        }

        return (Result);
    }

2条回答
Bombasti
2楼-- · 2019-09-05 20:24

You can get IWpfTextView (that implements ITextView) from IVsTextView using:

IVsTextView textView = ...;
IWpfTextView v = GetEditorAdaptersFactoryService().GetWpfTextView(textView);

private Microsoft.VisualStudio.Editor.IVsEditorAdaptersFactoryService GetEditorAdaptersFactoryService()
{
    Microsoft.VisualStudio.ComponentModelHost.IComponentModel componentModel =
        (Microsoft.VisualStudio.ComponentModelHost.IComponentModel)serviceProvider.GetService(
            typeof(Microsoft.VisualStudio.ComponentModelHost.SComponentModel));
    return componentModel.GetService<Microsoft.VisualStudio.Editor.IVsEditorAdaptersFactoryService>();
}
查看更多
孤傲高冷的网名
3楼-- · 2019-09-05 20:32

You can get IEditorOperationsFactoryService instance from variable named Model, like this:

var Model = (IComponentModel)this.ServiceProvider.GetService(typeof(SComponentModel));

var Editor = (IEditorOperationsFactoryService)Model.GetService<IEditorOperationsFactoryService>();
查看更多
登录 后发表回答