windows - Electron:在图标上拖放文件
问题描述
使用 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
}
推荐阅读
- angular - Angular 组件不显示内容
- r - R语言中的group_by和summarize_at显示参数的无效“类型”(内置)
- python - 如何对列表中的类进行排序
- python - 对 x 轴的值进行排序,以便在计算 f(x) 时均匀地填充绘图 f(x)
- javascript - 如何让 Underscore 表现得像 Ramda?
- python - 使用需要编码的moviepy向视频添加字幕
- angular - Angular 将冒号放在 HTML 元素之外
- spring-mvc - Saml 2.0 与 Spring MVC ui Extjs 的集成
- sql - 编辑 GeoJSON 解析代码以在 SQL 中解析 JSON 代码
- laravel - 发送事件时出错 - laravel websocket ssl