Module winapi

A useful set of Windows API functions.

  • Enumerating and accessing windows, including sending keys.
  • Enumerating processes and querying their program name, memory used, etc.
  • Reading and Writing to the Registry
  • Copying and moving files, and showing drive information.
  • Launching processes and opening documents.
  • Monitoring filesystem changes.

Text encoding

set_encoding (e) set the current text encoding.
get_encoding () get the current text encoding.
encode (e_in, e_out, text) encode a string in another encoding.
utf8_expand (text) expand # unicode escapes in a string.

Class Window

Window:get_handle () the handle of this window.
Window:get_text () get the window text.
Window:set_text () set the window text.
Window:show (flags) change the visibility, state etc
Window:get_position () get the position in pixels
Window:get_bounds () get the bounds in pixels
Window:is_visible () is this window visible?
Window:destroy () destroy this window.
Window:resize (x0, y0, w, h) resize this window.
Window:send_message (msg, wparam, lparam) send a message.
Window:enum_children (a) enumerate all child windows.
Window:get_parent () get the parent window.
Window:get_module_filename () get the name of the program owning this window.
Window:get_class_name () get the window class name.
Window:set_foreground () bring this window to the foreground.
Window:get_process () get the associated process of this window
Window:__tostring () this window as string (up to 100 chars).

Manipulating Windows

find_window (cname, wname) find a window based on classname and caption
make_name_matcher (text) makes a function that matches against window text
make_class_matcher (text) makes a function that matches against window class name
find_window_ex (match) find a window using a condition function.
find_all_windows (match) return all windows matching a condition.
find_window_match (text) find a window matching the given text.
get_foreground_window () current foreground window.
get_desktop_window () the desktop window.
enum_windows (callback) enumerate over all top-level windows.
use_gui () route callback dispatch through a message window.
send_to_window (text) send a string or virtual key to the active window.
tile_windows (parent, horiz, kids, bounds) tile a group of windows.

Miscellaneous functions

sleep (millisec) sleep and use no processing time.
show_message (caption, msg, btns, icon) show a message box.
beep (type) make a beep sound.
copy_file (src, dest, fail_if_exists) copy a file.
output_debug_string (str) output text to the system debugger.
move_file (src, dest) move a file.
shell_exec (verb, file, parms, dir, show) execute a shell command.
set_clipboard (text) copy text onto the clipboard.
get_clipboard () get the text on the clipboard.
get_console () open console i/o.
open_serial (defn) open a serial port for reading and writing.

Class Event

Event:wait (timeout) wait for this event to be signalled.
Event:wait_async (callback, timeout) run callback when this process is finished.

Class Process

Process:get_process_name (full) get the name of the process.
Process:get_pid () get the the pid of the process.
Process:kill () kill the process.
Process:get_working_size () get the working size of the process.
Process:get_start_time () get the start time of this process.
Process:get_run_times () elapsed run time of this process.
Process:wait (timeout) wait for this process to finish.
Process:wait_async (callback, timeout) run callback when this process is finished.
Process:wait_for_input_idle (timeout) wait for this process to become idle and ready for input.
Process:get_exit_code () exit code of this process.
Process:close () close this process handle.

Working with processes

process_from_id (pid) create a process object from the id.
get_current_pid () process id of current process.
get_current_process () process object of the current process.
get_processes () get all process ids in the system.
wait_for_processes (processes, all, timeout) wait for a group of processes.

Class Thread

Thread:suspend () suspend this thread.
Thread:resume () resume a suspended thread.
Thread:kill () kill this thread.
Thread:set_priority (p) set a thread’s priority
Thread:get_priority () get a thread’s priority
Thread:wait (timeout) wait for this thread to finish.
Thread:wait_async (callback, timeout) run callback when this thread is finished.

Class File

File:write (s) write to a file.
File:read () read from a file.
File:read_async (callback) asynchronous read.

Launching processes

setenv (name, value) set an environment variable for any child processes.
spawn_process (program, dir) Spawn a process.
execute (cmd, unicode) execute a system command.
thread (fun, data) launch a function in a new thread.

Asynchronous Timers

make_timer (msec, callback) Create an asynchronous timer.

Dealing with named pipes

open_pipe (pipename) open a pipe for reading and writing.
make_pipe_server (callback, pipename) create a named pipe server.

Drive information and directories

