Skip to content

↩ Programmatically switch to the previously active window on Windows

Notifications You must be signed in to change notification settings

JosephusPaye/activate-previous-window

Repository files navigation

Activate Previous Window

A native Node.js module for switching to the previously active window on Windows. It programatically replicates what happens when you quickly press and release Alt+Tab.

Installation

npm install JosephusPaye/activate-previous-window --save

Usage

const { activatePreviousWindow, activatePreviousWindowInChildProcess } = require('activate-previous-window');

// Activate the previous window
activatePreviousWindow();

// Same as above, but run the activation using the standalone binary in a child process.
// Works in environments like Electron, where the Node process is not the same as the main window's.
activatePreviousWindowInChildProcess();

How it works

The module follows the approach taken here. That means it:

  • Enumerates top-level windows in z-order using EnumWindows().
  • Chooses the second window that is visible and has a non-empty title. This is assumes that the topmost (first) window in z-order is the currently active window, and the second window below that is the previously active window.
  • Switches to the chosen window using SetForegroundWindow().

Alternative approaches

I tried a few other approaches that didn't work:

  • Simulating Alt+Tab using SendInput(). This led to a flicker where the Alt Tab switcher was visible briefly before the active window was switched.
  • Using GetWindow() to get the previous window in Z-order, instead of EnumWindows(). This required getting the handle of the current active window, and had problems redirecting focus when switching. Using SetForegroundWindow(), the window switched to would come to the top, but won't have keyboard focus.

About

↩ Programmatically switch to the previously active window on Windows

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published