visual-studio-codevscode-keybinding

Binding a terminal command to a keybind, how can I focus on the terminal?


I have a keybind that triggers a terminal command. The terminal command prompts for input, but in order to respond, I have to make an extra, unnecessary click to focus on the terminal. How can I avoid this so that when I trigger the keybind, the terminal command runs, and the VSCode focus automatically shifts to the terminal?

I found a solution, but I'd prefer not to press the keybind twice in a row; though it's still better than using the keybind and then clicking.

tasks.json

{
  "tasks": [
    {
      "label": "Run Example Command",
      "type": "shell",
      "command": "powershell",
      "args": [
        "..."
      ],
      "windows": {
        "command": "powershell",
        "args": [
          "..."
        ]
      }
    }
  ]
}

keybindings.json

{
  {
    "key": "f4",
    "command": "workbench.action.tasks.runTask",
    "args": "Run Example Command"
  },
  {
    "key": "f4",
    "command": "workbench.action.terminal.focus",
    "when": "taskRunning"
  },
}

How can I make the terminal receive focus on the first F4 press?

Update Illustration

By default what my problem With @Mark's second solution
can't give focus to terminal after started PS script use tasks.*.presentation.{focus, reveal}

Solution

  • There may be two solutions - which I can't test without your actual powershell command and args.

    Combine your commands into one keybinding using the runCommands command:

    {
      "key": "alt+c",
      "command": "runCommands",
      "args": {
        "commands": [
          {
            "command": "workbench.action.tasks.runTask",
            "args": "echo"
          },
          "workbench.action.terminal.focus"
        ]
      }
    }
    

    Or try adding presentation options to your task:

      "tasks": [
        {
          "label": "echo",
          "type": "shell",
          "command": "powershell",
          "args":
            [...],
          "presentation": {
            "echo": true,
            "reveal": "always",    // note
            "focus": true,         // see if this works
            "panel": "new",
            "showReuseMessage": false,
            "clear": true
          }
        }
      ],