electron 监听U盘插拔事件,并获得U盘路径

思路,用electron监听窗口事件,在监听的回调里,运行C#代码,获取当前电脑的U盘路径,获取到就返回路径,获取不到就返回0

在这里卡了好久,分享出来让大家参考

(环境没必要和我的一样)

我的环境:node 10.2.0

     electron  7.3.1

 依赖: "electron-edge-js": "^12.14.2"

代码 :

hookWindowMessage electron 官方方法:链接https://www.electronjs.org/docs/api/browser-window#winhookwindowmessagemessage-callback-windows

mainWindow.hookWindowMessage(0x0219, (wParam, lParam) => {

//不要以为下面代码中的 /**/是注释。在edge中想要执行C#代码 就需要 /**/包括着
  var edge = require("electron-edge-js");
  const findUSB=edge.func(function () {/*
    using System.IO;
    async (input) => {
      DriveInfo[] allDrives = DriveInfo.GetDrives();
      foreach (DriveInfo d in allDrives)
      {
        if (d.DriveType == DriveType.Removable)
        {
        return d.Name;
        }
      }
      return "0";
      }
    */});

 
  findUSB('0',function (error, result) {
    if (error) throw error;
    console.log(result);
    if(result!=="0"){
      console.log(fs.readdirSync(result))
    }
  });

})

原文地址:https://www.cnblogs.com/caolonggang/p/13178158.html