Skip to content
Tauri 中文网

单个实例

GitHub crates.io
API Reference

使用单实例插件确保你的 tauri 应用一次只运行一个实例。

¥Ensure that a single instance of your tauri app is running at a time using the Single Instance Plugin.

支持的平台

¥Supported Platforms

This plugin requires a Rust version of at least 1.77.2

Platform Level Notes
windows
linux
macos
android
ios

设置

¥Setup

安装单实例插件以开始使用。

¥Install the Single Instance plugin to get started.

使用项目的包管理器添加依赖:

¥Use your project’s package manager to add the dependency:

npm run tauri add single-instance

使用

¥Usage

插件已安装并初始化,应该可以立即正常运行。尽管如此,我们也可以使用 init() 方法增强其功能。

¥The plugin is already installed and initialized, and it should be functioning correctly right away. Nevertheless, we can also enhance its functionality with the init() method.

插件 init() 方法采用闭包,当启动新的应用实例但由插件关闭时调用该闭包。闭包有三个参数:

¥The plugin init() method takes a closure that is invoked when a new app instance was started, but closed by the plugin. The closure has three arguments:

  1. app:应用的 AppHandle

    ¥app: The AppHandle of the application.

  2. args:用户传递的用于启动此新实例的参数列表。

    ¥args: The list of arguments, that was passed by the user to initiate this new instance.

  3. cwd:当前工作目录表示启动新应用实例的目录。

    ¥cwd: The Current Working Directory denotes the directory from which the new application instance was launched.

因此,闭包应如下所示

¥So, the closure should look like below

.plugin(tauri_plugin_single_instance::init(|app, args, cwd| {
// Write your code here...
}))

专注于新实例

¥Focusing on New Instance

默认情况下,当你在应用已运行时启动新实例时,不会采取任何行动。要在用户尝试打开新实例时聚焦正在运行的实例的窗口,请按如下方式更改回调闭包:

¥By default, when you initiate a new instance while the application is already running, no action is taken. To focus the window of the running instance when user tries to open a new instance, alter the callback closure as follows:

src-tauri/src/lib.rs
use tauri::{AppHandle, Manager};
pub fn run() {
let mut builder = tauri::Builder::default();
#[cfg(desktop)]
{
builder = builder.plugin(tauri_plugin_single_instance::init(|app, args, cwd| {
let _ = app.get_webview_window("main")
.expect("no main window")
.set_focus();
}));
}
builder
.run(tauri::generate_context!())
.expect("error while running tauri application");
}

Tauri v2.4 中文网 - 粤ICP备13048890号
Nodejs.cn 旗下网站