แก้ไข

แชร์ผ่าน


Add custom keyboard shortcuts to your Office Add-ins

Keyboard shortcuts, also known as key combinations, make it possible for your add-in's users to work more efficiently. Keyboard shortcuts also improve the add-in's accessibility for users with disabilities by providing an alternative to the mouse.

There are three steps to add keyboard shortcuts to an add-in.

  1. Configure the add-in's manifest to use a shared runtime.
  2. Define custom keyboard shortcuts and the actions they'll run.
  3. Map custom actions to their functions using the Office.actions.associate API.

Prerequisites

Keyboard shortcuts are currently only supported in the following platforms and build of Excel and Word.

  • Office on the web

    Note

    The keyboard shortcut feature is currently being rolled out to Word on the web. If you test the feature in Word on the web at this time, the shortcuts may not work if they're activated from within the add-in's task pane. We recommend to periodically check Keyboard Shortcuts requirement sets to find out when the feature is fully supported.

  • Office on Windows

    • Excel: Version 2102 (Build 13801.20632) and later
    • Word: Version 2408 (Build 17928.20114) and later
  • Office on Mac

    • Excel: Version 16.55 (21111400) and later
    • Word: Version 16.88 (24081116) and later

Additionally, keyboard shortcuts only work on platforms that support the following requirement sets. For information about requirement sets and how to work with them, see Specify Office applications and API requirements.

Tip

To start with a working version of an add-in with keyboard shortcuts already configured, clone and run the Use keyboard shortcuts for Office Add-in actions sample. When you're ready to add keyboard shortcuts to your own add-in, continue with this article.

Define custom keyboard shortcuts

The process to define custom keyboard shortcuts for your add-in varies depending on the type of manifest your add-in uses. Select the tab for the type of manifest you're using.

Tip

To learn more about manifests for Office Add-ins, see Office Add-ins manifest.

Note

Implementing keyboard shortcuts with the unified app manifest for Microsoft 365 is in public developer preview. This shouldn't be used in production add-ins. We invite you to try it out in test or development environments. For more information, see the Public developer preview app manifest schema.

If your add-in uses the unified app manifest for Microsoft 365, custom keyboard shortcuts and their actions are defined in the manifest.

  1. In your add-in project, open the manifest.json file.

  2. Add the following object to the "extensions.runtimes" array. Note the following about this markup.

    • The "actions" objects specify the functions your add-in can run. In the following example, an add-in will be able to show and hide a task pane. You'll create these functions in a later section. Currently, custom keyboard shortcuts can only run actions that are of type "executeFunction".
    • While the "actions.displayName" property is optional, it's required if a custom keyboard shortcut will be created for the action. This property is used to describe the action of a keyboard shortcut. The description you provide appears in the dialog that's shown to a user when there's a shortcut conflict between multiple add-ins or with Microsoft 365. Office appends the name of the add-in in parentheses at the end of the description. For more information on how conflicts with keyboard shortcuts are handled, see Avoid key combinations in use by other add-ins.
    "runtimes": [
        {
            "id": "TaskPaneRuntime",
            "type": "general",
            "code": {
                "page": "https://localhost:3000/taskpane.html"
            },
            "lifetime": "long",
            "actions": [
                {
                    "id": "ShowTaskpane",
                    "type": "executeFunction",
                    "displayName": "Show task pane (Contoso Add-in)"
                },
                {
                    "id": "HideTaskpane",
                    "type": "executeFunction",
                    "displayName": "Hide task pane (Contoso Add-in)"
                }
            ],
        }
    ]
    
  3. Add the following to the "extensions" array. Note the following about the markup.

    • The SharedRuntime 1.1 requirement set is specified in the "requirements.capabilities" object to support custom keyboard shortcuts.
    • Each "shortcuts" object represents a single action that's invoked by a keyboard shortcut. It specifies the supported key combinations for various platforms, such as Office on the web, on Windows, and on Mac. For guidance on how to create custom key combinations, see Guidelines for custom key combinations.
    • A default key combination must be specified. It's used on all supported platforms if there isn't a specific combination configured for a particular platform.
    • The value of the "actionId" property must match the value specified in the "id" property of the applicable "extensions.runtimes.actions" object.
    "keyboardShortcuts": [
        {
            "requirements": {
                "capabilities": [
                    {
                        "name": "SharedRuntime",
                        "minVersion": "1.1"
                    }
                ]
            },
            "shortcuts": [
                {
                    "key": {
                        "default": "Ctrl+Alt+Up",
                        "mac": "Command+Shift+Up",
                        "web": "Ctrl+Alt+1",
                        "windows": "Ctrl+Alt+Up"
                    },
                    "actionId": "ShowTaskpane"
                },
                {
                    "key": {
                        "default": "Ctrl+Alt+Down",
                        "mac": "Command+Shift+Down",
                        "web": "Ctrl+Alt+2",
                        "windows": "Ctrl+Alt+Up"
                    },
                    "actionId": "HideTaskpane"
                }
            ]
        }
    ]
    

