Skip to content

winapi

stable

Windows API utilities for system information, window manipulation, environment variables, registry path parsing, wallpaper control, and desktop layer management. Most window manipulation functions are Windows-only.

use plugin winapi::{registry_path_parts, is_windows, known_folder_path, …}
32 functions Systems
/ filter jk navigate Esc clear
Functions (32)
  1. registry_path_parts Parse a registry path into hive, subkey, and value name
  2. is_windows Check if the current platform is Windows
  3. known_folder_path Get a well-known folder path by name
  4. expand_env_vars Expand %VAR% patterns in a string
  5. hresult_to_string Convert an HRESULT code to a readable string
  6. last_error_format Format a Win32 error code as a string
  7. message_box Show a native Windows message dialog
  8. get_system_metrics Read a system metric value
  9. find_window Find a window by class and/or title
  10. get_process_id Get the current process ID
  11. get_computer_name Get the machine hostname
  12. get_user_name Get the current user's name
  13. get_env Read an environment variable
  14. set_env Set an environment variable
  15. get_file_association Get the MIME type for a file extension
  16. get_tick_count Get milliseconds since system boot
  17. sleep_ms Sleep for a given number of milliseconds
  18. get_wallpaper_path Get the current desktop wallpaper path
  19. set_wallpaper Set the desktop wallpaper
  20. find_progman Find the Progman shell window handle
  21. find_worker_w Find the WorkerW desktop layer handle
  22. spawn_worker_w Create the WorkerW desktop layer
  23. set_window_parent Re-parent a window
  24. set_window_pos Move and resize a window
  25. set_window_style Add/remove GWL_STYLE flags on a window
  26. set_window_ex_style Add/remove GWL_EXSTYLE flags on a window
  27. show_desktop_icons Show or hide the desktop icon layer
  28. get_work_area Get the usable desktop work area
  29. get_virtual_screen Get the full virtual screen bounds
  30. enum_monitors List all connected monitors
  31. enum_windows_for_pid List all window handles for a process
  32. consts Return a table of common WinAPI constants

Overview

winapi is a thin bridge to the Windows platform: it exposes system information, environment helpers, and direct window-manipulation calls backed by user32, kernel32, and shcore. Windows handles (HWNDs) are passed around as plain integers, so you find or create a window, get its handle as a number, then feed that number to the positioning and styling functions. Pure-data helpers like is_windows, get_env, expand_env_vars, known_folder_path, and get_file_association work on every platform; everything that touches real windows, monitors, or the desktop shell is Windows-only and returns nil or raises on other systems.

The mental model is layered: query the environment with the cross-platform helpers, locate or spawn a window to get an HWND, then reshape it with set_window_pos, set_window_style, and set_window_parent. The desktop-layer functions (find_progman, find_worker_w, spawn_worker_w, show_desktop_icons) exist specifically for embedding content behind the desktop icons (animated wallpapers and the like). Reach for consts to get the style flag values those style functions expect.

Common patterns

Probe the machine before doing anything Windows-specific:

use plugin winapi::{is_windows, get_computer_name, get_user_name, get_system_metrics}

if is_windows() {
  let w = get_system_metrics("screen_width")
  let h = get_system_metrics("screen_height")
  print("{get_user_name()}@{get_computer_name()} on {w}x{h}")
}

Find a window and reshape it to fill the usable work area:

use plugin winapi::{find_window, get_work_area, set_window_pos}

let hwnd = find_window("Notepad", "")
if hwnd != nil {
  let area = get_work_area()
  set_window_pos(hwnd, area["x"], area["y"], area["w"], area["h"])
}

Embed a window behind the desktop icons (animated-wallpaper trick):

use plugin winapi::{spawn_worker_w, set_window_parent, set_window_ex_style, consts}

let c = consts()
let worker = spawn_worker_w()
set_window_parent(my_hwnd, worker)
set_window_ex_style(my_hwnd, c["WS_EX_NOACTIVATE"], 0)

Parse a registry path into hive, subkey, and value name

