Setting focus to a Windows application from Node-JS

后端 未结 1 1183
生来不讨喜
生来不讨喜 2021-02-05 17:33

I have a NodeJS application running on Windows that needs to display and switch the focus to a running Windows application when a user does a certain action. I have been using

1条回答
  •  青春惊慌失措
    2021-02-05 18:10

    I've worked out the following solution which works well in all circumstances to bring a window to the top. First it will get the window handle to a running instance of the Calculator application, then it will bring it topmost and focus it.

    var ffi = require('ffi-napi')
    
    var user32 = new ffi.Library('user32', {
        'GetTopWindow': ['long', ['long']],
        'FindWindowA': ['long', ['string', 'string']],
        'SetActiveWindow': ['long', ['long']],
        'SetForegroundWindow': ['bool', ['long']],
        'BringWindowToTop': ['bool', ['long']],
        'ShowWindow': ['bool', ['long', 'int']],
        'SwitchToThisWindow': ['void', ['long', 'bool']],
        'GetForegroundWindow': ['long', []],
        'AttachThreadInput': ['bool', ['int', 'long', 'bool']],
        'GetWindowThreadProcessId': ['int', ['long', 'int']],
        'SetWindowPos': ['bool', ['long', 'long', 'int', 'int', 'int', 'int', 'uint']],
        'SetFocus': ['long', ['long']]
    });
    
    var kernel32 = new ffi.Library('Kernel32.dll', {
        'GetCurrentThreadId': ['int', []]
    });
    
    var winToSetOnTop = user32.FindWindowA(null, "calculator")
    var foregroundHWnd = user32.GetForegroundWindow()
    var currentThreadId = kernel32.GetCurrentThreadId()
    var windowThreadProcessId = user32.GetWindowThreadProcessId(foregroundHWnd, null)
    var showWindow = user32.ShowWindow(winToSetOnTop, 9)
    var setWindowPos1 = user32.SetWindowPos(winToSetOnTop, -1, 0, 0, 0, 0, 3)
    var setWindowPos2 = user32.SetWindowPos(winToSetOnTop, -2, 0, 0, 0, 0, 3)
    var setForegroundWindow = user32.SetForegroundWindow(winToSetOnTop)
    var attachThreadInput = user32.AttachThreadInput(windowThreadProcessId, currentThreadId, 0)
    var setFocus = user32.SetFocus(winToSetOnTop)
    var setActiveWindow = user32.SetActiveWindow(winToSetOnTop)
    

    0 讨论(0)
提交回复
热议问题