---
url: /guide/desktop/skills/create-electron-window.md
---
# 极达办公项目 Electron 窗体创建指南

本指南说明在极达办公项目中创建新 Electron 窗口的标准步骤和文件结构。

***

## 一、窗体创建标准流程

以创建一个名为 `image-preview`（图片预览）的窗口为例：

### 1. 创建 HTML 入口文件

**文件位置**: `packages/electron-host/windows/{window-name}.html`

**示例**: `windows/image-preview.html`

```html
<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" href="/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta
      http-equiv="Content-Security-Policy"
      content="default-src 'self' http://localhost:* http://127.0.0.1:* ws://localhost:* limapp://*; 
               script-src 'self' 'unsafe-eval' 'unsafe-inline' http://localhost:* http://127.0.0.1:* ws://localhost:* limapp://*; 
               style-src 'self' 'unsafe-inline' http://localhost:* http://127.0.0.1:* limapp://*; 
               img-src 'self' data: blob: http://localhost:* http://127.0.0.1:* limapp://* https://*; 
               font-src 'self' data: http://localhost:* http://127.0.0.1:* limapp://*; 
               connect-src 'self' http://localhost:* http://127.0.0.1:* ws://localhost:* wss://* limapp://* https://*;"
    />
    <title>图片预览</title>
  </head>
  <body>
    <div id="app"></div>
    <script type="module" src="/src/renderer/apps/image-preview/main.ts"></script>
  </body>
</html>
```

***

### 2. 创建 Vue 渲染进程

**目录位置**: `packages/electron-host/src/renderer/apps/{window-name}/`

**文件结构**:

```
src/renderer/apps/image-preview/
  ├── main.ts              # Vue 入口
  ├── App.vue              # 根组件
  ├── WindowLayout.vue     # 通用窗口布局组件
  ├── ImagePreviewView.vue # 业务视图组件
  └── app.config.json      # (可选) 应用配置
```

#### 2.1 main.ts

```ts
import { createApp } from "vue";
import ElementPlus from "element-plus";
import "element-plus/dist/index.css";

import "virtual:uno.css";
import "../../assets/main.css";

import App from "./App.vue";
import { setupStore } from "@lim/src/store";
import { initToken } from "@lim/src/utils/token";
import "@lim/base";

const app = createApp(App);

setupStore(app);
app.use(ElementPlus);

initToken()
  .then(() => {
    app.mount("#app");
  })
  .catch(() => {
    app.mount("#app");
  });
```

#### 2.2 App.vue

```vue
<template>
  <ImagePreviewView />
</template>

<script setup lang="ts">
import ImagePreviewView from "./ImagePreviewView.vue";
</script>
```

#### 2.3 WindowLayout.vue（通用窗口布局组件）

**文件位置**: `src/renderer/apps/{window-name}/WindowLayout.vue`

提供统一的窗口布局，支持标题栏、窗口控制按钮和插槽扩展。

````vue
<template>
  <div class="window-layout">
    <div
      class="title-bar"
      :style="{
        background: titleBarBg,
        borderBottom: showBorder ? '1px solid var(--el-border-color)' : 'none',
      }"
    >
      <div class="title-bar-left">
        <slot name="title">
          <span v-if="title" class="title-bar-title">{{ title }}</span>
        </slot>
      </div>
      <div class="title-bar-right">
        <slot name="controls">
          <template v-if="showControls">
            <div v-if="showDivider" class="divider"></div>
            <button type="button" class="window-control-btn" @click="handleMinimize" title="最小化">
              <slot name="minimize-icon">
                <div v-html="Minimize" class="svg-icon"></div>
              </slot>
            </button>
            <button
              type="button"
              class="window-control-btn"
              @click="handleMaximize"
              :title="isMaximized ? '还原' : '最大化'"
            >
              <slot name="maximize-icon">
                <div v-html="isMaximized ? Shrink : Maximize" class="svg-icon"></div>
              </slot>
            </button>
            <button
              type="button"
              class="window-control-btn close-btn"
              @click="handleClose"
              title="关闭"
            >
              <slot name="close-icon">
                <div v-html="Close" class="svg-icon"></div>
              </slot>
            </button>
          </template>
        </slot>
      </div>
    </div>
    <div class="window-content">
      <slot></slot>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from "vue";

// 最小化图标
const Minimize = `<svg xmlns="http://www.w3.org/2000/svg" class="icon" viewBox="0 0 1024 1024"><path fill="currentColor" d="M929.8 528.1H93.5c-15.5 0-28-12.5-28-28s12.5-28 28-28h836.3c15.5 0 28 12.5 28 28s-12.5 28-28 28"/></svg>`;

