docs: fix take-screenshot fiddle to use desktopCapturer in main.js (#39420)

This commit is contained in:
Milan Burda 2023-08-10 10:53:23 +02:00 committed by GitHub
parent c4d417b6f6
commit 1ce2fdd63d
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 18 additions and 19 deletions

View file

@ -1,4 +1,4 @@
const { BrowserWindow, app, screen, ipcMain } = require('electron') const { BrowserWindow, app, screen, ipcMain, desktopCapturer } = require('electron')
let mainWindow = null let mainWindow = null
@ -6,6 +6,10 @@ ipcMain.handle('get-screen-size', () => {
return screen.getPrimaryDisplay().workAreaSize return screen.getPrimaryDisplay().workAreaSize
}) })
ipcMain.handle('get-sources', (event, options) => {
return desktopCapturer.getSources(options)
})
function createWindow () { function createWindow () {
const windowOptions = { const windowOptions = {
width: 600, width: 600,

View file

@ -1,6 +1,6 @@
const { desktopCapturer, shell, ipcRenderer } = require('electron') const { shell, ipcRenderer } = require('electron')
const fs = require('node:fs') const fs = require('node:fs').promises
const os = require('node:os') const os = require('node:os')
const path = require('node:path') const path = require('node:path')
@ -12,24 +12,19 @@ screenshot.addEventListener('click', async (event) => {
const thumbSize = await determineScreenShotSize() const thumbSize = await determineScreenShotSize()
const options = { types: ['screen'], thumbnailSize: thumbSize } const options = { types: ['screen'], thumbnailSize: thumbSize }
desktopCapturer.getSources(options, (error, sources) => { const sources = await ipcRenderer.invoke('get-sources', options)
if (error) return console.log(error) for (const source of sources) {
const sourceName = source.name.toLowerCase()
if (sourceName === 'entire screen' || sourceName === 'screen 1') {
const screenshotPath = path.join(os.tmpdir(), 'screenshot.png')
sources.forEach((source) => { await fs.writeFile(screenshotPath, source.thumbnail.toPNG())
const sourceName = source.name.toLowerCase() shell.openExternal(`file://${screenshotPath}`)
if (sourceName === 'entire screen' || sourceName === 'screen 1') {
const screenshotPath = path.join(os.tmpdir(), 'screenshot.png')
fs.writeFile(screenshotPath, source.thumbnail.toPNG(), (error) => { const message = `Saved screenshot to: ${screenshotPath}`
if (error) return console.log(error) screenshotMsg.textContent = message
shell.openExternal(`file://${screenshotPath}`) }
}
const message = `Saved screenshot to: ${screenshotPath}`
screenshotMsg.textContent = message
})
}
})
})
}) })
async function determineScreenShotSize () { async function determineScreenShotSize () {