Map custom actions to their functions

  1. In your project, open the JavaScript file loaded by your HTML page in the <FunctionFile> element.

  2. In the JavaScript file, use the Office.actions.associate API to map each action you specified in an earlier step to a JavaScript function. Add the following JavaScript to the file. Note the following about the code.

    • The first parameter is the name of an action that you mapped to a keyboard shortcut. The location of the name of the action depends on the type of manifest your add-in uses.
      • Unified app manifest for Microsoft 365: The value of the "extensions.keyboardShortcuts.shortcuts.actionId" property in the manifest.json file.
      • Add-in only manifest: The value of the "actions.id" property in the shortcuts JSON file.
    • The second parameter is the function that runs when a user presses the key combination that's mapped to an action.
    Office.actions.associate("ShowTaskpane", () => {
        return Office.addin.showAsTaskpane()
            .then(() => {
                return;
            })
            .catch((error) => {
                return error.code;
            });
    });
    
    Office.actions.associate("HideTaskpane", () => {
        return Office.addin.hide()
            .then(() => {
                return;
            })
            .catch((error) => {
                return error.code;
            });
    });
    

Guidelines for custom key combinations

Use the following guidelines to create custom key combinations for your add-ins.

  • A keyboard shortcut must include at least one modifier key (Alt/Option, Ctrl/Cmd, Shift) and only one other key. These keys must be joined with a + character.
  • The Cmd modifier key is supported on the macOS platform.
  • On macOS, the Alt key is mapped to the Option key. On Windows, the Cmd key is mapped to the Ctrl key.
  • The Shift key can't be used as the only modifier key. It must be combined with either Alt/Option or Ctrl/Cmd.
  • Key combinations can include characters "A-Z", "a-z", "0-9", and the punctuation marks "-", "_", and "+". By convention, lowercase letters aren't used in keyboard shortcuts.
  • When two characters are linked to the same physical key on a standard keyboard, then they're synonyms in a custom keyboard shortcut. For example, Alt+a and Alt+A are the same shortcut, as well as Ctrl+- and Ctrl+_ ("-" and "_" are linked to the same physical key).

Note

Custom keyboard shortcuts must be pressed simultaneously. KeyTips, also known as sequential key shortcuts (for example, Alt+H, H), aren't supported in Office Add-ins.

Browser shortcuts that can't be overridden

When using custom keyboard shortcuts on the web, some keyboard shortcuts that are used by the browser can't be overridden by add-ins. The following list is a work in progress. If you discover other combinations that can't be overridden, please let us know by using the feedback tool at the bottom of this page.

  • Ctrl+N
  • Ctrl+Shift+N
  • Ctrl+T
  • Ctrl+Shift+T
  • Ctrl+W
  • Ctrl+PgUp/PgDn

Avoid key combinations in use by other add-ins

There are many keyboard shortcuts that are already in use by Microsoft 365. Avoid registering keyboard shortcuts for your add-in that are already in use. However, there may be some instances where it's necessary to override existing keyboard shortcuts or handle conflicts between multiple add-ins that have registered the same keyboard shortcut.

In the case of a conflict, the user will see a dialog box the first time they attempt to use a conflicting keyboard shortcut. Note that the source of the text for the add-in option that's displayed in this dialog varies depending on the type of manifest your add-in uses. - Unified app manifest for Microsoft 365: The value of the "extensions.runtimes.actions.displayName" property in the manifest.json file. - Add-in only manifest: The value of the "actions.name" property in the shortcuts JSON file.

A conflict modal with two different actions for a single shortcut.

The user can select which action the keyboard shortcut will take. After making the selection, the preference is saved for future uses of the same shortcut. The shortcut preferences are saved per user, per platform. If the user wishes to change their preferences, they can invoke the Reset Office Add-ins shortcut preferences command from the Tell me search box. Invoking the command clears all of the user's add-in shortcut preferences and the user will again be prompted with the conflict dialog box the next time they attempt to use a conflicting shortcut.

The Tell me search box in Excel showing the reset Office Add-in shortcut preferences action.

For the best user experience, we recommend that you minimize keyboard shortcut conflicts with these good practices.

  • Use only keyboard shortcuts with the following pattern: Ctrl+Shift+Alt+x, where x is some other key.
  • Avoid using established keyboard shortcuts in Excel and Word. For a list, see the following:
  • When the keyboard focus is inside the add-in UI, Ctrl+Space and Ctrl+Shift+F10 won't work as these are essential accessibility shortcuts.
  • On a Windows or Mac computer, if the Reset Office Add-ins shortcut preferences command isn't available on the search menu, the user can manually add the command to the ribbon by customizing the ribbon through the context menu.