// 最大化图标
const Maximize = `<svg xmlns="http://www.w3.org/2000/svg" class="icon" viewBox="0 0 1024 1024"><path fill="currentColor" d="M812.3 959.4H213.7c-81.6 0-148-66.4-148-148V212.9c0-81.6 66.4-148 148-148h598.5c81.6 0 148 66.4 148 148v598.5c.1 81.6-66.3 148-147.9 148M213.7 120.9c-50.7 0-92 41.3-92 92v598.5c0 50.7 41.3 92 92 92h598.5c50.7 0 92-41.3 92-92V212.9c0-50.7-41.3-92-92-92z"/></svg>`;

// 还原图标
const Shrink = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024"><path fill="currentColor" d="M812.2 65H351.6c-78.3 0-142.5 61.1-147.7 138.1-77 5.1-138.1 69.4-138.1 147.7v460.6c0 81.6 66.4 148 148 148h460.6c78.3 0 142.5-61.1 147.7-138.1 77-5.1 138.1-69.4 138.1-147.7V213c0-81.6-66.4-148-148-148m-45.8 746.3c0 50.7-41.3 92-92 92H213.8c-50.7 0-92-41.3-92-92V350.7c0-50.7 41.3-92 92-92h460.6c50.7 0 92 41.3 92 92zm137.8-137.7c0 47.3-35.8 86.3-81.8 91.4V350.7c0-81.6-66.4-148-148-148H260.2c5.1-45.9 44.2-81.8 91.4-81.8h460.6c50.7 0 92 41.3 92 92z"/></svg>`;

// 关闭图标
const Close = `<svg xmlns="http://www.w3.org/2000/svg" class="icon" viewBox="0 0 1024 1024"><path fill="currentColor" d="M96.6 915c-10.9-10.9-10.9-28.7 0-39.6L887 85c10.9-10.9 28.7-10.9 39.6 0s10.9 28.7 0 39.6L136.2 915c-10.9 10.9-28.6 10.9-39.6 0"/><path fill="currentColor" d="M887 915 96.6 124.6c-10.9-10.9-10.9-28.7 0-39.6s28.7-10.9 39.6 0l790.4 790.4c10.9 10.9 10.9 28.7 0 39.6s-28.6 10.9-39.6 0"/></svg>`;

withDefaults(
  defineProps<{
    title?: string;
    showControls?: boolean;
    showBorder?: boolean;
    showDivider?: boolean;
    titleBarBg?: string;
  }>(),
  {
    title: "",
    showControls: true,
    showBorder: true,
    showDivider: false,
    titleBarBg: "",
  },
);

const isMaximized = ref(false);

const handleWindowMaximized = (_event: unknown, maximized: boolean) => {
  isMaximized.value = maximized;
};

function handleMinimize() {
  window.ipcRenderer?.invoke("minimize-window");
}

function handleMaximize() {
  window.ipcRenderer?.invoke("maximize-window").then((maximized: boolean) => {
    isMaximized.value = maximized;
  });
}

function handleClose() {
  window.ipcRenderer?.invoke("close-window");
}

onMounted(() => {
  window.ipcRenderer?.on("window-maximized", handleWindowMaximized);
});

onUnmounted(() => {
  window.ipcRenderer?.off("window-maximized", handleWindowMaximized);
});
</script>

<style scoped lang="scss">
.title-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 40px;
  padding: 0 0 0 12px;
  -webkit-app-region: drag;
}

.window-layout {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  background: var(--el-bg-color);
  overflow: hidden;
}

.title-bar-left {
  display: flex;
  align-items: center;
  flex: 1;
  min-width: 0;
}

.title-bar-title {
  font-size: 14px;
  font-weight: 500;
  color: var(--el-text-color-primary);
}

.title-bar-right {
  display: flex;
  align-items: center;
  flex-shrink: 0;
  -webkit-app-region: no-drag;
}

.divider {
  width: 1px;
  height: 24px;
  background: var(--el-border-color);
  margin: 0 8px;
}

.window-control-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  border: none;
  background: transparent;
  color: var(--el-text-color-primary);
  cursor: pointer;
  transition: all 0.2s;

  &:hover {
    background: var(--el-fill-color);
  }

  &.close-btn:hover {
    background: #e81123;
    color: #ffffff;
  }
}

.window-content {
  flex: 1;
  overflow: hidden;
}

.svg-icon {
  width: 18px;
  height: 18px;
  color: currentColor;
}
</style>