short_path (path) the short path name of a directory or file.
temp_name () get a temporary filename.
delete_file_or_dir (file) delete a file or directory.
make_dir () make a directory.
remove_dir (dir, tree) remove a directory.
files (mask, subdirs, attrib) iterator over directory contents.
dirs (file, subdirs) iterate over subdirectories
get_logical_drives () get all the drives on this computer.
get_drive_type (root) get the type of the given drive.
get_disk_free_space (root) get the free disk space.
get_disk_network_name (root) get the network resource associated with this drive.
watch_for_file_changes (dir, how, subdirs, callback) start watching a directory.

Class Regkey

Regkey:set_value (name, val, type) set the string value of a name.
Regkey:get_value (name) get the value and type of a name.
Regkey:get_keys () enumerate the subkeys of a key.
Regkey:close () close this key.
Regkey:flush () flush the key.

Registry Functions

open_reg_key (path, writeable) Open a registry key.
create_reg_key (path) Create a registry key.

Constants

constants useful Windows API constants


Text encoding

set_encoding (e)
set the current text encoding.

Parameters:

  • e: one of CP_ACP (Windows code page; default) and CP_UTF8
get_encoding ()
get the current text encoding.

Returns:

    either CP_ACP or CP_UTF8
encode (e_in, e_out, text)
encode a string in another encoding. Note: currently there’s a limit of about 2K on the string buffer.

Parameters:

  • e_in: CP_ACP, CP_UTF8 or CP_UTF16
  • e_out: likewise
  • text: the string
utf8_expand (text)
expand # unicode escapes in a string.

Parameters:

  • text: ASCII text with #XXXX, where XXXX is four hex digits. ## means # itself.

Returns:

    text as UTF-8

see also:

Class Window

Window:get_handle ()
the handle of this window.
Window:get_text ()
get the window text.
Window:set_text ()
set the window text.
Window:show (flags)
change the visibility, state etc

Parameters:

  • flags: one of SW_SHOW, SW_MAXIMIZE, etc
Window:get_position ()
get the position in pixels

Returns:

  1. left position
  2. top position
Window:get_bounds ()
get the bounds in pixels

Returns:

  1. width
  2. height
Window:is_visible ()
is this window visible?
Window:destroy ()
destroy this window.
Window:resize (x0, y0, w, h)
resize this window.

Parameters:

  • x0: left
  • y0: top
  • w: width
  • h: height
Window:send_message (msg, wparam, lparam)
send a message.

Parameters:

  • msg: the message
  • wparam:
  • lparam:

Returns:

    the result
Window:enum_children (a)
enumerate all child windows.

Parameters:

  • a: callback which to receive each window object
Window:get_parent ()
get the parent window.
Window:get_module_filename ()
get the name of the program owning this window.
Window:get_class_name ()
get the window class name. Useful to find all instances of a running program, when you know the class of the top level window.
Window:set_foreground ()
bring this window to the foreground.
Window:get_process ()
get the associated process of this window
Window:__tostring ()
this window as string (up to 100 chars).

Manipulating Windows

find_window (cname, wname)
find a window based on classname and caption

Parameters:

  • cname: class name (may be nil)
  • wname: caption (may be nil)

Returns:

    Window
make_name_matcher (text)
makes a function that matches against window text

Parameters:

  • text:
make_class_matcher (text)
makes a function that matches against window class name

Parameters:

  • text:
find_window_ex (match)
find a window using a condition function.

Parameters:

  • match: will return true when its argument is the desired window

Returns:

    Window
find_all_windows (match)
return all windows matching a condition.

Parameters:

  • match: will return true when its argument is the desired window

Returns:

    a list of window objects
find_window_match (text)
find a window matching the given text.

Parameters:

  • text: the pattern to match against the caption

Returns:

    a window object.
get_foreground_window ()
current foreground window. An example of setting the caption is caption.lua

Returns:

    Window
get_desktop_window ()
the desktop window.

Usage:

    winapi.get_desktop_window():get_bounds()

Returns:

    Window
enum_windows (callback)
enumerate over all top-level windows.

Parameters:

  • callback: a function to receive each window object
use_gui ()
route callback dispatch through a message window. You need to do this when using Winapi in a GUI application, since it ensures that Lua callbacks happen in the GUI thread.
send_to_window (text)
send a string or virtual key to the active window. input.lua shows launching a process, waiting for it to be ready, and sending it some keys

Parameters:

  • text: either a key (like winapi.VK_SHIFT) or a string

Returns:

  1. number of keys sent, or nil if an error
  2. any error string
tile_windows (parent, horiz, kids, bounds)
tile a group of windows.

