import { BrowserWindow, BrowserWindowConstructorOptions, app, session, screen, desktopCapturer, globalShortcut } from "electron" import { Window } from "./win" import { join } from "path" import { platform, env } from "process" export default class ScreenShotsWindow implements Window { win: BrowserWindow option: BrowserWindowConstructorOptions constructor(opts?: BrowserWindowConstructorOptions) { this.option = { ...opts, frame: false, transparent: true, show: false, resizable: false, webPreferences: { webSecurity: false, contextIsolation: true, nodeIntegration: true, preload: join(app.getAppPath(), 'preload.js'), } } if (platform !== 'linux') { this.option.titleBarStyle = 'hidden' this.option.skipTaskbar = true } this.setup() } async setup() { this.win = new BrowserWindow(this.option) this.win?.loadFile(join(app.getAppPath(), 'screen-shots/index.html')) // window if (platform === 'win32') { // 禁用右键菜单 this.win.hookWindowMessage(278, () => { this.win.setEnabled(false); //窗口禁用 setTimeout(() => { this.win.setEnabled(true); }, 100); //延时太快会立刻启动,太慢会妨碍窗口其他操作,可自行测试最佳时间 return true; }) } // 注册截图快捷键 globalShortcut.register('ESC', () => { if (!this.win?.isDestroyed() && this.win?.isFocused()) { this.win.hide() this.win.reload() } }) } async forward(evt: string, data?: Any) { if (evt === 'screen') { // 截图 if (this.win && !this.win.isDestroyed()) { const allPlay = screen.getAllDisplays() const { size } = screen.getPrimaryDisplay() const source = await this.getScreenData(size.width, size.height, allPlay) this.win.webContents.send('source-screen', source) this.win.show() } } else if (evt === 'screenSave' || evt === 'screenClose') { this.win.hide() this.win.reload() } } debug() { if (this.win?.isFocused()) { this.win?.webContents.openDevTools() } } async getScreenData(width: number, height: number, allPlay: Electron.Display[]) { const sors = await desktopCapturer.getSources({ types: ['screen'], thumbnailSize: { width, height } }) const allSource = [] if (sors.length > 1) { const { x } = screen.getCursorScreenPoint() const sc = [] for (let k = 0; k < allPlay.length; k++) { const el = allPlay[k]; const X = el.bounds.x + el.bounds.width const obj = { num: X - x, _index: k, ...el } if (X - x > 0) sc.push(obj) } const array = sc.sort((a, b) => a.num - b.num) if (!array.length) return [] const { id } = array[0] const { thumbnail } = sors.find(el => +el.display_id === id) allSource.push({ width: thumbnail.getSize().width, height: thumbnail.getSize().height, base64: thumbnail.toDataURL() }) this.win.setBounds(array[0].bounds) } else if (sors.length === 1) { // 一块屏 const { thumbnail } = sors[0] allSource.push({ width: thumbnail.getSize().width, height: thumbnail.getSize().height, base64: thumbnail.toDataURL() }) this.win.setBounds(screen.getPrimaryDisplay().bounds) } this.win.setFullScreen(true) this.win.setAlwaysOnTop(true) return allSource } }