Splits a registry path like HKLM\Software\Foo\BarValue into hive (HKLM), subkey (Software\Foo), and value_name (BarValue).

use plugin winapi::{registry_path_parts}

let parts = registry_path_parts("HKLM\\Software\\Microsoft\\Windows\\CurrentVersion")
print("hive={parts["hive"]} subkey={parts["subkey"]}")

When the path ends in a value name, that trailing segment is split out into value_name; the remainder becomes the subkey:

use plugin winapi::{registry_path_parts}

let p = registry_path_parts("HKCU\\Environment\\Path")
print("value={p["value_name"]} under {p["subkey"]}")

Check if the current platform is Windows

Returns true when the current platform is Windows, false otherwise. Safe to call cross-platform.

use plugin winapi::{is_windows}

if is_windows() {
  print("running on Windows")
}

Get a well-known folder path by name

Returns the path of a well-known folder: "desktop", "documents", "downloads", "music", "pictures", "videos", "appdata", "localappdata", "temp", or "home".

use plugin winapi::{known_folder_path}

let docs = known_folder_path("documents")
print("Documents: {docs}")

Aliases let you reach roaming and local app-data as well as the temp directory:

use plugin winapi::{known_folder_path}

print("roaming: {known_folder_path("appdata")}")
print("local:   {known_folder_path("localappdata")}")
print("temp:    {known_folder_path("temp")}")

Expand %VAR% patterns in a string

Expands %VAR_NAME% patterns in the input string using the current process environment. Unknown variables are left unchanged.

use plugin winapi::{expand_env_vars}

let path = expand_env_vars("%APPDATA%\\MyApp\\config.json")
print(path)

Convert an HRESULT code to a readable string

Converts an HRESULT integer (e.g. 0, -2147024882) to a human-readable string like "0x00000000 (S_OK)".

use plugin winapi::{hresult_to_string}

print(hresult_to_string(0))          // "0x00000000 (S_OK)"
print(hresult_to_string(-2147467259)) // "0x80004005 (E_FAIL)"

Format a Win32 error code as a string

Formats a Win32 last-error code (from GetLastError) as a human-readable string.

use plugin winapi::{last_error_format}

print(last_error_format(5))  // "Error 5 (ERROR_ACCESS_DENIED)"

Show a native Windows message dialog

Shows a native Windows message box dialog. style can be "ok", "okcancel", "yesno", "yesnocancel", "info", "warning", "error". Returns the clicked button name.

use plugin winapi::{message_box}

let result = message_box("Confirm", "Delete this file?", "yesno")
if result == "yes" {
  print("user confirmed")
}

style is optional and defaults to "ok"; use the "info", "warning", or "error" icon styles for plain notifications:

use plugin winapi::{message_box}

message_box("Done", "Export finished successfully.", "info")

Read a system metric value

Reads a system metric by name. Accepted names include "screen_width" ("cx_screen"), "screen_height" ("cy_screen"), "mouse_buttons", "monitors", "virtual_screen_x", "virtual_screen_y", "virtual_screen_width", and "virtual_screen_height". An unknown name raises an error.

use plugin winapi::{get_system_metrics}

let w = get_system_metrics("screen_width")
let h = get_system_metrics("screen_height")
print("screen: {w}x{h}")

Ask how many physical monitors and mouse buttons are present:

use plugin winapi::{get_system_metrics}

print("monitors: {get_system_metrics("monitors")}")
print("mouse buttons: {get_system_metrics("mouse_buttons")}")

Find a window by class and/or title

Returns the HWND (as integer) of the first window matching the given class name and/or title. Returns nil if not found.

use plugin winapi::{find_window}

let hwnd = find_window("Notepad", "")
if hwnd != nil {
  print("Notepad HWND: {hwnd}")
}

Get the current process ID

Returns the current process ID.

Get the machine hostname

Returns the machine's hostname from COMPUTERNAME or HOSTNAME environment variables.

Get the current user's name

Returns the current user's login name from USERNAME or USER environment variables.

