使用 Electron 应用程序,是否可以像使用普通桌面应用程序一样通过在应用程序图标上拖动文件来打开文件?
使用其他地方的代码,我可以打开一个被拖到文档窗口的文件:
document.ondragover = document.ondrop = (event) => {
event.preventDefault();
};
document.body.ondrop = (event) => {
openFile(event.dataTransfer.files[0].path.toString());
event.preventDefault();
};
我希望能够通过将文件拖到应用程序图标本身上来打开文件。
在某些情况下,如果应用程序尚未运行,这也意味着启动应用程序。
最佳答案
拖动文件的路径将作为命令行参数传递。您可以使用 process.argv 访问命令行参数.
const { app } = require('electron')
// You can get the dragged file's path like this
if (process.argv.length >= 2) {
const filePath = process.argv[1]
handleFile(filePath)
}
// If you only allow a single instance of your application to be running
// you should use the 'second-instance' event to handle the case if your app is already running
const gotTheLock = app.requestSingleInstanceLock()
if (!gotTheLock) {
app.quit()
} else {
app.on('second-instance', (event, argv, workingDirectory) => {
// Someone tried to run a second instance
// Handle argv here
if (argv.length >= 2) {
const filePath = argv[1]
handleFile(filePath)
}
})
}
function handleFile(filePath) {
// handle the file as you want
}
关于windows - Electron:在图标上拖放文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57900693/