节点 ffi - GetWindowRect

node ffi - GetWindowRect

我正在构建一个 Windows Electron 应用程序,它将移动和调整活动的 window。
我正在使用 ffi-napi 访问 user32 特定功能,例如 GetForegroundWindowShowWindow、& SetWindowPos.

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

// create foreign function
const user32 = new ffi.Library('user32', {
  'GetForegroundWindow': ['long', []],
  'ShowWindow': ['bool', ['long', 'int']],
  'SetWindowPos': ['bool', ['long', 'long', 'int', 'int', 'int', '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,
  0, // 0 left have margin on left 
  0, // 0 top have margin on top 
  1024,
  768,
  0x4000 | 0x0020 | 0x0020 | 0x0040
);

现在解决我的问题
我需要获取活动的 window 维度。我在网上搜索,发现 GetWindowRect.
问题是当我将它添加到 user32 函数时,我不确定第二个参数 (RECT) 需要什么。

// create foreign function
const user32 = new ffi.Library('user32', {
  'GetForegroundWindow': ['long', []],
  'ShowWindow': ['bool', ['long', 'int']],
+ 'GetWindowRect': ['bool', ['int', 'rect']],
  'SetWindowPos': ['bool', ['long', 'long', 'int', 'int', 'int', 'int', '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 的小项目中使用此代码。