Read an environment variable

Reads an environment variable by name. Returns nil if not set.

Set an environment variable

Sets an environment variable for the current process.

Get the MIME type for a file extension

Returns the MIME type string for a file extension (with or without the leading .), e.g. ".png""image/png".

Get milliseconds since system boot

Returns milliseconds elapsed since the system started (from GetTickCount64 on Windows, 0 on other platforms).

Sleep for a given number of milliseconds

Pauses the current thread for the specified number of milliseconds.

Get the current desktop wallpaper path

Returns the path to the current desktop wallpaper. Windows-only; returns nil on other platforms.

Set the desktop wallpaper

Sets the desktop wallpaper to the image at path. Windows-only.

use plugin winapi::{set_wallpaper, known_folder_path}

let pics = known_folder_path("pictures")
set_wallpaper("{pics}\\background.jpg")

Find the Progman shell window handle

Returns the HWND of the Progman shell window, which hosts the desktop icon layer. Returns nil if not found.

Find the WorkerW desktop layer handle

Finds the WorkerW window that sits below the desktop icons. Used when embedding custom content behind desktop icons. Windows-only.

Create the WorkerW desktop layer

Sends the magic 0x052C message to Progman to create the WorkerW desktop layer and returns its HWND. Windows-only.

use plugin winapi::{spawn_worker_w, set_window_parent}

let worker = spawn_worker_w()
set_window_parent(my_hwnd, worker)

Re-parent a window

Calls SetParent to re-parent child HWND under parent HWND. Returns the previous parent HWND. Windows-only.

Move and resize a window

Moves and resizes the window at hwnd. Windows-only.

Add/remove GWL_STYLE flags on a window

Modifies the GWL_STYLE flags of a window by ORing in add and ANDing out remove. Returns the new style value. Windows-only.

use plugin winapi::{set_window_style, consts}

let c = consts()
// Make a window a borderless popup.
set_window_style(my_hwnd, c["WS_POPUP"], 0)

Add/remove GWL_EXSTYLE flags on a window

Modifies the GWL_EXSTYLE (extended style) flags of a window. Windows-only.

use plugin winapi::{set_window_ex_style, consts}

let c = consts()
// Hide a tool window from the Alt+Tab list and stop it from stealing focus.
set_window_ex_style(my_hwnd, c["WS_EX_TOOLWINDOW"], c["WS_EX_APPWINDOW"])

Show or hide the desktop icon layer

Shows or hides the SHELLDLL_DefView desktop icon layer. Pass true to show, false to hide. Windows-only.

Get the usable desktop work area

Returns the usable desktop area (excluding taskbar) as {x, y, w, h}. Windows-only.

Get the full virtual screen bounds

Returns the bounding rectangle of the entire virtual screen (all monitors combined). Windows-only.

List all connected monitors

Returns a table of monitor descriptors, each with x, y, w, h, is_primary, dpi, and name fields.

use plugin winapi::{enum_monitors}

let monitors = enum_monitors()
print("monitors: {#monitors}")

List all window handles for a process

Returns a table of all HWND integers belonging to the given process ID.

use plugin winapi::{get_process_id, enum_windows_for_pid}

let hwnds = enum_windows_for_pid(get_process_id())
print("this process owns {#hwnds} windows")

Return a table of common WinAPI constants

Returns a table of common WinAPI constant values for use with set_window_style and set_window_ex_style. Includes the extended-style flags WS_EX_TOOLWINDOW, WS_EX_NOACTIVATE, WS_EX_APPWINDOW, WS_EX_TRANSPARENT, WS_EX_LAYERED, the window styles WS_POPUP and WS_VISIBLE, and the Z-order placement handles HWND_TOP, HWND_BOTTOM, HWND_TOPMOST, and HWND_NOTOPMOST.

use plugin winapi::{consts}

let c = consts()
print("WS_EX_LAYERED = {c["WS_EX_LAYERED"]}")
print("HWND_TOPMOST  = {c["HWND_TOPMOST"]}")
enespt-br