在启用扩展时,如何默认执行VS代码命令?

发布于 2025-02-07 20:37:39 字数 1159 浏览 1 评论 0原文

当在VS代码中启用扩展时,如何默认执行命令?

我正在创建我的第一个VS代码扩展名,并且我创建了一个命令,但是它仅在命令调色板中可执行。

在VS代码中启用后,如何使其立即执行?

let myStatusBarItem: vscode.StatusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left,0);

export function activate(context: vscode.ExtensionContext) {
    let countLines = vscode.commands.registerCommand('line-counter.countLines', () => {
        vscode.window.showInformationMessage('Hello from line-counter');
    });

    context.subscriptions.push(countLines);
    context.subscriptions.push(myStatusBarItem);
    updateStatusBarItem();
}

function updateStatusBarItem(): void {
    const n = getNumberOfSelectedLines(vscode.window.activeTextEditor);
    if (n > 0) {
        myStatusBarItem.text = `$(megaphone) ${n} line(s) selected`;
        myStatusBarItem.show();
    } else {
        myStatusBarItem.hide();
    }
}

function getNumberOfSelectedLines(editor: vscode.TextEditor | undefined): number {
    let lines = 0;
    if (editor) {
        lines = editor.selections.reduce((prev, curr) => prev + (curr.end.line - curr.start.line), 0);
    }
    return lines;
}

How to make a command be executed by default when extension enabled in VS Code?

I am creating my first VS Code extension and I have created a command but it is only executable from the command palette.

How do I make it execute as soon as it is enabled in VS Code?

let myStatusBarItem: vscode.StatusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left,0);

export function activate(context: vscode.ExtensionContext) {
    let countLines = vscode.commands.registerCommand('line-counter.countLines', () => {
        vscode.window.showInformationMessage('Hello from line-counter');
    });

    context.subscriptions.push(countLines);
    context.subscriptions.push(myStatusBarItem);
    updateStatusBarItem();
}

function updateStatusBarItem(): void {
    const n = getNumberOfSelectedLines(vscode.window.activeTextEditor);
    if (n > 0) {
        myStatusBarItem.text = `$(megaphone) ${n} line(s) selected`;
        myStatusBarItem.show();
    } else {
        myStatusBarItem.hide();
    }
}

function getNumberOfSelectedLines(editor: vscode.TextEditor | undefined): number {
    let lines = 0;
    if (editor) {
        lines = editor.selections.reduce((prev, curr) => prev + (curr.end.line - curr.start.line), 0);
    }
    return lines;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

音栖息无 2025-02-14 20:37:39

激活函数最高级别的任何内容都将在激活时调用。

Anything on the top level of the activation function will be called on activation.

We do this at watermelon for our activity bar object.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文