Created
May 23, 2024 18:20
-
-
Save JosXa/13bed419cdb01397fc48f1b4adea6e3d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Name: Get current Windows Explorer selection | |
import "@johnlindquist/kit" | |
import ffi from "ffi-napi" | |
import winax from "winax" | |
// Load user32.dll functions for window interaction using ffi-napi | |
const user32 = new ffi.Library("user32", { | |
GetForegroundWindow: ["long", []], | |
GetClassNameA: ["int", ["long", "string", "int"]], | |
}) | |
// Function to get class of the current active window | |
function getActiveWindowClass() { | |
const hwnd = user32.GetForegroundWindow() | |
const buf = Buffer.alloc(256) | |
user32.GetClassNameA(hwnd, buf, 256) | |
return buf.toString() | |
} | |
// Function to get selected items in Explorer | |
async function getExplorerSelection() { | |
const selectedPaths = [] | |
const className = getActiveWindowClass() | |
// Check if the window class matches Explorer classes | |
if (!/^(Progman|WorkerW|(Cabinet|Explore)WClass).*$/.test(className)) { | |
return undefined | |
} | |
// Use ActiveX to interact with Shell.Application | |
const shell = new winax.Object("Shell.Application") | |
const windows = shell.Windows() | |
for (let i = 0; i < windows.Count; i++) { | |
const window = windows.Item(i) | |
if (window && window.HWND === user32.GetForegroundWindow()) { | |
const items = window.Document.SelectedItems() | |
for (let j = 0; j < items.Count; j++) { | |
selectedPaths.push(items.Item(j).Path) | |
} | |
break | |
} | |
} | |
return selectedPaths | |
} | |
const selectedPaths = await getExplorerSelection() | |
if (selectedPaths === undefined) { | |
exit() | |
} | |
const cache = await db("win-current-selection", { paths: [] }, true) | |
const previous = cache.paths | |
if (JSON.stringify(selectedPaths) === JSON.stringify(previous)) { | |
exit() | |
} | |
cache.paths = selectedPaths | |
console.log({ selectedPaths }) | |
await cache.write() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment