窗口管理
多窗口创建、IPC 通信和窗口间事件管理
概述
Linch Desktop Core 提供了完整的多窗口管理方案,包括窗口创建、窗口间通信和事件监听。
窗口管理 API
createWindow
创建一个新窗口。
import { createWindow } from '@linch-tech/desktop-core';
const editorWindow = await createWindow('editor', {
url: '/editor',
title: '编辑器',
width: 800,
height: 600,
center: true,
});签名
function createWindow(label: string, options?: WindowOptions): Promise<WebviewWindow>WindowOptions
| 字段 | 类型 | 默认值 | 说明 |
|---|---|---|---|
url | string | - | 窗口加载的 URL |
title | string | - | 窗口标题 |
width | number | - | 窗口宽度 |
height | number | - | 窗口高度 |
x | number | - | 窗口 X 坐标 |
y | number | - | 窗口 Y 坐标 |
resizable | boolean | true | 是否可调整大小 |
decorations | boolean | true | 是否显示系统装饰 |
center | boolean | false | 是否居中显示 |
getWindow
获取已有窗口的引用。
import { getWindow } from '@linch-tech/desktop-core';
const win = getWindow('editor');
if (win) {
await win.setFocus();
}closeWindowByLabel
关闭指定窗口。
import { closeWindowByLabel } from '@linch-tech/desktop-core';
await closeWindowByLabel('editor');getAllWindows
获取所有窗口列表。
import { getAllWindows } from '@linch-tech/desktop-core';
const windows = getAllWindows();
console.log(`当前打开 ${windows.length} 个窗口`);窗口间通信
sendToWindow
向指定窗口发送事件。
import { sendToWindow } from '@linch-tech/desktop-core';
await sendToWindow('editor', 'file-opened', {
path: '/data/document.txt',
content: '文件内容...',
});签名
function sendToWindow(label: string, event: string, payload: unknown): Promise<void>useWindowEvent
在 React 组件中监听来自其他窗口的事件,组件卸载时自动清理。
import { useWindowEvent } from '@linch-tech/desktop-core';
function EditorPage() {
useWindowEvent<{ path: string; content: string }>('file-opened', (payload) => {
setFilePath(payload.path);
setContent(payload.content);
});
return <div>...</div>;
}签名
function useWindowEvent<T = unknown>(
event: string,
handler: (payload: T) => void
): voiduseBroadcast
向所有窗口广播事件。
import { useBroadcast } from '@linch-tech/desktop-core';
function MainWindow() {
const { broadcast } = useBroadcast();
const handleThemeChange = async (theme: string) => {
await broadcast('theme-changed', { theme });
};
return <ThemeSwitcher onChange={handleThemeChange} />;
}签名
function useBroadcast(): {
broadcast: (event: string, payload: unknown) => Promise<void>;
}完整示例
import { createWindow, sendToWindow, useWindowEvent, useBroadcast } from '@linch-tech/desktop-core';
// 主窗口
function MainWindow() {
const { broadcast } = useBroadcast();
const openEditor = async () => {
await createWindow('editor', {
url: '/editor',
width: 800,
height: 600,
});
// 等窗口就绪后发送数据
setTimeout(() => {
sendToWindow('editor', 'load-file', { id: 123 });
}, 500);
};
return <button onClick={openEditor}>打开编辑器</button>;
}
// 编辑器窗口
function EditorWindow() {
const [fileId, setFileId] = useState<number | null>(null);
useWindowEvent<{ id: number }>('load-file', (payload) => {
setFileId(payload.id);
});
return <div>编辑文件 #{fileId}</div>;
}