Parameters:

  • parent: Window (can use the desktop)
  • horiz: tile vertically by default
  • kids: a table of window objects
  • bounds: a bounds table (left,top,right,bottom) – can be nil

Miscellaneous functions

sleep (millisec)
sleep and use no processing time.

Parameters:

  • millisec: sleep period
show_message (caption, msg, btns, icon)
show a message box.

Parameters:

  • caption: for dialog
  • msg: the message
  • btns: (default ‘ok’) one of ‘ok’,‘ok-cancel’,‘yes’,‘yes-no’, “abort-retry-ignore”, “retry-cancel”, “yes-no-cancel”
  • icon: (default ‘information’) one of ‘information’,‘question’,‘warning’,‘error’

Returns:

    a string giving the pressed button: one of ‘ok’,‘yes’,‘no’,‘cancel’, ‘try’,‘abort’ and ‘retry’

see also:

beep (type)
make a beep sound.

Parameters:

  • type: (default ‘ok’); one of ‘information’,‘question’,‘warning’,‘error’
copy_file (src, dest, fail_if_exists)
copy a file.

Parameters:

  • src: source file
  • dest: destination file
  • fail_if_exists: if true, then cannot copy onto existing file
output_debug_string (str)
output text to the system debugger. A uility such as DebugView can show the output

Parameters:

  • str: text
move_file (src, dest)
move a file.

Parameters:

  • src: source file
  • dest: destination file
shell_exec (verb, file, parms, dir, show)
execute a shell command.

Parameters:

  • verb: the action (e.g. ‘open’ or ‘edit’) can be nil.
  • file: the command
  • parms: any parameters (optional)
  • dir: the working directory (optional)
  • show: the window show flags (default is SW_SHOWNORMAL)
set_clipboard (text)
copy text onto the clipboard.

Parameters:

  • text: the text
get_clipboard ()
get the text on the clipboard.

Returns:

    the text
get_console ()
open console i/o.

Returns:

    File
open_serial (defn)
open a serial port for reading and writing.

Parameters:

Returns:

    File

Class Event

Event:wait (timeout)
wait for this event to be signalled.

Parameters:

  • timeout: optional timeout in millisec; defaults to waiting indefinitely.

Returns:

  1. this event object
  2. either “OK” or “TIMEOUT”
Event:wait_async (callback, timeout)
run callback when this process is finished.

Parameters:

  • callback: the callback
  • timeout: optional timeout in millisec; defaults to waiting indefinitely.

Returns:

  1. this process object
  2. either “OK” or “TIMEOUT”

Class Process

this example was helpful
Process:get_process_name (full)
get the name of the process.

Parameters:

  • full: true if you want the full path; otherwise returns the base name.
Process:get_pid ()
get the the pid of the process.
Process:kill ()
kill the process. test-spawn.lua kills a launched process after a certain amount of output.
Process:get_working_size ()
get the working size of the process.

Returns:

  1. minimum working set size
  2. maximum working set size.
Process:get_start_time ()
get the start time of this process.

Returns:

    a table in the same format as os.time() and os.date() expects.
Process:get_run_times ()
elapsed run time of this process.

Returns:

  1. user time in msec
  2. system time in msec
Process:wait (timeout)
wait for this process to finish.

Parameters:

  • timeout: optional timeout in millisec; defaults to waiting indefinitely.

Returns:

  1. this process object
  2. either “OK” or “TIMEOUT”
Process:wait_async (callback, timeout)
run callback when this process is finished.

Parameters:

  • callback: the callback
  • timeout: optional timeout in millisec; defaults to waiting indefinitely.

Returns:

  1. this process object
  2. either “OK” or “TIMEOUT”
Process:wait_for_input_idle (timeout)
wait for this process to become idle and ready for input. Only makes sense for processes with windows (will return immediately if not)

Parameters:

  • timeout: optional timeout in millisec

Returns:

  1. this process object
  2. either “OK” or “TIMEOUT”
Process:get_exit_code ()
exit code of this process. (Only makes sense if the process has in fact finished.)

Returns:

    exit code
Process:close ()
close this process handle.

Working with processes

Creating and working with Processes
process_from_id (pid)
create a process object from the id.

Parameters:

  • pid: the process id

Returns:

    Process
get_current_pid ()
process id of current process.

Returns:

    integer id
get_current_process ()
process object of the current process.

Returns:

    Process
get_processes ()
get all process ids in the system. test-processes.lua is a simple ps equivalent.

Returns:

    an array of process ids.
wait_for_processes (processes, all, timeout)
wait for a group of processes. Note that this will work with Event and Thread objects as well. process-wait.lua shows a number of processes launched in parallel

