본문 바로가기

ELECTRON

electron에서 WIN32 API SendMessage 사용하기.

반응형

electron프로그램에서 다른 윈도우 프로그램으로

메시지를 전달해야할 일이 생겼습니다.

 

오잉??? 이게 되려나??? 물론 되기야 하겠죠? 제 내공이 얕아서 잘 모를뿐 ㅎㅎ

 

역시나 이런 저런 키워드로 검색해보니 딱 있습니다.

 

Node.js Foreign Function Interface for N-API - node-ffi-napi

 

Node라이브러리 말고, 윈도우 DLL 라이브러리등을 사용할 수 있게 해 줍니다.

Linux, OS X, Windows, Solaris에서도 돌아간다는데 저는 Windows에서만 사용해 봤습니다

 

EnumWindows로 실행중인 프로그램을 하나 찾아 그 녀석에게 메시지 하나를 날려주는 간단한 작업입니다.

 

* 윈도우 개발툴이 필요합니다. Visual Studio 없으시면, 개발툴 먼저 설치해야합니다.

- 필요한 개발툴 -

 

1. ffi-napi 설치

npm install ffi-napi

 

 

2. DLL과 함수 정의 

const ffi = require("ffi-napi");
const ref = require("ref-napi");

const voidPtr = ref.refType(ref.types.void);
const stringPtr = ref.refType(ref.types.CString);

const user32 = ffi.Library("user32.dll", {
  EnumWindows: ["bool", [voidPtr, "int32"]],
  GetWindowTextA: ["long", ["long", stringPtr, "long"]],
  SendMessageA: ["int32", ["long", "int32", "uint32", "long"]],
});

 

3. EnumWindows 콜백함수 정의 및 사용

let _handle = null;

const _enumWindowProc = ffi.Callback("bool", ["long", "int32"], function (hwnd: unknown, lParam: unknown) {
  const buf = Buffer.alloc(255);
  user32.GetWindowTextA(hwnd, buf, 255);
  
  const name = ref.readCString(buf, 0);
  console.log(name);
  
  if (name.indexOf("TargetProgram") >= 0) {
    console.log("FOUND:", name);
    _handle = hwnd;
    return true;
  }
  return false;
});

user32.EnumWindows(_enumWindowProc, 0);

if(_handle) {
  const _wParam = 1000;
  const _msgId = 9999;
  
  user32.SendMessageA(_handle, _msgId, _wParam, 0);
}

 

이런식으로 WIN32 DLL에서 제공하는 API를 호출할 수 있습니다.

 

 

 

 

 

 

 

 

반응형