Windows tool position window

Содержание
  1. Add a tool window
  2. Prerequisites
  3. Create a tool window
  4. Add a control to the tool window
  5. Add a toolbar to the tool window
  6. Add a command to the toolbar
  7. Add a MediaPlayer property to FirstToolWindowControl
  8. Instantiate the tool window and toolbar
  9. To implement a menu command in the tool window
  10. Set the default position for the tool window
  11. Test the tool window
  12. Добавление окна инструментов Add a tool window
  13. Предварительные требования Prerequisites
  14. Создание окна инструментов Create a tool window
  15. Добавление элемента управления в окно инструментов Add a control to the tool window
  16. Добавление панели инструментов в окно инструментов Add a toolbar to the tool window
  17. Добавление команды на панель инструментов Add a command to the toolbar
  18. Добавление свойства MediaPlayer в Фирсттулвиндовконтрол Add a MediaPlayer property to FirstToolWindowControl
  19. Создание экземпляра окна инструментов и панели инструментов Instantiate the tool window and toolbar
  20. Реализация команды меню в окне инструментов To implement a menu command in the tool window
  21. Задание расположения по умолчанию для окна инструментов Set the default position for the tool window
  22. Тестирование окна инструментов Test the tool window

Add a tool window

In this walkthrough you learn how to create a tool window and integrate it into Visual Studio in the following ways:

Add a control to the tool window.

Add a toolbar to a tool window.

Add a command to the toolbar.

Implement the commands.

Set the default position for the tool window.

Prerequisites

The Visual Studio SDK is included as an optional feature in Visual Studio setup. For more information, see Install the Visual Studio SDK.

Create a tool window

Create a project named FirstToolWin using the VSIX template, and add a custom tool window item template named FirstToolWindow.

For more information about creating an extension with a tool window, see Create an extension with a tool window.

Add a control to the tool window

Remove the default control. Open FirstToolWindowControl.xaml and delete the Click Me! button.

In the Toolbox, expand the All WPF Controls section and drag the Media Element control to the FirstToolWindowControl form. Select the control, and in the Properties window, name this element mediaElement1.

Add a toolbar to the tool window

By adding a toolbar in the following manner, you guarantee that its gradients and colors are consistent with the rest of the IDE.

In Solution Explorer, open FirstToolWindowPackage.vsct. The .vsct file defines the graphical user interface (GUI) elements in your tool window by using XML.

In the section, find the node whose name attribute is guidFirstToolWindowPackageCmdSet . Add the following two elements to the list of elements in this node to define a toolbar and a toolbar group.

Just above the section, create a section that resembles this:

There are several different kinds of menu. This menu is a toolbar in a tool window, defined by its type attribute. The guid and id settings make up the fully qualified ID of the toolbar. Typically, the

of a menu is the containing group. However, a toolbar is defined as its own parent. Therefore, the same identifier is used for the and

elements. The priority attribute is just ‘0’.

Toolbars resemble menus in many ways. For example, just as a menu may have groups of commands, toolbars may also have groups. (On menus, the command groups are separated by horizontal lines. On toolbars, the groups are not separated by visual dividers.)

Add a section that contains a element. This defines the group whose ID you declared in the section. Add the section just after the section.

By setting the parent GUID and ID to the GUID and ID of the toolbar, you add the group to the toolbar.

Add a command to the toolbar

Add a command to the toolbar, which is displayed as a button.

In the section, declare the following IDSymbol elements just after the toolbar and toolbar group declarations.

Add a Button element inside the section. This element will appear on the toolbar in the tool window, with a Search (magnifying glass) icon.

Open FirstToolWindowCommand.cs and add the following lines in the class just after the existing fields.

Doing this makes your commands available in code.

Add a MediaPlayer property to FirstToolWindowControl

From the event handlers for the toolbar controls, your code must be able to access the Media Player control, which is a child of the FirstToolWindowControl class.

In Solution Explorer, right-click FirstToolWindowControl.xaml, click View Code, and add the following code to the FirstToolWindowControl class.

Instantiate the tool window and toolbar

Add a toolbar and a menu command that invokes the Open File dialog and plays the selected media file.

Open FirstToolWindow.cs and add the following using directives:

Inside the FirstToolWindow class, add a public reference to the FirstToolWindowControl control.

Читайте также:  Linux hard link to file

At the end of the constructor, set this control variable to the newly-created control.

Instantiate the toolbar inside the constructor.

At this point, the FirstToolWindow constructor should look like this:

Add the menu command to the toolbar. In the FirstToolWindowCommand.cs class, add the following using directive:

