node.js - Electron 应用程序无法使用 `ffi-napi` 模块

标签 node.js windows electron native ffi

我有以下 Electron 代码,

//main.js
const e = require("electron");
const ffi = require("ffi-napi");

const user32 = new ffi.Library("user32", {
  GetKeyState: ["short", ["int32"]],
});

console.log(user32.GetKeyState(0x06) < 0);

function createWindow() {
  let win = new e.BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true,
    },
  });
  win.loadFile("index.html");
}

e.app.whenReady().then(createWindow);
我的主要目标是访问 Electron 应用程序中的 windows.h 函数。 ffi-node似乎作为一个单独的 Node 应用程序运行良好。
但是,当我将其嵌入到 Electron 应用程序中并运行 electron main.js看起来它运行了几秒钟,然后退出。没有错误代码什么都没有。当我尝试删除 const ffi = require("ffi-napi"); 行时和相应的方法调用,它似乎工作正常。我还尝试通过 electron-builder install-app-deps 重建应用程序它没有帮助。

最佳答案

我设法通过将代码更改为此来解决问题。

const { app, BrowserWindow } = require("electron");
const ffi = require("ffi-napi");

const user32 = new ffi.Library("user32", {
  GetKeyState: ["short", ["int32"]],
});

console.log(user32.GetKeyState(0x06) < 0);

var win;

function createWindow() {
  win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true,
    },
  });
  win.loadFile("index.html");
}
app.on("ready", createWindow);
npm install electron -g后跟 npm link electron

关于node.js - Electron 应用程序无法使用 `ffi-napi` 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62576713/

相关文章:

Electron 应用程序 Mac 应用程序商店图标问题 -> "missing required icon"

javascript - PageSpeed Insights (node.js) 未检测到 gzip 压缩

node.js - 是否可以在 node.js 服务器端使用 google.maps api 库?

c++ - 如何在给定 PID 的情况下隐藏进程的控制台?

python - pySerial 程序无法正确读取串行

node.js - 接收SIGINT时子进程未记录

node.js - 在node.js winston中添加行号配置进行日志记录时时间戳消失

javascript - Node.js 从回调函数中提取值

Python 手动/独立/可移植 Windows 安装

reactjs - 将 Electron 应用转移到 Cordova 应用