节点ffi-GetWindowRect

问题描述

我正在构建一个Windows Electron应用程序,它将移动并调整活动窗口的大小。
我正在使用ffi-napi访问 user32 特定功能,例如 GetForegroundWindow ShowWindow SetwindowPos

const ffi = require('ffi-napi');

// create foreign function
const user32 = new ffi.Library('user32',{
  'GetForegroundWindow': ['long',[]],'ShowWindow': ['bool',['long','int']],'SetwindowPos': ['bool','long','int','uint']]
});

// get active window
const activeWindow = user32.GetForegroundWindow();
// force active window to restore mode
user32.ShowWindow(activeWindow,9);
// set window position
user32.SetwindowPos(
  activeWindow,// 0 left have margin on left ?
  0,// 0 top have margin on top ?
  1024,768,0x4000 | 0x0020 | 0x0020 | 0x0040
);

现在遇到我的问题?
我需要获取活动窗口的尺寸。我正在网上搜索,发现了 GetwindowRect
问题是,当我将其添加 user32 函数时,我不确定第二个参数(RECT)要求什么。

// create foreign function
const user32 = new ffi.Library('user32',+ 'GetwindowRect': ['bool',['int','rect']],'uint']]
});
...
// get active window dimensions
user32.GetwindowRect(activeWindow,0);
...

这是我得到的错误

A javascript error occurred in the main process

Uncaught Exemption:
TypeError: error setting argument 2 - writePointer: Buffer instance expected as
third argument at Object.writePointer

希望任何人都可以帮助我。先感谢您。 ?

解决方法

这就是我解决问题的方法?

...
// create rectangle from pointer
const pointerToRect = function (rectPointer) {
  const rect = {};
  rect.left = rectPointer.readInt16LE(0);
  rect.top = rectPointer.readInt16LE(4);
  rect.right = rectPointer.readInt16LE(8);
  rect.bottom = rectPointer.readInt16LE(12);
  return rect;
}

// obtain window dimension
const getWindowDimensions = function (handle) {
  const rectPointer = Buffer.alloc(16);
  const getWindowRect = user32.GetWindowRect(handle,rectPointer);
  return !getWindowRect
    ? null
    : pointerToRect(rectPointer);
}

// get active window
const activeWindow = user32.GetForegroundWindow();

// get window dimension
const activeWindowDimensions = getWindowDimensions(activeWindow);

// get active window width and height
const activeWindowWidth = activeWindowDimensions.right - activeWindowDimensions.left;
const activeWindowHeight = activeWindowDimensions.bottom - activeWindowDimensions.top;
...

我在名为 Sōkan 的小项目中使用此代码。