Пошаговое руководство: Использование сочетание клавиш с расширением редактора
Можно ответить на сочетаниям клавиш в расширении редактора. В следующем пошаговом руководстве показано, как добавить оформление представлений к представлению текста с помощью сочетаний клавиш. В этом пошаговом руководстве основано на шаблоне редактора элемента оформления окна просмотра, а также позволяет добавлять оформление с помощью + знак.
Обязательные компоненты
Чтобы выполнить это пошаговое руководство, необходимо устанавливать SDK для Visual Studio 2010.
Примечание
Дополнительные сведения о пакете SDK для Visual Studio см. в разделе интеграция SDK Visual Studio.Чтобы узнать, как загрузить пакет SDK для Visual Studio см. в разделе Центр разработчиков расширяемости Visual Studio на веб-сайте MSDN.
Создание управляемой расширяемости проекта .NET Framework (платформа MEF)
Создание проекта MEF
Создание проекта элемента оформления окна просмотра редактора. Назовите решение KeyBindingTest.
Откройте файл source.extension.vsixmanifest в редакторе манифеста VSIX.
Убедитесь, что Content заголовок содержит тип содержимого и компонент MEF Path имеет значение KeyBindingTest.dll.
Сохранить и закрыть Source.extension.vsixmanifest.
Добавьте следующие ссылки и набор CopyLocal В false.
Microsoft.VisualStudio.Editor
Microsoft.VisualStudio.OLE.Interop
Microsoft.VisualStudio.Shell
Microsoft.VisualStudio.TextManager.Interop
Удалите файл класса KeyBindingTestFactory.
В файле класса KeyBindingTest измените имя класса в PurpleCornerBox. Измените конструктор. Внутри конструктора, измените линия.
_adornmentLayer = view.GetAdornmentLayer("KeyBindingTest")
_adornmentLayer = view.GetAdornmentLayer("KeyBindingTest");
в
_adornmentLayer = view.GetAdornmentLayer("PurpleCornerBox")
_adornmentLayer = view.GetAdornmentLayer("PurpleCornerBox");
Определение фильтра команды
Фильтр команды реализация IOleCommandTarget, который обрабатывает команды, создав крайний элемент.
Определить фильтр команды
Добавьте файл классов и назовите его KeyBindingCommandFilter.
Добавьте следующие строки с помощью выписки.
Imports System Imports System.Runtime.InteropServices Imports Microsoft.VisualStudio.OLE.Interop Imports Microsoft.VisualStudio Imports Microsoft.VisualStudio.Text.Editor
using System; using System.Runtime.InteropServices; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Text.Editor;
Класс должен наследоваться от KeyBindingCommandFilter IOleCommandTarget.
Friend Class KeyBindingCommandFilter Implements IOleCommandTarget
internal class KeyBindingCommandFilter : IOleCommandTarget
Добавьте закрытые поля для представления текста, следующей команды в цепочке команды, представления и пометить фильтр уже был добавлен ли команды.
Private m_textView As IWpfTextView Friend m_nextTarget As IOleCommandTarget Friend m_added As Boolean Friend m_adorned As Boolean
private IWpfTextView m_textView; internal IOleCommandTarget m_nextTarget; internal bool m_added; internal bool m_adorned;
Добавьте конструктор, который задает представление текста.
Public Sub New(ByVal textView As IWpfTextView) m_textView = textView m_adorned = False End Sub
public KeyBindingCommandFilter(IWpfTextView textView) { m_textView = textView; m_adorned = false; }
Реализуйте QueryStatus() метод следующим образом.
Private Function QueryStatus(ByRef pguidCmdGroup As Guid, ByVal cCmds As UInteger, ByVal prgCmds() As OLECMD, ByVal pCmdText As IntPtr) As Integer Implements IOleCommandTarget.QueryStatus Return m_nextTarget.QueryStatus(pguidCmdGroup, cCmds, prgCmds, pCmdText) End Function
int IOleCommandTarget.QueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText) { return m_nextTarget.QueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText); }
Реализуйте Exec() метод, чтобы он добавляет пурпуровое окно к представлению, если a + знак типизирован.
Private Function Exec(ByRef pguidCmdGroup As Guid, ByVal nCmdID As UInteger, ByVal nCmdexecopt As UInteger, ByVal pvaIn As IntPtr, ByVal pvaOut As IntPtr) As Integer Implements IOleCommandTarget.Exec If m_adorned = False Then Dim typedChar As Char = Char.MinValue If pguidCmdGroup = VSConstants.VSStd2K AndAlso nCmdID = CUInt(VSConstants.VSStd2KCmdID.TYPECHAR) Then typedChar = CChar(ChrW(Marshal.GetObjectForNativeVariant(pvaIn))) If typedChar.Equals("+"c) Then Dim TempPurpleCornerBox As PurpleCornerBox = New PurpleCornerBox(m_textView) m_adorned = True End If End If End If Return m_nextTarget.Exec(pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut) End Function
int IOleCommandTarget.Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) { if (m_adorned == false) { char typedChar = char.MinValue; if (pguidCmdGroup == VSConstants.VSStd2K && nCmdID == (uint)VSConstants.VSStd2KCmdID.TYPECHAR) { typedChar = (char)(ushort)Marshal.GetObjectForNativeVariant(pvaIn); if (typedChar.Equals('+')) { new PurpleCornerBox(m_textView); m_adorned = true; } } } return m_nextTarget.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut); }
Добавление фильтра команды поставщика
Поставщик крайнего элемента должен добавить фильтр команды к представлению текста. В этом примере поставщик реализует IVsTextViewCreationListener для прослушивания текст просмотрите события создания. Этот поставщик крайнего элемента также экспортирует слой оформлений, который задает z-порядок элемента оформления.
Добавление фильтра команды поставщика
Добавьте файл классов и назовите его KeyBindingFilterProvider.
Добавьте следующие строки с помощью выписки.
Imports System Imports System.Collections.Generic Imports System.ComponentModel.Composition Imports Microsoft.VisualStudio Imports Microsoft.VisualStudio.OLE.Interop Imports Microsoft.VisualStudio.Utilities Imports Microsoft.VisualStudio.Editor Imports Microsoft.VisualStudio.Text.Editor Imports Microsoft.VisualStudio.TextManager.Interop
using System; using System.Collections.Generic; using System.ComponentModel.Composition; using Microsoft.VisualStudio; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Utilities; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.TextManager.Interop;
Добавьте в проект класс KeyBindingFilterProvider он наследует IVsTextViewCreationListenerи экспортировать его с типом содержимого "text" и " a " TextViewRoleAttributeEditable.
<Export(GetType(IVsTextViewCreationListener)), ContentType("text"), TextViewRole(PredefinedTextViewRoles.Editable)> Friend Class KeyBindingCommandFilterProvider Implements IVsTextViewCreationListener
[Export(typeof(IVsTextViewCreationListener))] [ContentType("text")] [TextViewRole(PredefinedTextViewRoles.Editable)] internal class KeyBindingCommandFilterProvider : IVsTextViewCreationListener
Добавьте определение слоев оформлений.
<Export(GetType(AdornmentLayerDefinition)), Name("PurpleCornerBox"), Order(), TextViewRole(PredefinedTextViewRoles.Editable)> Friend keybindingAdornmentLayer As AdornmentLayerDefinition
[Export(typeof(AdornmentLayerDefinition))] [Name("PurpleCornerBox")] [Order()] [TextViewRole(PredefinedTextViewRoles.Editable)] internal AdornmentLayerDefinition keybindingAdornmentLayer;
Чтобы получить адаптер представления текста необходимо импортировать IVsEditorAdaptersFactoryService.
<Import(GetType(IVsEditorAdaptersFactoryService))> Friend editorFactory As IVsEditorAdaptersFactoryService = Nothing
[Import(typeof(IVsEditorAdaptersFactoryService))] internal IVsEditorAdaptersFactoryService editorFactory = null;
Реализуйте VsTextViewCreated метод, чтобы он добавляет KeyBindingCommandFilter.
Public Sub VsTextViewCreated(ByVal textViewAdapter As IVsTextView) Implements IVsTextViewCreationListener.VsTextViewCreated Dim textView As IWpfTextView = editorFactory.GetWpfTextView(textViewAdapter) If textView Is Nothing Then Return End If AddCommandFilter(textViewAdapter, New KeyBindingCommandFilter(textView)) End Sub
public void VsTextViewCreated(IVsTextView textViewAdapter) { IWpfTextView textView = editorFactory.GetWpfTextView(textViewAdapter); if (textView == null) return; AddCommandFilter(textViewAdapter, new KeyBindingCommandFilter(textView)); }
AddCommandFilter обработчик получает адаптер представления текста и добавляет фильтр команды.
Private Sub AddCommandFilter(ByVal viewAdapter As IVsTextView, ByVal commandFilter As KeyBindingCommandFilter) If commandFilter.m_added = False Then 'get the view adapter from the editor factory Dim [next] As IOleCommandTarget Dim hr As Integer = viewAdapter.AddCommandFilter(commandFilter, [next]) If hr = VSConstants.S_OK Then commandFilter.m_added = True 'you'll need the next target for Exec and QueryStatus If [next] IsNot Nothing Then commandFilter.m_nextTarget = [next] End If End If End If End Sub
void AddCommandFilter(IVsTextView viewAdapter, KeyBindingCommandFilter commandFilter) { if (commandFilter.m_added == false) { //get the view adapter from the editor factory IOleCommandTarget next; int hr = viewAdapter.AddCommandFilter(commandFilter, out next); if (hr == VSConstants.S_OK) { commandFilter.m_added = true; //you'll need the next target for Exec and QueryStatus if (next != null) commandFilter.m_nextTarget = next; } } }
Построение и тестирование кода
Для тестирования этого кода выполните построение решения KeyBindingTest и запустите его в экспериментальном экземпляре.
Построение и тестирование решение KeyBindingTest
Выполните построение решения.
Если запустить этот проект в отладчике, второй экземпляр Visual Studio создается.
Создайте или откройте текстовый файл, а затем щелкните мышью в любом месте представления текста.
Тип +.
Измените размер представления текста.
Пурпуровый квадрат должен отображаться в правом верхнем углу представления текста.
См. также
Задачи
Пошаговое руководство: Связывание тип контента в расширение имени файла