Parameters:

  • processes: an array of Process objects
  • all: wait for all processes to finish (default false)
  • timeout: wait upto this time in msec (default infinite)

Class Thread

This is returned by the File:read_async method and the make_timer, make_pipe_server and watch_for_file_changes functions. Useful to kill a thread and free associated resources.
Thread:suspend ()
suspend this thread.
Thread:resume ()
resume a suspended thread.
Thread:kill ()
kill this thread. Generally considered a ‘nuclear’ option, but this implementation will free any associated callback references, buffers and handles. test-timer.lua shows how a timer can be terminated.
Thread:set_priority (p)
set a thread’s priority

Parameters:

  • p: positive integer to increase thread priority
Thread:get_priority ()
get a thread’s priority
Thread:wait (timeout)
wait for this thread to finish.

Parameters:

  • timeout: optional timeout in millisec; defaults to waiting indefinitely.

Returns:

  1. this thread object
  2. either “OK” or “TIMEOUT”
Thread:wait_async (callback, timeout)
run callback when this thread is finished.

Parameters:

  • callback: the callback
  • timeout: optional timeout in millisec; defaults to waiting indefinitely.

Returns:

  1. this thread object
  2. either “OK” or “TIMEOUT”

Class File

The write handle may be distinct from the read handle.
File:write (s)
write to a file.

Parameters:

  • s: text

Returns:

    number of bytes written.
File:read ()
read from a file. Please note that this is not buffered, and you will have to split into lines, etc yourself.

Returns:

    text if successful, nil plus error otherwise.
File:read_async (callback)
asynchronous read.

Parameters:

  • callback: function that will receive each chunk of text as it comes in.

Returns:

    Thread

Launching processes

setenv (name, value)
set an environment variable for any child processes. setenv.lua shows how this also affects processes launched with os.execute Note that this can’t affect any system environment variables, see here for how to set these.

Parameters:

  • name: name of variable
  • value: value to set
spawn_process (program, dir)
Spawn a process.

Parameters:

  • program: the command-line (program + parameters)
  • dir: the working directory for the process (optional)

Returns:

  1. Process
  2. File
execute (cmd, unicode)
execute a system command. This is like os.execute(), except that it works without ugly console flashing in Windows GUI applications. It additionally returns all text read from stdout and stderr.

Parameters:

  • cmd: a shell command (may include redirection, etc)
  • unicode: if ‘unicode’ force built-in commands to output in unicode; in this case the result is always UTF-8

Returns:

  1. return code
  2. program output
thread (fun, data)
launch a function in a new thread.

Parameters:

  • fun: a Lua function
  • data: any Lua value to be passed to function

Returns:

    Thread object

Asynchronous Timers

make_timer (msec, callback)
Create an asynchronous timer. The callback can return true if it wishes to cancel the timer. test-sleep.lua shows how you need to call sleep at the end of a console application for these timers to work in the background.

Parameters:

  • msec: interval in millisec
  • callback: a function to be called at each interval.

Returns:

    Thread

Dealing with named pipes

open_pipe (pipename)
open a pipe for reading and writing.

Parameters:

  • pipename: the pipename (default is “\\.\pipe\luawinapi”)
make_pipe_server (callback, pipename)
create a named pipe server. This goes into a background loop, and accepts client connections. For each new connection, the callback will be called with a File object for reading and writing to the client.

Parameters:

  • callback: a function that will be passed a File object
  • pipename: Must be of the form \.\pipe\name, defaults to \.\pipe\luawinapi.

Returns:

    Thread.

Drive information and directories

short_path (path)
the short path name of a directory or file. This is always in ASCII, 8.3 format. This function will create the file first if it does not exist; the result can be used to open files with unicode names (see testshort.lua)

Parameters:

  • path: multibyte encoded file path

Returns:

    ASCII 8.3 format file path
temp_name ()
get a temporary filename. (Don’t use os.tmpname)

Returns:

    full path within temporary files directory.
delete_file_or_dir (file)
delete a file or directory.

Parameters:

  • file: may be a wildcard
make_dir ()
make a directory. Will make necessary subpaths if command extensions are enabled.
remove_dir (dir, tree)
remove a directory.

Parameters:

  • dir: the directory
  • tree: if true, clean out the directory tree
files (mask, subdirs, attrib)
iterator over directory contents.

Parameters:

  • mask: a file mask like “*.txt”
  • subdirs: iterate over subdirectories (default no)
  • attrib: iterate over items with given attribute (as in dir /A:)