**WindowLayout Props:** | 属性 | 类型 | 默认值 | 说明 | |------|------|--------|------| | `title` |
`string` | `''` | 窗口标题 | | `showControls` | `boolean` | `true` | 是否显示窗口控制按钮 | |
`showBorder` | `boolean` | `true` | 是否显示底部边框分隔线 | | `showDivider` | `boolean` | `false` |
是否在控制按钮前显示分隔线 | | `titleBarBg` | `string` | `''` | 标题栏背景色 | **WindowLayout
Slots:** | 插槽名 | 说明 | |--------|------| | `default` | 主体内容区域 | | `title` |
自定义标题区域（覆盖默认 `title` 属性） | | `controls` | 自定义右侧控制区域（覆盖默认控制按钮） | |
`minimize-icon` | 自定义最小化图标 | | `maximize-icon` | 自定义最大化/还原图标 | | `close-icon` |
自定义关闭图标 | #### 2.4 ImagePreviewView.vue（业务视图示例） ```vue
<template>
  <WindowLayout title="图片预览" :show-controls="true">
    <!-- 自定义标题区域 -->
    <template #title>
      <div class="toolbar-left">
        <button type="button" class="tool-btn" @click="handleZoomOut" title="缩小">
          <div v-html="ZoomOut" class="svg-icon"></div>
        </button>
        <button type="button" class="tool-btn" @click="handleReset" title="原图">
          <div v-html="Refresh" class="svg-icon"></div>
        </button>
        <button type="button" class="tool-btn" @click="handleZoomIn" title="放大">
          <div v-html="ZoomIn" class="svg-icon"></div>
        </button>
        <button type="button" class="tool-btn" @click="handleRotateRight" title="向右旋转">
          <div v-html="RotateRight" class="svg-icon"></div>
        </button>
        <button type="button" class="tool-btn" @click="handleDownload" title="下载保存">
          <div v-html="Download" class="svg-icon"></div>
        </button>
      </div>
    </template>
    <!-- 主体内容插槽 -->
    <div class="image-preview-content" @wheel.prevent="handleWheel">
      <div class="image-wrapper" :style="imageWrapperStyle" @mousedown="handleMouseDown">
        <img v-if="currentUrl" :src="currentUrl" class="preview-image" draggable="false" />
      </div>
    </div>
  </WindowLayout>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from "vue";
import WindowLayout from "./WindowLayout.vue";

// ... 业务逻辑
</script>

<style scoped lang="scss">
.toolbar-left {
  display: flex;
  align-items: center;
  gap: 4px;
}

.tool-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 36px;
  height: 40px;
  border: none;
  background: transparent;
  color: var(--el-text-color-primary);
  cursor: pointer;
  transition: all 0.2s;

  &:hover:not(:disabled) {
    background: var(--el-fill-color);
  }
}

.image-preview-content {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  cursor: move;
  background: var(--el-fill-color-light);
  user-select: none;
}

.image-wrapper {
  transition: transform 0.1s ease-out;
  transform-origin: center center;
}

.preview-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
  user-select: none;
  pointer-events: none;
}
</style>
````

***

### 3. 创建 BrowserWindow 工厂

**文件位置**: `packages/electron-host/src/main/windows/{window-name}-window.ts`

**示例**: `src/main/windows/image-preview-window.ts`

```ts
import { BrowserWindow, screen } from "electron";
import path from "node:path";
import { __dirname, VITE_DEV_SERVER_URL, RENDERER_DIST } from "../core/constants";
import { getMainWindow } from "./main-window";

let imagePreviewWindow: BrowserWindow | null = null;

export interface ImagePreviewData {
  src: string; // 图片地址（URL / Base64 / Blob）
  title?: string;
}

function calcWindowPosition(winWidth: number, winHeight: number): { x: number; y: number } {
  const cursor = screen.getCursorScreenPoint();
  const display = screen.getDisplayNearestPoint(cursor);
  const { x: wa, y: wy, width: ww, height: wh } = display.workArea;

  const marginX = 15;
  const marginY = 20;

  let x: number;
  if (cursor.x + marginX + winWidth <= wa + ww) {
    x = cursor.x + marginX;
  } else {
    x = cursor.x - marginX - winWidth;
  }

  let y: number;
  if (cursor.y + marginY + winHeight <= wy + wh) {
    y = cursor.y + marginY;
    y -= 50;
  } else {
    y = cursor.y - marginY - winHeight;
    y += 50;
  }

  x = Math.max(wa, Math.min(x, wa + ww - winWidth));
  y = Math.max(wy, Math.min(y, wy + wh - winHeight));

  return { x: Math.round(x), y: Math.round(y) };
}

export function createImagePreviewWindow(data: ImagePreviewData): BrowserWindow {
  if (imagePreviewWindow && !imagePreviewWindow.isDestroyed()) {
    const { x, y } = calcWindowPosition(800, 600);
    imagePreviewWindow.setPosition(x, y);
    imagePreviewWindow.focus();
    imagePreviewWindow.webContents.send("image-preview:update", data);
    return imagePreviewWindow;
  }

  const parent = getMainWindow();
  const winWidth = 800;
  const winHeight = 600;
  const { x, y } = calcWindowPosition(winWidth, winHeight);

  const previewWindow = new BrowserWindow({
    width: winWidth,
    height: winHeight,
    x,
    y,
    parent: parent || undefined,
    modal: false,
    resizable: true,
    minimizable: true,
    maximizable: true,
    skipTaskbar: false,
    frame: false,
    title: data.title || "图片预览",
    autoHideMenuBar: true,
    show: false,
    webPreferences: {
      preload: path.join(__dirname, "preload.js"),
      contextIsolation: true,
      nodeIntegration: false,
      additionalArguments: [`--image-data=${JSON.stringify(data)}`],
    },
  });

  if (VITE_DEV_SERVER_URL) {
    previewWindow.loadURL(`${VITE_DEV_SERVER_URL}windows/image-preview.html`);
  } else {
    previewWindow.loadFile(path.join(RENDERER_DIST, "windows/image-preview.html"));
  }

  previewWindow.webContents.send("image-preview:init", data);
  previewWindow.once("ready-to-show", () => {
    previewWindow.show();
  });

  previewWindow.on("closed", () => {
    imagePreviewWindow = null;
  });

  imagePreviewWindow = previewWindow;
  return previewWindow;
}

export function closeImagePreviewWindow(): void {
  if (imagePreviewWindow && !imagePreviewWindow.isDestroyed()) {
    imagePreviewWindow.destroy();
  }
}

export function closeAllImagePreviewWindows(): void {
  if (imagePreviewWindow && !imagePreviewWindow.isDestroyed()) {
    imagePreviewWindow.destroy();
  }
  imagePreviewWindow = null;
}
```

