Search code examples
node.jswindowselectronffiuser32

node ffi - GetWindowRect


I am building a Windows Electron app that will move and resize an active window.
I am using ffi-napi to access user32 specific functions such as 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', '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
);

Now to my problem 🙂
I need to get the active window dimension. I am searching the web and I found GetWindowRect.
The problem is when I add it to the user32 functions, I am not sure what is the 2nd param (RECT) requires.

// 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);
...

This is the error I am getting:

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

Hoping anyone can help me. Thank you in advance. 🙏


Solution

  • This is how I solve my issue 🙂

    ...
    // 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;
    ...
    

    I use this code on my small project called Sōkan.