Usage:

    for f in winapi.files 'dir\\*.txt' do print(f) end

see also:

dirs (file, subdirs)
iterate over subdirectories

Parameters:

  • file: mask like “mydirs\t*”
  • subdirs: iterate over subdirectories (default no)

see also:

get_logical_drives ()
get all the drives on this computer. An example is drives.lua

Returns:

    a table of drive names
get_drive_type (root)
get the type of the given drive.

Parameters:

  • root: root of drive (e.g. ‘c:\’)

Returns:

    one of the following: unknown, none, removable, fixed, remote, cdrom, ramdisk.
get_disk_free_space (root)
get the free disk space.

Parameters:

  • root: the root of the drive (e.g. ‘d:\’)

Returns:

  1. free space in kB
  2. total space in kB
get_disk_network_name (root)
get the network resource associated with this drive.

Parameters:

  • root: drive name in the form ‘X:’

Returns:

    UNC name
watch_for_file_changes (dir, how, subdirs, callback)
start watching a directory.

Parameters:

  • dir: the directory
  • how:

    what events to monitor. Can be a sum of these flags:

    • FILE_NOTIFY_CHANGE_FILE_NAME
    • FILE_NOTIFY_CHANGE_DIR_NAME
    • FILE_NOTIFY_CHANGE_LAST_WRITE
  • subdirs: whether subdirectories should be monitored
  • callback:

    a function which will receive the kind of change plus the filename that changed. The change will be one of these:

    • FILE_ACTION_ADDED
    • FILE_ACTION_REMOVED
    • FILE_ACTION_MODIFIED
    • FILE_ACTION_RENAMED_OLD_NAME
    • FILE_ACTION_RENAMED_NEW_NAME

Returns:

    a thread object.

see also:

Class Regkey

Regkey:set_value (name, val, type)
set the string value of a name.

Parameters:

  • name: the name
  • val: the string value
  • type: one of REG_BINARY,REG_DWORD,REG_SZ,REG_MULTI_SZ,REG_EXPAND_SZ
Regkey:get_value (name)
get the value and type of a name.

Parameters:

  • name: the name (can be empty for the default value)

Returns:

  1. the value (either a string or a number)
  2. the type
Regkey:get_keys ()
enumerate the subkeys of a key.

Returns:

    a table of key names
Regkey:close ()
close this key. Although this will happen when garbage collection happens, it is good practice to call this explicitly.
Regkey:flush ()
flush the key. Considered an expensive function; use it only when you have to guarantee modification.

Registry Functions

open_reg_key (path, writeable)
Open a registry key. test-reg.lua shows reading a registry value and enumerating subkeys.

Parameters:

  • path: the full registry key e.g [[HKEY\_LOCAL\_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion]]
  • writeable: true if you want to set values

Returns:

    Regkey
create_reg_key (path)
Create a registry key.

Parameters:

  • path: the full registry key

Returns:

    Regkey

Constants

The following constants are available:

  • CP_ACP, (valid values for encoding)
  • CP_UTF8,
  • CP_UTF16,
  • SW_HIDE, (Window operations for Window.show)
  • SW_MAXIMIZE,
  • SW_MINIMIZE,
  • SW_SHOWNORMAL,
  • VK_BACK,
  • VK_TAB,
  • VK_RETURN,
  • VK_SPACE,
  • VK_PRIOR,
  • VK_NEXT,
  • VK_END,
  • VK_HOME,
  • VK_LEFT,
  • VK_UP,
  • VK_RIGHT,
  • VK_DOWN,
  • VK_INSERT,
  • VK_DELETE,
  • VK_ESCAPE,
  • VK_F1,
  • VK_F2,
  • VK_F3,
  • VK_F4,
  • VK_F5,
  • VK_F6,
  • VK_F7,
  • VK_F8,
  • VK_F9,
  • VK_F10,
  • VK_F11,
  • VK_F12,
  • FILE_NOTIFY_CHANGE_FILE_NAME (these are input flags for watch_for_file_changes)
  • FILE_NOTIFY_CHANGE_DIR_NAME
  • FILE_NOTIFY_CHANGE_LAST_WRITE
  • FILE_ACTION_ADDED (these describe the change: first argument of callback)
  • FILE_ACTION_REMOVED
  • FILE_ACTION_MODIFIED
  • FILE_ACTION_RENAMED_OLD_NAME
  • FILE_ACTION_RENAMED_NEW_NAME
constants
useful Windows API constants
generated by LDoc 1.2