|
1 | 1 | ---
|
2 |
| -title: Menus and commands |
| 2 | +title: Menus & commands |
3 | 3 | date: 2021-5-24
|
4 | 4 | ---
|
5 | 5 |
|
6 |
| -TBD |
| 6 | +Commands are most often used as buttons in menus around Visual Studio. To create a command requires two steps: |
| 7 | + |
| 8 | +1. Define the command |
| 9 | +2. Handle the click/invocation |
| 10 | + |
| 11 | +## Define the command |
| 12 | +Every button in every menu is a command. To add a command to your extension, you must define it in the .vsct file first. It could look something like this: |
| 13 | + |
| 14 | +```xml |
| 15 | +<Buttons> |
| 16 | + <Button guid="MyPackage" id="MyCommand" priority="0x0105" type="Button"> |
| 17 | + <Parent guid="VSMainMenu" id="View.DevWindowsGroup.OtherWindows.Group1"/> |
| 18 | + <Icon guid="ImageCatalogGuid" id="StatusInformation" /> |
| 19 | + <CommandFlag>IconIsMoniker</CommandFlag> |
| 20 | + <Strings> |
| 21 | + <ButtonText>R&unner Window</ButtonText> |
| 22 | + </Strings> |
| 23 | + </Button> |
| 24 | +</Buttons> |
| 25 | +``` |
| 26 | + |
| 27 | +This button is placed in the parent group located in the **View -> Other Windows** menu as specified in the `Parent` element. |
| 28 | + |
| 29 | +You can now run the extension now to see if the command shows up in the right location and menu. |
| 30 | + |
| 31 | +## Handle the click/invocations |
| 32 | +Once the button is defined, we need to handle what happens when it is invoked. We do that in a C# class that looks like this: |
| 33 | + |
| 34 | +```csharp |
| 35 | +[Command("489ba882-f600-4c8b-89db-eb366a4ee3b3", 0x0100)] |
| 36 | +public class MyCommand : BaseCommand<TestCommand> |
| 37 | +{ |
| 38 | + protected override Task ExecuteAsync(OleMenuCmdEventArgs e) |
| 39 | + { |
| 40 | + // Do something |
| 41 | + } |
| 42 | +} |
| 43 | +``` |
| 44 | + |
| 45 | +Make sure to call it from your `Package` class's `InitializeAsync` method. |
| 46 | + |
| 47 | +```csharp |
| 48 | +protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress) |
| 49 | +{ |
| 50 | + await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); |
| 51 | + |
| 52 | + await MyCommand.InitializeAsync(this); |
| 53 | + } |
| 54 | +``` |
| 55 | + |
| 56 | +The command Guid and ID must match the guid/id pair from `Button` element in the .vsct file |
0 commit comments