In the FirstToolWindowCommand class, add the following code at the end of the ShowToolWindow() method. The ButtonHandler command will be implemented in the next section.

To implement a menu command in the tool window

In the FirstToolWindowCommand class, add a ButtonHandler method that invokes the Open File dialog. When a file has been selected, it plays the media file.

In the FirstToolWindowCommand class, add a private reference to the FirstToolWindow window that gets created in the FindToolWindow() method.

Change the ShowToolWindow() method to set the window you defined above (so that the ButtonHandler command handler can access the window control. Here is the complete ShowToolWindow() method.

Add the ButtonHandler method. It creates an OpenFileDialog for the user to specify the media file to play, and then plays the selected file.

Set the default position for the tool window

Next, specify a default location in the IDE for the tool window. Configuration information for the tool window is in the FirstToolWindowPackage.cs file.

In FirstToolWindowPackage.cs, find the ProvideToolWindowAttribute attribute on the FirstToolWindowPackage class, which passes the FirstToolWindow type to the constructor. To specify a default position, you must add more parameters to the constructor following example.

The first named parameter is Style and its value is Tabbed , which means that the window will be a tab in an existing window. The docking position is specified by the Window parameter, n this case, the GUID of the Solution Explorer.

For more information about the types of windows in the IDE, see vsWindowType.

Test the tool window

Press F5 to open a new instance of the Visual Studio experimental build.

On the View menu, point to Other Windows and then click First Tool Window.

The media player tool window should open in the same position as Solution Explorer. If it still appears in the same position as before, reset the window layout (Window / Reset Window Layout).

Добавление окна инструментов Add a tool window

В этом пошаговом руководстве вы узнаете, как создать окно инструментов и интегрировать его в Visual Studio следующими способами. In this walkthrough you learn how to create a tool window and integrate it into Visual Studio in the following ways:

Добавление элемента управления в окно инструментов. Add a control to the tool window.

Добавление панели инструментов в окно инструментов. Add a toolbar to a tool window.

Добавьте команду на панель инструментов. Add a command to the toolbar.

Реализуйте команды. Implement the commands.

Задайте расположение по умолчанию для окна инструментов. Set the default position for the tool window.

Предварительные требования Prerequisites

Пакет SDK для Visual Studio входит в состав программы установки Visual Studio в качестве дополнительного компонента. The Visual Studio SDK is included as an optional feature in Visual Studio setup. Дополнительные сведения см. в статье Установка пакета SDK для Visual Studio. For more information, see Install the Visual Studio SDK.

Создание окна инструментов Create a tool window

Создайте проект с именем фирсттулвин с помощью шаблона VSIX и добавьте пользовательский шаблон элемента окна инструментов с именем фирсттулвиндов. Create a project named FirstToolWin using the VSIX template, and add a custom tool window item template named FirstToolWindow.

Дополнительные сведения о создании расширения с помощью окна инструментов см. в разделе Создание расширения с помощью окна инструментов. For more information about creating an extension with a tool window, see Create an extension with a tool window.

Добавление элемента управления в окно инструментов Add a control to the tool window

Удалите элемент управления по умолчанию. Remove the default control. Откройте фирсттулвиндовконтрол. XAML и удалите элемент » Click Me! «. Open FirstToolWindowControl.xaml and delete the Click Me! . button.

На панели элементов разверните раздел все элементы управления WPF и перетащите элемент управления » элемент мультимедиа » в форму фирсттулвиндовконтрол . In the Toolbox, expand the All WPF Controls section and drag the Media Element control to the FirstToolWindowControl form. Выберите элемент управления и в окне Свойства назовите этот элемент mediaElement1. Select the control, and in the Properties window, name this element mediaElement1.

Добавление панели инструментов в окно инструментов Add a toolbar to the tool window

Добавив панель инструментов следующим образом, вы гарантируете, что ее градиенты и цвета будут согласованы с остальной частью интегрированной среды разработки. By adding a toolbar in the following manner, you guarantee that its gradients and colors are consistent with the rest of the IDE.

Читайте также:  Проблема с кодировками windows

В Обозреватель решений откройте фирсттулвиндовпаккаже. vsct. In Solution Explorer, open FirstToolWindowPackage.vsct. Файл . vsct определяет графические элементы пользовательского интерфейса (GUI) в окне инструментов с помощью XML. The .vsct file defines the graphical user interface (GUI) elements in your tool window by using XML.

В разделе найдите узел, атрибут которого name имеет значение guidFirstToolWindowPackageCmdSet . In the section, find the node whose name attribute is guidFirstToolWindowPackageCmdSet . Добавьте следующие два элемента в список элементов этого узла, чтобы определить панель инструментов и группу панелей инструментов. Add the following two elements to the list of elements in this node to define a toolbar and a toolbar group.

Непосредственно над разделом создайте раздел, похожий на следующий: Just above the section, create a section that resembles this:

Существует несколько различных видов меню. There are several different kinds of menu. Это меню представляет собой панель инструментов в окне инструментов, определяемую его type атрибутом. This menu is a toolbar in a tool window, defined by its type attribute. guid Параметры и id составляют полный идентификатор панели инструментов. The guid and id settings make up the fully qualified ID of the toolbar. Как правило, в

меню содержится группа, содержащая. Typically, the

of a menu is the containing group. Однако панель инструментов определяется как собственная родительская. However, a toolbar is defined as its own parent. Таким образом, для элементов и используется один и тот же идентификатор

. Therefore, the same identifier is used for the and

elements. priority Атрибут имеет значение только «0». The priority attribute is just ‘0’.

Во многих случаях панели инструментов напоминают меню. Toolbars resemble menus in many ways. Например, так как меню могут иметь группы команд, панели инструментов могут также иметь группы. For example, just as a menu may have groups of commands, toolbars may also have groups. (В меню группы команд разделяются горизонтальными линиями. (On menus, the command groups are separated by horizontal lines. На панелях инструментов группы не разделяются визуальными разделителями.) On toolbars, the groups are not separated by visual dividers.)

Добавьте раздел, содержащий элемент. Add a section that contains a element. Определяет группу, идентификатор которой был объявлен в разделе. This defines the group whose ID you declared in the section. Добавьте раздел сразу после раздела. Add the section just after the section.

Установив для родительского идентификатора GUID и идентификатора идентификатор GUID и идентификатор панели инструментов, вы добавите группу на панель инструментов. By setting the parent GUID and ID to the GUID and ID of the toolbar, you add the group to the toolbar.

Добавление команды на панель инструментов Add a command to the toolbar

Добавьте команду на панель инструментов, которая отображается как кнопка. Add a command to the toolbar, which is displayed as a button.

В разделе объявите следующие элементы IDSymbol сразу после объявлений групп панелей инструментов и панелей инструментов. In the section, declare the following IDSymbol elements just after the toolbar and toolbar group declarations.

Добавьте в раздел элемент Button . Add a Button element inside the section. Этот элемент появится на панели инструментов в окне инструментов с значком поиска (лупа). This element will appear on the toolbar in the tool window, with a Search (magnifying glass) icon.

Откройте фирсттулвиндовкомманд. CS и добавьте следующие строки в класс сразу после существующих полей. Open FirstToolWindowCommand.cs and add the following lines in the class just after the existing fields.

Это делает команды доступными в коде. Doing this makes your commands available in code.

Добавление свойства MediaPlayer в Фирсттулвиндовконтрол Add a MediaPlayer property to FirstToolWindowControl

В обработчиках событий для элементов управления панели инструментов код должен иметь доступ к элементу управления Media Player, который является дочерним по отношению к классу Фирсттулвиндовконтрол. From the event handlers for the toolbar controls, your code must be able to access the Media Player control, which is a child of the FirstToolWindowControl class.

В Обозреватель решений щелкните правой кнопкой мыши фирсттулвиндовконтрол. XAML, выберите пункт Просмотреть код и добавьте следующий код в класс фирсттулвиндовконтрол. In Solution Explorer, right-click FirstToolWindowControl.xaml, click View Code, and add the following code to the FirstToolWindowControl class.

Создание экземпляра окна инструментов и панели инструментов Instantiate the tool window and toolbar

Добавьте панель инструментов и команду меню, которая вызывает диалоговое окно открытия файла и воспроизводит выбранный файл мультимедиа. Add a toolbar and a menu command that invokes the Open File dialog and plays the selected media file.

Откройте фирсттулвиндов. CS и добавьте следующие using директивы: Open FirstToolWindow.cs and add the following using directives:

В классе Фирсттулвиндов добавьте открытую ссылку на элемент управления Фирсттулвиндовконтрол. Inside the FirstToolWindow class, add a public reference to the FirstToolWindowControl control.

Читайте также:  Восстановление windows 10 ошибка 0xc00002a

В конце конструктора присвойте этой переменной элемента управления только что созданный элемент управления. At the end of the constructor, set this control variable to the newly-created control.

Создайте экземпляр панели инструментов внутри конструктора. Instantiate the toolbar inside the constructor.

На этом этапе конструктор Фирсттулвиндов должен выглядеть следующим образом: At this point, the FirstToolWindow constructor should look like this:

Добавьте команду меню на панель инструментов. Add the menu command to the toolbar. В классе Фирсттулвиндовкомманд. cs добавьте следующую директиву using: In the FirstToolWindowCommand.cs class, add the following using directive:

В классе Фирсттулвиндовкомманд добавьте следующий код в конце метода Шовтулвиндов (). In the FirstToolWindowCommand class, add the following code at the end of the ShowToolWindow() method. Команда Буттонхандлер будет реализована в следующем разделе. The ButtonHandler command will be implemented in the next section.

Реализация команды меню в окне инструментов To implement a menu command in the tool window

В классе Фирсттулвиндовкомманд добавьте метод Буттонхандлер, который вызывает диалоговое окно открытия файла . In the FirstToolWindowCommand class, add a ButtonHandler method that invokes the Open File dialog. Если файл выбран, он воспроизводит файл мультимедиа. When a file has been selected, it plays the media file.

В классе Фирсттулвиндовкомманд добавьте закрытую ссылку на окно Фирсттулвиндов, которое создается в методе Финдтулвиндов (). In the FirstToolWindowCommand class, add a private reference to the FirstToolWindow window that gets created in the FindToolWindow() method.

Измените метод Шовтулвиндов (), чтобы задать определенное выше окно (чтобы обработчик команд Буттонхандлер мог получить доступ к элементу управления «окно». Change the ShowToolWindow() method to set the window you defined above (so that the ButtonHandler command handler can access the window control. Ниже приведен полный метод Шовтулвиндов (). Here is the complete ShowToolWindow() method.

Добавьте метод Буттонхандлер. Add the ButtonHandler method. Он создает OpenFileDialog для пользователя, чтобы указать файл мультимедиа для воспроизведения, а затем воспроизводит выбранный файл. It creates an OpenFileDialog for the user to specify the media file to play, and then plays the selected file.

Задание расположения по умолчанию для окна инструментов Set the default position for the tool window

Затем укажите расположение по умолчанию в интегрированной среде разработки для окна инструментов. Next, specify a default location in the IDE for the tool window. Сведения о конфигурации для окна инструментов находятся в файле фирсттулвиндовпаккаже. CS . Configuration information for the tool window is in the FirstToolWindowPackage.cs file.

В фирсттулвиндовпаккаже. CS найдите ProvideToolWindowAttribute атрибут FirstToolWindowPackage класса, который передает тип фирсттулвиндов в конструктор. In FirstToolWindowPackage.cs, find the ProvideToolWindowAttribute attribute on the FirstToolWindowPackage class, which passes the FirstToolWindow type to the constructor. Чтобы указать расположение по умолчанию, необходимо добавить дополнительные параметры в конструктор, как показано ниже. To specify a default position, you must add more parameters to the constructor following example.

Первый именованный параметр — Style , а его значение — Tabbed , то есть окно будет вкладкой в существующем окне. The first named parameter is Style and its value is Tabbed , which means that the window will be a tab in an existing window. Положение закрепления задается Window параметром n в данном случае — идентификатор GUID Обозреватель решений. The docking position is specified by the Window parameter, n this case, the GUID of the Solution Explorer.

Дополнительные сведения о типах окон в интегрированной среде разработки см. в разделе vsWindowType . For more information about the types of windows in the IDE, see vsWindowType.

Тестирование окна инструментов Test the tool window

Нажмите клавишу F5 , чтобы открыть новый экземпляр экспериментальной сборки Visual Studio. Press F5 to open a new instance of the Visual Studio experimental build.

В меню вид наведите указатель мыши на пункт другие окна и выберите пункт первое окно инструментов. On the View menu, point to Other Windows and then click First Tool Window.

Окно инструментов проигрывателя мультимедиа должно открываться в том же расположении, что и Обозреватель решений. The media player tool window should open in the same position as Solution Explorer. Если он по-прежнему отображается в том же расположении, что и ранее, сбросьте макет окна (окно или Сброс макета окна). If it still appears in the same position as before, reset the window layout (Window / Reset Window Layout).

Нажмите кнопку (она содержит значок поиска ) в окне инструментов. Click the button (it has the Search icon) in the tool window. Выберите поддерживаемый звуковой или видеофайл, например к:\виндовс\медиа\чимес.ВАВ, и нажмите кнопку Открыть. Select a supported sound or video file, for example, C:\windows\media\chimes.wav, then press Open.

Вы должны слышать звук подвеска. You should hear the chime sound.

Оцените статью