***

### 4. 创建 IPC 处理器

**文件位置**: `packages/electron-host/src/main/ipc/{window-name}.ts`

**示例**: `src/main/ipc/image-preview.ts`

```ts
import { ipcMain } from "electron";
import {
  createImagePreviewWindow,
  closeImagePreviewWindow,
  type ImagePreviewData,
} from "../windows/image-preview-window";

export const IPC_OPEN_IMAGE_PREVIEW = "image-preview:open";
export const IPC_CLOSE_IMAGE_PREVIEW = "image-preview:close";

export function registerImagePreviewIpc(): void {
  ipcMain.handle(IPC_OPEN_IMAGE_PREVIEW, (_event, data: ImagePreviewData) => {
    try {
      createImagePreviewWindow(data);
      return { success: true };
    } catch (error) {
      console.error("[IPC] 打开图片预览窗口失败:", error);
      return { success: false, error: String(error) };
    }
  });

  ipcMain.on(IPC_CLOSE_IMAGE_PREVIEW, () => {
    try {
      closeImagePreviewWindow();
    } catch (error) {
      console.error("[IPC] 关闭图片预览窗口失败:", error);
    }
  });
}

export function unregisterImagePreviewIpc(): void {
  ipcMain.removeHandler(IPC_OPEN_IMAGE_PREVIEW);
  ipcMain.removeAllListeners(IPC_CLOSE_IMAGE_PREVIEW);
}
```

***

### 5. 注册 IPC 到统一入口

**文件位置**: `packages/electron-host/src/main/ipc/index.ts`

```ts
// 导入新增窗口的 IPC 处理器
import { registerImagePreviewIpc, unregisterImagePreviewIpc } from "./image-preview";

export function registerAllIpc(): void {
  // ... 其他 IPC 注册 ...

  // 新增：注册图片预览相关 IPC
  registerImagePreviewIpc();
}

export function unregisterAllIpc(): void {
  // ... 其他 IPC 注销 ...

  // 新增：注销图片预览相关 IPC
  unregisterImagePreviewIpc();
}
```

***

### 6. 配置 Vite 构建入口

**文件位置**: `packages/electron-host/vite.config.ts`

```ts
export default defineConfig({
  // ...
  build: {
    rollupOptions: {
      input: {
        main: resolve(__dirname, "windows/index.html"),
        login: resolve(__dirname, "windows/login.html"),
        userDetail: resolve(__dirname, "windows/user-detail.html"),
        emojiPicker: resolve(__dirname, "windows/emoji-picker.html"),
        // 新增：图片预览入口
        imagePreview: resolve(__dirname, "windows/image-preview.html"),
      },
    },
  },
});
```

***

## 二、使用方式

在渲染进程中打开新窗口：

```ts
window.ipcRenderer?.invoke("image-preview:open", {
  src: "https://example.com/image.jpg",
  title: "我的图片",
});
```

或者从 Base64/Blob 打开：

```ts
window.ipcRenderer?.invoke("image-preview:open", {
  src: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...",
});
```
