windows - Electron:在图标上拖放文件

标签 windows macos drag-and-drop 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
}

关于windows - Electron:在图标上拖放文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57900693/

相关文章:

c# - 如何在 ubuntu 上安装 IIS 服务器

objective-c - OS X 音频编程通用教程

java - 如何制作不需要安装Java的Java Mac App

php - 如何使用 AMPPS 和 Mac OS 10.9.4 在 php 中安装 imagick 作为扩展

three.js - 如何停用 Three.js 中的 DragControls?

javascript - Javascript 中现有的拖放应用程序/框架

c - 从一个函数传递到另一个函数的值发生变化......无法弄清楚为什么?

windows - 事件日志消息大小 31885? Windows 2008

sql-server - 在 Docker 中安装 MSSQL 2014 Express 时出现 "Value cannot be null. Parameter name: userName"错误

javascript - 如何放置元素/拖放看板之类的东西/到它的初始位置