title: Setting focus to a Windows application from Node-JS
body: <p>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 the node-ffi package to make windows API calls but have not been able to make it switch focus consistently.  Here is the code I am using. It successfully gets the HWND of a running Calculator app, but then tries to switch focus to that HWND and it only works sometimes:</p>
  
  <pre><code>    var ffi = require('ffi');   
      var intPtr = ref.refType('long');
      var user32 = new ffi.Library('user32', {
          'FindWindowA': ['long', [ 'string', 'string']],
          'SetForegroundWindow': ['bool', ['long']],
          'BringWindowToTop': ['bool', ['long']],
      });
  
      var winToSetOnTop = user32.FindWindowA(null,"calculator")
      var res = user32.ShowWindow(winToSetOnTop, 9);
      res = user32.SetForegroundWindow(winToSetOnTop);
      res = user32.BringWindowToTop(winToSetOnTop);   
  </code></pre>
  
  <p>This combination of commands seems to work most consistently of the ones I have tried, but it does not work all the time.  If the window I want to switch focus to is minimized it will always pop to the top.  If the window is not minimized, but just behind another window, it will only be shown intermittently.  I am not sure how to consistently to get a running windows application to always move to the top of the order, even if it is currently minimized.</p>