Localize the description of a keyboard shortcut

You may need to localize your custom keyboard shortcuts in the following scenarios.

  • Your add-in supports multiple locales.
  • Your add-in supports different alphabets, writing systems, or keyboard layouts.

Guidance on how to localize your keyboard shortcuts varies depending on the type of manifest your add-in uses.

To learn how to localize your custom keyboard shortcuts with the unified app manifest for Microsoft 365, see Localize strings in your app manifest.

Turn on shortcut customization for specific users

Note

The APIs described in this section require the KeyboardShortcuts 1.1 requirement set.

Users of your add-in can reassign the actions of the add-in to alternate keyboard combinations.

Use the Office.actions.replaceShortcuts method to assign a user's custom keyboard combinations to your add-ins actions. The method takes a parameter of type {[actionId:string]: string|null}, where the actionIds are a subset of the action IDs that must be defined in the add-in's extended manifest JSON. The values are the user's preferred key combinations. The value can also be null, which will remove any customization for that actionId and revert to the specified default keyboard combination.

If the user is logged into Microsoft 365, the custom combinations are saved in the user's roaming settings per platform. Customizing shortcuts aren't currently supported for anonymous users.

const userCustomShortcuts = {
    ShowTaskpane: "Ctrl+Shift+1",
    HideTaskpane: "Ctrl+Shift+2"
};

Office.actions.replaceShortcuts(userCustomShortcuts)
    .then(() => {
        console.log("Successfully registered shortcut.");
    })
    .catch((error) => {
        if (error.code == "InvalidOperation") {
            console.log("ActionId doesn't exist or shortcut combination is invalid.");
        }
    });

To find out what shortcuts are already in use for the user, call the Office.actions.getShortcuts method. This method returns an object of type [actionId:string]:string|null}, where the values represent the current keyboard combination the user must use to invoke the specified action. The values can come from three different sources.

  • If there was a conflict with the shortcut and the user has chosen to use a different action (either native or another add-in) for that keyboard combination, the value returned will be null since the shortcut has been overridden and there's no keyboard combination the user can currently use to invoke that add-in action.
  • If the shortcut has been customized using the Office.actions.replaceShortcuts method, the value returned will be the customized keyboard combination.
  • If the shortcut hasn't been overridden or customized, the value returned varies depending on the type of manifest the add-in uses.
    • Unified app manifest for Microsoft 365: The shortcut specified in the manifest.json file of the add-in.
    • Add-in only manifest: The shortcut specified in the shortcuts JSON file of the add-in.

The following is an example.

Office.actions.getShortcuts()
    .then((userShortcuts) => {
       for (const action in userShortcuts) {
           let shortcut = userShortcuts[action];
           console.log(action + ": " + shortcut);
       }
    });

As described in Avoid key combinations in use by other add-ins, it's a good practice to avoid conflicts in shortcuts. To discover if one or more key combinations are already in use, pass them as an array of strings to the Office.actions.areShortcutsInUse method. The method returns a report containing key combinations that are already in use in the form of an array of objects of type {shortcut: string, inUse: boolean}. The shortcut property is a key combination, such as "Ctrl+Shift+1". If the combination is already registered to another action, the inUse property is set to true. For example, [{shortcut: "Ctrl+Shift+1", inUse: true}, {shortcut: "Ctrl+Shift+2", inUse: false}]. The following code snippet is an example.

const shortcuts = ["Ctrl+Shift+1", "Ctrl+Shift+2"];
Office.actions.areShortcutsInUse(shortcuts)
    .then((inUseArray) => {
        const availableShortcuts = inUseArray.filter((shortcut) => {
            return !shortcut.inUse;
        });
        console.log(availableShortcuts);
        const usedShortcuts = inUseArray.filter((shortcut) => {
            return shortcut.inUse;
        });
        console.log(usedShortcuts);
    });

Implement custom keyboard shortcuts across supported Microsoft 365 apps

You can implement a custom keyboard shortcut to be used across supported Microsoft 365 apps, such as Excel and Word. If the implementation to perform the same task is different on each app, you must use the Office.actions.associate method to call a different callback function for each app. The following code is an example.

const host = Office.context.host;
if (host === Office.HostType.Excel) {
    Office.actions.associate("ChangeFormat", changeFormatExcel);
} else if (host === Office.HostType.Word) {
    Office.actions.associate("ChangeFormat", changeFormatWord);
}
...

See also