我尝试通过窗口菜单创建新的应用程序窗口。但我遇到了这个方法的问题
创建窗口
不可用
我该怎么做?
#![cfg_attr(
all(not(debug_assertions), target_os = "windows"),
windows_subsystem = "windows"
)]
use tauri::{Menu, WindowMenuEvent, Wry, Submenu, CustomMenuItem, WindowUrl, WindowBuilder};
pub fn create() -> Menu {
let test_menu = Menu::new()
.add_item(CustomMenuItem::new("new_window", "Create new window"));
Menu::new()
.add_submenu(Submenu::new("Test", test_menu))
}
pub fn handler(event: WindowMenuEvent<Wry>) {
match event.menu_item_id() {
"new_window" => {
let mut window = event.window().clone();
}
_ => {}
}
}
fn main() {
tauri::Builder::default()
.menu(create())
.on_menu_event(handler)
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
我在事件中创建了菜单并克隆了主窗口(我需要创建相同的窗口)
您不能简单地“克隆”旧窗口。这将违背 Tauri 的方法,即所有窗口必须是唯一的(每个窗口都有一个唯一的 id!)。当您使用
.clone()
时,您仅克隆一个包含窗口所有相关数据的结构。但是,此克隆未以任何方式向应用程序注册,因此当您对其调用 .show()
时,它不会显示。
再次创建第二个窗口(具有相同内容!)的正确方法是使用
WindowBuilder
构建一个窗口。您可以获取 AppHandle
的 WindowBuilder
克隆,用于创建新窗口并将其注册到应用程序中。您必须为 WindowBuilder 提供唯一的 ID(如果您不需要跟踪特定窗口,则可以使用随机数。为此,请使用 rand
板条箱)。
一个简单的例子如下所示:
use tauri::{Manager, WindowBuilder};
pub fn handler(event: WindowMenuEvent<Wry>) {
match event.menu_item_id() {
"new_window" => {
// Get the underlying AppHandle
let app_handle = event.window().app_handle();
// Generate random number, then turn it into a String
let random_number = rand::random::<i64>().to_string();
// Build a new Window struct
// The HTML file to use depends on which contents should be presented
// The main window is usually "index.html"
let window = WindowBuilder::new(&app_handle, random_number, tauri::WindowUrl::App("YOURPAGE.html".into()))
// Any additional window configuration here
.build()
.expect("Failed to create window.");
// Show the window
window.show().expect("Failed to show window.");
}
_ => {}
}
}
如果您需要在大小、位置等方面匹配现有窗口,您可以使用
event.window().inner_size()
等检索旧窗口的配置。
然后,您需要在我评论的步骤中应用这些// Any additional window configuration here
。