Skip to content

Instantly share code, notes, and snippets.

@MarkTiedemann
Created February 15, 2025 22:03
Show Gist options
  • Save MarkTiedemann/cc8d1c77defd3114004c2b6a74e31d58 to your computer and use it in GitHub Desktop.
Save MarkTiedemann/cc8d1c77defd3114004c2b6a74e31d58 to your computer and use it in GitHub Desktop.
Using Deno, register a command in the Windows registry to be run at startup
// https://github.com/DjDeveloperr/deno_win32
import { HKEY_CURRENT_USER, REG_SZ, RegDeleteKeyValueA, RegSetKeyValueA } from "https://win32.deno.dev/0.4.1/System.Registry";
const HKEY = Deno.UnsafePointer.create(BigInt(HKEY_CURRENT_USER));
const STARTUP_RUN = "Software\\Microsoft\\Windows\\CurrentVersion\\Run";
export function registerStartupRun(name: string, command: string) {
const ffiString = new TextEncoder().encode(`${command}\0`);
const lpData = Deno.UnsafePointer.of(ffiString);
// https://learn.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-regsetkeyvaluea
const error = RegSetKeyValueA(
/*hKey*/ HKEY,
/*lpSubKey*/ STARTUP_RUN,
/*lpValueName*/ name,
/*dwType*/ REG_SZ,
/*lpData*/ lpData,
/*cbData*/ ffiString.length,
)
if (error !== 0) {
throw new Error(`RegSetKeyValueA failed with error ${error}`);
}
}
export function deregisterStartupRun(name: string) {
// https://learn.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-regdeletekeyvaluea
const error = RegDeleteKeyValueA(
/*hKey*/ HKEY,
/*lpSubKey*/ STARTUP_RUN,
/*lpValueName*/ name,
);
if (error !== 0) {
throw new Error(`RegDeleteKeyValueA failed with error ${error}`);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment