Overview - TWAPI Version 2.2 Overview

Overview

Tcl Windows API V2.2 overview

DESCRIPTION

The Tcl Windows API (TWAPI) extension provides access to functions in the Windows API from within the Tcl scripting language. The TWAPI 2.x series supports Windows 2000 and later versions. For Windows NT 4.0 (SP3 or later), use TWAPI 1.1.5 or earlier releases.

The extension provides access to the Windows API at two levels:

  • a raw interface to the supported Windows API is provided where the Tcl commands directly map to Windows functions. Programmers who are familiar with the Win32 API and prefer to do things the hard way may prefer to use this interface.
  • a more convenient and powerful higher level interface that makes the API much more accessible. This is the interface documented in the remaining sections.

COPYRIGHT

Copyright © 2003-2009 Ashok P. Nadkarni


Packages - TWAPI packages

Packages

Tcl Windows API V2.2 package description

DESCRIPTION

TWAPI functionality is available through three packages: twapi, twapi_desktop and twapi_server.

The entire TWAPI extension described in this manual is available through the twapi package. Most applications should use this package unless they are under severe space constraints such as size of the application distribution package. Even then, note the compressed TclKit version of the full package in only a little over 300KB and the uncompressed Tcl module (usable with Tcl 8.5 and later) is just over 800KB.

In situations where even the 300KB kit is too large or if the TclKit packaging cannot be used with your Tcl build, TWAPI provides the twapi_desktop and twapi_server packages which contain a subset of the most commonly used TWAPI commands for desktop and server environments respectively. The subset of TWAPI included by each is listed below. It must be emphasized that the subset packages may not include all commands listed in that section. Even within an included command, some command options may not be supported. This is not explicitly documented, and it is important that application writers test that specific commands and options being used in their application are available in the subset package in use.

The twapi_desktop subset package includes the following components:

  • Window management
  • COM
  • Windows shell
  • Keyboard and mouse input
  • Sound
  • Clipboard
  • System (subset)
  • Files, Disks and Volumes
  • Windows INI file
  • Error generation and handling
  • Miscellaneous

The twapi_server subset package includes the following components:

  • Services
  • Event log
  • System (subset)
  • Files, Disks and Volumes
  • Windows INI file
  • Error generation and handling
  • Miscellaneous

Note the twapi_desktop and twapi_server packages are not distributed in binary form. To build them from source, run the command

nmake SERVERONLY=1

or

nmake DESKTOPONLY=1

in the top-level TWAPI directory.

COPYRIGHT

Copyright © 2009 Ashok P. Nadkarni


Installation and Usage - TWAPI Installation

Installation and Usage

Installation requirements and usage instructions

DESCRIPTION

System Requirements

The current version of the TWAPI extension supports Windows 2000 and later.

TWAPI also requires Tcl 8.4 or higher. It will not load on older versions of Tcl.

Distribution formats

Each TWAPI package comes in multiple forms. The main twapi package distribution comes in three forms: a ZIP archive ("twapi-VERSION.zip"), a single file Tcl module ("twapi-VERSION.tm") for Tcl 8.5 and above, and a Starkit ("twapi-VERSION.kit").

The subset packages twapi_desktop and twapi_server are only distributed as single file Tcl modules and Starkits.

To install the ZIP distribution, unzip it into a directory and add the location of the twapi distribution directory to your Tcl auto_path variable.

The Tcl module distributions can be used with Tcl 8.5 or later. To install, copy the file into one of the directories returned by Tcl's ::tcl::tm::path list command.

The Starkit distributions are self-contained except for the documentation. To use one of these distributions, simply use the Tcl source command to read it into your Tcl interpreters.

Some factors to consider in choosing the distribution:

  • The ZIP distribution is the most complete, including a test suite for testing the installation using Tcl's tcltest command. It also makes it easy to look through or adapt the Tcl script level code if required.
  • The Starkit is the most compact on-disk if distribution size is a factor.
  • The Tcl module distribution loads the fastest. However, it can only be used with Tcl 8.5 or later.
  • Both the Starkit and Tcl module distributions write the TWAPI DLL component to a temporary directory before calling the OS loader. They therefore cannot be used in read-only disk environments. However, this writing is done only the first time a specific TWAPI build is loaded. The written DLL is identified by a GUID that is specific to every TWAPI build and not rewritten if it already exists.

Loading TWAPI

Once installed, TWAPI can be loaded using the command package require PACKAGENAME where PACKAGENAME is one of twapi, twapi_desktop or twapi_server. Note that with the Starkit distribution, you still need to source the file before invoking this command.

Commands

All commands installed by this extension fall under the twapi:: namespace even if you load the twapi_server or twapi_desktop packages.

The commands are not exported from the namespace by default. To import the commands, they must first be exported by calling ::twapi::export_public_commands. Alternatively, you can call ::twapi::import_commands to import all TWAPI commands.

COPYRIGHT

Copyright © 2003-2009 Ashok P. Nadkarni


Win32 raw API - Windows API

Win32 raw API

Direct access to the Win32 API

DESCRIPTION

The Windows API may be directly accessed by Tcl commands that map to Windows functions. This interface is not documented in the TWAPI documentation. Refer to the Microsoft Windows SDK for a description of the functions and parameters.

It is recommended that the higher level documented TWAPI Tcl functions be used instead. These provide an easier and more flexible interface in addition to hiding platform-specific differences.

Commands

The Windows functions which may be directly accessed are shown below. This list may be obtained by executing the command twapi::list_raw_api.

  • AbortSystemShutdown
  • AcceptSecurityContext
  • AcquireCredentialsHandle
  • AddFontResourceEx
  • AllocateAndGetTcpExTableFromStack
  • AllocateAndGetUdpExTableFromStack
  • AllocateLocallyUniqueId
  • AllocConsole
  • ArrangeIconicWindows
  • AttachThreadInput
  • BackupEventLog
  • Beep
  • BlockInput
  • CastToHANDLE
  • ChangeServiceConfig
  • ClearEventLog
  • CloseClipboard
  • CloseDesktop
  • CloseEventLog
  • CloseHandle
  • CloseServiceHandle
  • CloseThemeData
  • CloseWindow
  • CloseWindowStation
  • CLSIDFromProgID
  • CLSIDFromString
  • ComEventSink
  • CommandLineToArgv
  • ControlService
  • ConvertToIUnknown
  • CreateBindCtx
  • CreateConsoleScreenBuffer
  • CreateDesktop
  • CreateFile
  • CreateFileMoniker
  • CreateMutex
  • CreateProcess
  • CreateProcessAsUser
  • CreateScalableFontResource
  • CreateSemaphore
  • CreateService
  • CreateWindowEx
  • CreateWindowStation
  • DecryptMessage
  • DefineDosDevice
  • DeleteSecurityContext
  • DeleteService
  • DeleteVolumeMountPoint
  • DeregisterEventSource
  • DestroyWindow
  • DeviceIoControl
  • DsGetDcName
  • DuplicateHandle
  • DuplicateTokenEx
  • EmptyClipboard
  • EnableWindow
  • EncryptMessage
  • EnumChildWindows
  • EnumDependentServices
  • EnumDesktops
  • EnumDesktopWindows
  • EnumDeviceDrivers
  • EnumDisplayDevices
  • EnumDisplayMonitors
  • EnumerateSecurityPackages
  • EnumProcesses
  • EnumProcessModules
  • EnumServicesStatus
  • EnumServicesStatusEx
  • EnumWindows
  • EnumWindowStations
  • ExitWindowsEx
  • ExpandEnvironmentStrings
  • FileTimeToSystemTime
  • FillConsoleOutputAttribute
  • FillConsoleOutputCharacter
  • FindFirstVolume
  • FindFirstVolumeMountPoint
  • FindNextVolume
  • FindNextVolumeMountPoint
  • FindVolumeClose
  • FindVolumeMountPointClose
  • FindWindow
  • FindWindowEx
  • FlashWindow
  • FlushConsoleInputBuffer
  • FlushIpNetTable
  • FormatMessageFromModule
  • FormatMessageFromString
  • FreeConsole
  • FreeCredentialsHandle
  • FreeLibrary
  • GenerateConsoleCtrlEvent
  • GetACP
  • GetActiveObject
  • GetActiveWindow
  • GetAdapterIndex
  • GetAdaptersInfo
  • GetAncestor
  • GetAsyncKeyState
  • GetBestInterface
  • GetBestRoute
  • GetCaretBlinkTime
  • GetCaretPos
  • GetClassName
  • GetClientRect
  • GetClipboardData
  • GetClipboardFormatName
  • GetClipboardOwner
  • GetCommandLineW
  • GetComputerName
  • GetComputerNameEx
  • GetConsoleCP
  • GetConsoleMode
  • GetConsoleOutputCP
  • GetConsoleScreenBufferInfo
  • GetConsoleTitle
  • GetConsoleWindow
  • GetCurrencyFormat
  • GetCurrentProcess
  • GetCurrentThemeName
  • GetCurrentThread
  • GetCurrentThreadId
  • GetCursorPos
  • GetDC
  • GetDesktopWindow
  • GetDeviceCaps
  • GetDeviceDriverBaseName
  • GetDeviceDriverFileName
  • GetDevicePowerState
  • GetDiskFreeSpaceEx
  • GetDoubleClickTime
  • GetDriveType
  • GetExitCodeProcess
  • GetExtendedTcpTable
  • GetExtendedUdpTable
  • GetFileTime
  • GetFileType
  • GetForegroundWindow
  • GetGUIThreadInfo
  • GetHandleInformation
  • GetIfEntry
  • GetIfTable
  • GetInterfaceInfo
  • GetIpAddrTable
  • GetIpForwardTable
  • GetIpNetTable
  • GetKeyState
  • GetLargestConsoleWindowSize
  • GetLastInputInfo
  • GetLocaleInfo
  • GetLogicalDrives
  • GetModuleBaseName
  • GetModuleFileNameEx
  • GetModuleInformation
  • GetMonitorInfo
  • GetNetworkParams
  • GetNumberFormat
  • GetNumberOfConsoleInputEvents
  • GetNumberOfConsoleMouseButtons
  • GetNumberOfEventLogRecords
  • GetNumberOfInterfaces
  • GetObject
  • GetOEMCP
  • GetOldestEventLogRecord
  • GetOpenClipboardWindow
  • GetParent
  • GetPerAdapterInfo
  • GetPrivateProfileInt
  • GetPrivateProfileSection
  • GetPrivateProfileSectionNames
  • GetPrivateProfileString
  • GetProcessWindowStation
  • GetProfileInt
  • GetProfileString
  • GetProfileType
  • GetRecordInfoFromGuids
  • GetRecordInfoFromTypeInfo
  • GetServiceDisplayName
  • GetServiceKeyName
  • GetShellWindow
  • GetStdHandle
  • GetSystemDefaultLangID
  • GetSystemDefaultLCID
  • GetSystemDefaultUILanguage
  • GetSystemInfo
  • GetSystemPowerStatus
  • GetSystemTimeAsFileTime
  • GetThemeColor
  • GetThemeFont
  • GetThreadDesktop
  • GetThreadLocale
  • GetTickCount
  • GetTokenInformation
  • GetUserDefaultLangID
  • GetUserDefaultLCID
  • GetUserDefaultUILanguage
  • GetUserName
  • GetVersionEx
  • GetVolumeInformation
  • GetVolumeNameForVolumeMountPoint
  • GetVolumePathName
  • GetWindow
  • GetWindowDC
  • GetWindowInfo
  • GetWindowLong
  • GetWindowPlacement
  • GetWindowRect
  • GetWindowText
  • GetWindowThreadProcessId
  • GlobalAlloc
  • GlobalFree
  • GlobalLock
  • GlobalMemoryStatus
  • GlobalReAlloc
  • GlobalSize
  • GlobalUnlock
  • GUITHREADINFO
  • HideCaret
  • IIDFromString
  • ImpersonateLoggedOnUser
  • ImpersonateSecurityContext
  • ImpersonateSelf
  • InitializeSecurityContext
  • InitiateSystemShutdown
  • InvalidateRect
  • IsAppThemed
  • IsChild
  • IsClipboardFormatAvailable
  • IsIconic
  • IsThemeActive
  • IsValidAcl
  • IsValidSecurityDescriptor
  • IsValidSid
  • IsWindow
  • IsWindowEnabled
  • IsWindowUnicode
  • IsWindowVisible
  • IsZoomed
  • LoadLibraryEx
  • LoadRegTypeLib
  • LoadTypeLibEx
  • LockServiceDatabase
  • LockWorkStation
  • LogonUser
  • LookupAccountName
  • LookupAccountSid
  • LookupPrivilegeDisplayName
  • LookupPrivilegeName
  • LookupPrivilegeValue
  • LsaClose
  • LsaEnumerateLogonSessions
  • LsaGetLogonSessionData
  • MakeSignature
  • MapVirtualKey
  • MessageBeep
  • MonitorClipboardStart
  • MonitorClipboardStop
  • MonitorFromPoint
  • MonitorFromRect
  • MonitorFromWindow
  • MoveFileEx
  • MoveWindow
  • NetConnectionEnum
  • NetFileClose
  • NetFileEnum
  • NetFileGetInfo
  • NetGetDCName
  • NetGroupAdd
  • NetGroupAddUser
  • NetGroupDel
  • NetGroupDelUser
  • NetGroupEnum
  • NetGroupGetInfo
  • NetGroupGetUsers
  • NetLocalGroupAdd
  • NetLocalGroupDel
  • NetLocalGroupEnum
  • NetLocalGroupGetInfo
  • NetLocalGroupGetMembers
  • NetScheduleJobAdd
  • NetScheduleJobDel
  • NetScheduleJobEnum
  • NetScheduleJobGetInfo
  • NetSessionDel
  • NetSessionEnum
  • NetSessionGetInfo
  • NetShareAdd
  • NetShareDel
  • NetShareGetInfo
  • NetShareSetInfo
  • NetUseEnum
  • NetUserAdd
  • NetUserDel
  • NetUserGetGroups
  • NetUserGetInfo
  • NetUserGetLocalGroups
  • OleRun
  • OpenBackupEventLog
  • OpenClipboard
  • OpenDesktop
  • OpenEventLog
  • OpenIcon
  • OpenInputDesktop
  • OpenMutex
  • OpenProcess
  • OpenProcessToken
  • OpenSCManager
  • OpenSemaphore
  • OpenService
  • OpenThemeData
  • OpenThread
  • OpenThreadToken
  • OpenWindowStation
  • OSVERSIONINFOEXW
  • PdhAddCounter
  • PdhBrowseCounters
  • PdhCloseQuery
  • PdhCollectQueryData
  • PdhConnectMachine
  • PdhEnumObjectItems
  • PdhEnumObjects
  • PdhGetDllVersion
  • PdhGetFormattedCounterValue
  • PdhLookupPerfNameByIndex
  • PdhMakeCounterPath
  • PdhOpenQuery
  • PdhParseCounterPath
  • PdhRemoveCounter
  • PdhSetDefaultRealTimeDataSource
  • PdhValidatePath
  • PlaySound
  • POINT
  • PostMessage
  • ProcessIdToSessionId
  • ProgIDFromCLSID
  • QueryContextAttributes
  • QueryDosDevice
  • QueryPathOfRegTypeLib
  • QuerySecurityContextToken
  • QueryServiceConfig
  • QueryServiceLockStatus
  • QueryServiceStatus
  • QueryServiceStatusEx
  • ReadConsole
  • ReadEventLog
  • ReadProcessMemory
  • RealGetWindowClass
  • RECT
  • RegisterClipboardFormat
  • RegisterConsoleEventNotifier
  • RegisterDirChangeNotifier
  • RegisterEventSource
  • RegisterHotKey
  • RegisterTypeLib
  • ReleaseDC
  • ReleaseMutex
  • ReleaseSemaphore
  • RemoveFontResourceEx
  • ReportEvent
  • ResumeThread
  • RevertToSelf
  • SendInput
  • SendMessageTimeout
  • SendNotifyMessage
  • SetActiveWindow
  • SetCaretBlinkTime
  • SetCaretPos
  • SetClipboardData
  • SetConsoleActiveScreenBuffer
  • SetConsoleCP
  • SetConsoleCursorPosition
  • SetConsoleMode
  • SetConsoleOutputCP
  • SetConsoleScreenBufferSize
  • SetConsoleTextAttribute
  • SetConsoleTitle
  • SetConsoleWindowInfo
  • SetCursorPos
  • SetFileTime
  • SetFocus
  • SetForegroundWindow
  • SetHandleInformation
  • SetLayeredWindowAttributes
  • SetNamedSecurityInfo
  • SetProcessWindowStation
  • SetSecurityInfo
  • SetStdHandle
  • SetSuspendState
  • SetTcpEntry
  • SetThreadDesktop
  • SetThreadExecutionState
  • SetThreadToken
  • SetupDiClassGuidsFromNameEx
  • SetupDiClassNameFromGuidEx
  • SetupDiCreateDeviceInfoListEx
  • SetupDiDestroyDeviceInfoList
  • SetupDiEnumDeviceInfo
  • SetupDiEnumDeviceInterfaces
  • SetupDiGetClassDevsEx
  • SetupDiGetDeviceInstanceId
  • SetupDiGetDeviceInterfaceDetail
  • SetupDiGetDeviceRegistryProperty
  • SetVolumeLabel
  • SetVolumeMountPoint
  • SetWindowLong
  • SetWindowPlacement
  • SetWindowPos
  • SetWindowText
  • SHGetFolderPath
  • SHGetPathFromIDList
  • SHGetSpecialFolderLocation
  • SHGetSpecialFolderPath
  • SHInvokePrinterCommand
  • SHObjectProperties
  • ShowCaret
  • ShowOwnedPopups
  • ShowWindow
  • ShowWindowAsync
  • StartService
  • SuspendThread
  • SwitchDesktop
  • SystemParametersInfo
  • SystemTimeToFileTime
  • SystemTimeToVariantTime
  • TerminateProcess
  • TwapiGetSidStringRep
  • TwapiThemeDefineValue
  • UnloadUserProfile
  • UnlockServiceDatabase
  • UnregisterConsoleEventNotifier
  • UnregisterDirChangeNotifier
  • UnregisterHotKey
  • UnRegisterTypeLib
  • UpdateWindow
  • UuidCreate
  • UuidCreateNil
  • VariantTimeToSystemTime
  • VerifySignature
  • VerLanguageName
  • WaitForInputIdle
  • WaitForMultipleObjects
  • WindowFromPoint
  • WINDOWINFO
  • WINDOWPLACEMENT
  • WNetCancelConnection2
  • WNetGetUniversalName
  • WNetGetUser
  • WriteConsole
  • WriteConsoleOutputCharacter
  • WritePrivateProfileString
  • WriteProfileString
  • WTSCloseServer
  • WTSDisconnectSession
  • WTSEnumerateProcesses
  • WTSEnumerateSessions
  • WTSLogoffSession
  • WTSOpenServer
  • WTSQuerySessionInformation
  • WTSSendMessage

COPYRIGHT

Copyright © 2003-2008 Ashok P. Nadkarni


Window management - Window management

Window management

Commands related to management of windows

SYNOPSIS

package require twapi

arrange_icons ?HWIN?
close_window HWIN ?options?
configure_window_titlebar HWIN ?options?
disable_window_input HWIN
enable_window_input HWIN
find_windows ?options?
flash_window_caption HWIN ?-toggle?
get_active_window_for_current_thread TID
get_active_window_for_thread TID
get_caret_blink_time
get_caret_location
get_child_windows HWIN
get_color_depth ?HWIN?
get_descendent_windows HWIN
get_desktop_window
get_desktop_wallpaper
get_desktop_workarea
get_display_devices
get_display_monitor_from_point X Y ?-default DEFAULTMONITOR?
get_display_monitor_from_rect RECT ?-default DEFAULTMONITOR?
get_display_monitor_from_window HWIN ?-default DEFAULTMONITOR?
get_display_monitors ?-device DEVICENAME? ?-activeonly?
get_display_monitor_info HMONITOR
get_display_size
get_first_child HWIN
get_first_sibling_window HWIN
get_focus_window_for_thread TID
get_foreground_window
get_last_sibling_window HWIN
get_multiple_display_monitor_info
get_next_sibling_window HWIN
get_owner_window HWIN
get_parent_window HWIN
get_prev_sibling_window HWIN
get_shell_window
get_toplevel_windows ?-pid PID?
get_window_application HWIN
get_window_at_location X Y
get_window_class HWIN
get_window_client_area_size HWIN
get_window_coordinates HWIN
get_window_id HWIN
get_window_long HWIN INDEX
get_window_process HWIN
get_window_real_class HWIN
get_window_style HWIN
get_window_text HWIN
get_window_thread HWIN
get_window_userdata HWIN
hide_caret
hide_owned_popups HWIN
hide_window HWIN ?-sync?
invalidate_screen_region ?options?
maximize_window HWIN ?-sync?
minimize_window HWIN ?options?
move_window HWIN X Y ?-sync?
redraw_window HWIN ?-force?
redraw_window_frame HWIN
resize_window HWIN W H ?-sync?
restore_window HWIN ?options?
set_active_window_for_thread HWIN
set_caret_blink_time MILLISECONDS
set_caret_location POINT
set_desktop_wallpaper PATH ?-persist?
set_focus HWIN
set_foreground_window HWIN
set_window_long HWIN INDEX VALUE
set_window_style HWIN style exstyle
set_window_text HWIN TEXT
set_window_userdata HWIN INTEGER
set_window_zorder HWIN POS
show_caret
show_owned_popups HWIN
show_window HWIN ?options?
window_exists HWIN
window_input_enabled HWIN
window_is_child PARENTHWIN CHILDHWIN
window_maximized HWIN
window_minimized HWIN
window_visible HWIN
window_unicode_enabled HWIN

DESCRIPTION

This package provides procedures related to window management on Windows platforms.

Window Management

Windows are identified using window handles. A window handle consisting of an empty string represents an invalid or non-existent window when returned from a command.

The commands get_toplevel_windows, get_descendent_windows and get_child_windows enumerate the windows on the system. get_desktop_window and get_shell_window return handles to the desktop window and the shell window respectively. find_windows returns a list of windows that satisfy matching multiple matching criteria. The command window_exists can be used to check if a specific window exists.

The commands get_parent_window, get_owner_window, get_first_child, get_next_sibling_window, get_prev_sibling_window, get_first_sibling_window, get_last_sibling_window retrieve handles to windows with the appropriate relationship to the specified window. The command window_is_child can be used to check parent-child relationships between windows.

The commands get_window_process and get_window_thread retrieve the process and thread respectively that own the specified window. get_window_application returns the application instance for the specified window.

The commands get_foreground_window, set_foreground_window and set_window_zorder deal with the position of windows in the display Z-order.

The commands show_window, hide_window, restore_window, minimize_window, maximize_window, show_owned_popups, and hide_owned_popups control the visibility of windows. The commands window_minimized, window_maximized, window_visible check the visibility state of a window. close_window closes the specified window.

The commands get_window_style, set_window_style, get_window_class, get_window_real_class, get_window_long, set_window_long get_window_userdata and set_window_userdata retrieve and modify various attributes associated with windows.

The visibility and buttons displayed on the title bar of a window can be controlled through the command configure_window_titlebar.

The command get_window_id returns the window id of the specified window.

redraw_window and redraw_window_frame cause the window and the frame of a window to be redrawn respectively.

The commands move_window, resize_window and arrange_icons can be used to position and resize windows. The commands get_window_client_area_size and get_window_coordinates can be used to get window location and size. The command get_window_at_location returns the window at a given screen location.

The commands set_active_window_for_thread, get_active_window_for_thread, get_focus_window_for_thread, get_active_window_for_current_thread deal with the active window state and focus for a particular thread.

The commands enable_window_input, disable_window_input and set_focus deal with controlling input to windows. The command window_input_enabled can be used to check if input to a window is enabled or not. window_unicode_enabled checks if a window is Unicode-enabled or not.

The command flash_window_caption can be used to grab the user's attention by flashing a window or generating a sound.

The commands get_window_text and set_window_text retrieve and modify the title bar of a window or the text associated with a control. In the latter case, only controls in the same application are supported.

The commands get_caret_blink_time, set_caret_blink_time, hide_caret, show_caret, get_caret_location and set_caret_location allow manipulation of the caret and its position.

The command get_desktop_workarea returns the actual usable desktop area (not used by the taskbar etc.). get_color_depth returns the color depth of the display.

The commands get_desktop_wallpaper and set_desktop_wallpaper can be used to manipulate the wallpaper setting for the desktop.

Displays

Command get_display_devices returns a list of display devices in the system. Command get_display_monitors returns a list of monitors in the system. The command get_display_size returns the size of the display.

The monitor corresponing to a window, virtual screen coordinates or virtual screen rectangle be obtained from get_display_monitor_from_window, get_display_monitor_from_point, get_display_monitor_from_rect respectively.

The command get_display_monitor_info returns location and attributes of a specific display monitor. get_multiple_display_monitor_info returns the same information for all display monitors in the system.

Commands

arrange_icons ?HWIN?
Arranges all the minimized (iconized) child windows of the specified window. If HWIN is not specified, it defaults to the desktop window. The command returns the height of one row of icons.
close_window HWIN ?options?
Closes the window specified by HWIN by sending it a WM_CLOSE message. The following options may be specified:

-block | If this option is specified, Windows will block the calling thread from processing any other requests until the command returns.
-wait TIMEOUT | Specifies the number of milliseconds to wait for the window to process the message (default 10 milliseconds).

configure_window_titlebar HWIN ?options?
Configures the title bar of the specified window to show or hide specific buttons. The following options control what buttons are displayed. If a particular option is not specified, the corresponding button is unaffected. Note however that the minimize, maximize and context help buttons are shown only if the system menu is also visible. Also, the minimize and maximize buttons are hidden and displayed as a single group. If one is configured to be hidden and the other is not, both buttons are shown but the hidden one is disabled.

visible BOOLEAN | Controls whether the title bar is displayed.
sysmenu BOOLEAN | Controls whether the system menu button is displayed.
minimizebox BOOLEAN | Controls whether the minimize button is displayed.
maximizebox BOOLEAN | Controls whether the maximize button is displayed.
contexthelp BOOLEAN | Controls whether the context help button is displayed.

disable_window_input HWIN
Disables mouse and keyboard input to the specified window. Returns 1 if the window was previously disabled, else 0.
enable_window_input HWIN
Enables mouse and keyboard input to the specified window. Returns 1 if the window was previously disabled, else 0.
find_windows ?options?
Returns a list of handles corresponding to all windows that match the specified criteria.

The options below control the matching criteria. Note that the boolean options work in tri-state fashion. If the option is not specified, then the corresponding window attribute is not used in the matching at all. If the option value is specified as true, then only windows having that attribute are selected. If the option value is false, only windows without that attribute are selected.

-ancestor HWIN | The window with handle HWIN must be an ancestor of the window.
-caption BOOLEAN | The window must or must not have a caption/title bar depending on whether BOOLEAN is true or false.
-child BOOLEAN | The window must or must not be an child window depending on whether BOOLEAN is true or false.
-class CLASS | The window must belong to the specified class.
-match MATCHTYPE | Specifies the method used for matching PATTERN in the -text option. This may be one of string for an straight character match, glob for matching as in the string match command or regexp for regular expression based matching. In all cases, the comparisons are case-insensitive.
-maximize BOOLEAN | The window must or must not be maximized depending on whether BOOLEAN is true or false.
-maximizebox BOOLEAN | The window must or must not have a maximize box on the title bar depending on whether BOOLEAN is true or false.
-messageonlywindow BOOLEAN | The window must or must not be a message-only window depending on whether BOOLEAN is true or false.
-minimize BOOLEAN | The window must or must not be minimized depending on whether BOOLEAN is true or false.
-minimizebox BOOLEAN | The window must or must not have a minimize box on the title bar depending on whether BOOLEAN is true or false.
-overlapped BOOLEAN | The window must or must not be an overlapped window depending on whether BOOLEAN is true or false.
-pids PIDLIST | The window must be owned by a process whose id is in PIDLIST.
-popup BOOLEAN | The window must or must not be an popup window depending on whether BOOLEAN is true or false.
-single | Returns the first window found without looking for additional windows.
-style STYLE | The window must have the specified style. STYLE must be specified as a list of two integer values corresponding to the style and extended style for the window. See get_window_style.
-text PATTERN | The text associated with the window (generally the window title) must match PATTERN. The matching is done based on the -match option.
-toplevel BOOLEAN | The window must or must not be a toplevel window depending on whether BOOLEAN is true or false.
-visible BOOLEAN | The window must be visible if BOOLEAN is true and hidden if it is false.
Example: Find all windows for an application

Example: Find all windows with a given title

flash_window_caption HWIN ?-toggle?
Flashes the window's title bar. If -toggle is not specified, the window's title bar reverts back to the original state. If -toggle is specified, the title bar stays in the new state.
get_active_window_for_current_thread TID
Returns the current active window for the current thread. If the thread does not have a active window, returns $twapi::null_hwin.
get_active_window_for_thread TID
Returns the current active window for the thread with id TID. If the thread does not have a active window, returns $twapi::null_hwin.
get_caret_blink_time
Returns the blink time of the caret in milliseconds.
get_caret_location
Returns a list of two integers specifying the caret's coordinates. These are always with respect to the client area of the window that owns the caret.
get_child_windows HWIN
Returns a list of handles to all windows that are immediate child windows of the specified window.
get_color_depth ?HWIN?
Returns the number of bits per pixel in the device context of the window identified by HWIN. If HWIN is not specified, the color depth of the entire screen is returned.
get_descendent_windows HWIN
Returns a list of handles to all descendent windows of the specified window.
get_desktop_window
Returns a handle to the desktop window.
get_desktop_wallpaper
Returns the path to the file containing the current wallpaper for the desktop or an empty string if no wallpaper is in use.
get_desktop_workarea
Returns the screen coordinates of the usable area of the desktop as a list of four integers corresponding to the left, top, right and bottom coordinates on the display. The usable area is that area that is not covered by the taskbar and any application desktop toolbars.
get_display_devices
Returns a list of display devices in the system. Each element in the list is a keyed list of key value pairs with the following fields:

-description | A string describing the device.
-desktop | If the value is true, the device is attached to the desktop.
-disconnect
-flags | An integer value containing the device flags. These are also returned as the boolean fields described here.
-id | The value is the device id for the device.
-key | The registry key for the device.
-mirroring | If true, the device is a mirroring pseudo driver such as that used for NetMeeting.
-modespruned | If true, not all the device modes are supported by its output.
-multidriver
-name | The device name.
-primary | If true, the primary desktop is displayed on this device.
-remote
-removable | If true, the device is removable.
-vgacompatible | If true, the device is VGA compatible.

get_display_monitor_from_point X Y ?-default DEFAULTMONITOR?
Returns a handle to the monitor corresponding the virtual screen coordinates (X,Y). If the coordinates lie outside the extents of any monitor, the command will generate an error unless the -default option is specified. If -default is specified with a value of primary, then a handle to the primary display monitor is returned. If the value is nearest, the handle of the monitor whose extent is closest to the screen coordinates is returned.

Note that the returned monitor handle is not a Win32 handle and should not be closed.
get_display_monitor_from_rect RECT ?-default DEFAULTMONITOR?
Returns a handle to the monitor that has the largest area of intersection with the rectangle specified by RECT. RECT indicates a virtual screen region and should be specified as a list of four integers indicating the coordinates of the left, top, right, bottom edges. If the rectangle does not intersect any monitor, the command will generate an error unless the -default option is specified. If -default is specified with a value of primary, then a handle to the primary display monitor is returned. If the value is nearest, the handle of the monitor whose extent is closest to the rectangle is returned.

Note that the returned monitor handle is not a Win32 handle and should not be closed.
get_display_monitor_from_window HWIN ?-default DEFAULTMONITOR?
Returns a handle to the monitor on which the window identified by HWIN is displayed. If the window is not displayed on any monitor, because it is iconified or is placed outside of any monitor extents for example, the command will generate an error unless the -default option is specified. If -default is specified with a value of primary, then a handle to the primary display monitor is returned if the window is not currently displayed. If the value is nearest, the handle of the monitor whose extent is closest to the window is returned.

Note that the returned monitor handle is not a Win32 handle and should not be closed.
get_display_monitors ?-device DEVICENAME? ?-activeonly?
Returns a list of display monitors in the system. If -device is specified, only monitors attached to the device with name DEVICENAME are returned. If -activeonly is specified, only monitors marked as active are returned.

Each element in the returned list is a keyed list of key value pairs with the following fields:

-active | The monitor is active.
-attached
-description | A string describing the device.
-flags | An integer value containing the display monitor flags. These are also returned as the boolean fields described here.
-id | The value is the device id for the device.
-key | The registry key for the device.
-name | The monitor name.

get_display_monitor_info HMONITOR
Returns information about the display monitor identified by HMONITOR which is a monitor handle. The following fields are returned in a keyed list:

-extent | A list of four integers indicating the monitor extent corresponding to the left, top, right and bottom edges of the monitor's display area in virtual screen coordinates.
-name | The name identifying the display monitor.
-primary | A boolean indicating whether the monitor is the primary display monitor.
-workarea | A list of four integers indicating the usable monitor extent corresponding to the left, top, right and bottom edges of the monitor's display area in virtual screen coordinates excluding any space taken up by desktop toolbars and the taskbar.

get_display_size
Returns a list of two integers specifying the width and height of the display.
get_first_child HWIN
Returns a handle to the child window of the specified window that is the first (highest) in the display Z-order.
get_first_sibling_window HWIN
Returns a handle to a sibling window (ie. having the same parent) of the specified window that is the highest in the display Z-order.
get_focus_window_for_thread TID
Returns the window which has the focus the thread with id TID. If the thread does not have a active window, returns $twapi::null_hwin.
get_foreground_window
Returns the current foreground window on the desktop.
get_last_sibling_window HWIN
Returns a handle to a sibling window (ie. having the same parent) of the specified window that is the lowest (least visible) in the display Z-order.
get_multiple_display_monitor_info
Returns a list containing information for every monitor in the system. The information is in the same format as that returned by get_display_monitor_info.
get_next_sibling_window HWIN
Returns a handle to a sibling window (ie. having the same parent) of the specified window that is next in the display Z-order.
get_owner_window HWIN
Returns a handle to the owner window of the specified window or null handle if the window does not have a owner.
get_parent_window HWIN
Returns a handle to the parent window of the specified window.
get_prev_sibling_window HWIN
Returns a handle to a sibling window (ie. having the same parent) of the specified window that is previous (immediately higher) in the display Z-order.
get_shell_window
Returns a handle to the Windows shell process' window.
get_toplevel_windows ?-pid PID?
Returns a list of handles to toplevel windows in the system. If no options are specified, this includes all toplevel windows. If the -pid option is specified with a numeric value of PID, then only toplevel windows owned by the process with id PID are returned. If PID is non-numeric, it is treated as a process name. In this case, the toplevel windows owned by all processes whose name is PID are returned.
get_window_application HWIN
Returns the application instance associated with the specified window.
get_window_at_location X Y
Returns the highest window in the X-order that contains the screen coordinates (X,Y). Windows that are disabled or hidden are not ignored.
get_window_class HWIN
Returns the class of a window. This is simple wrapper around the GetClassName Windows function.
get_window_client_area_size HWIN
Returns a list of two integers containing the width and height in pixels of the client area of the window.
get_window_coordinates HWIN
Returns the screen coordinates of the window as a list of four integers corresponding to the left, top, right and bottom sides of the window.

Example: Move mouse to system menu
get_window_id HWIN
Returns the window id of the specified window. Note that this is different than the window handles.
get_window_long HWIN INDEX
This is a direct call to the GetWindowsLong function. Refer to Windows SDK documentation for details. Several other TWAPI functions act as wrappers provide more straightforward access to the values retrieved by this function.
get_window_process HWIN
Returns the id of the process that owns the specified window.
get_window_real_class HWIN
Returns the real class of a window for classes that are wrapped by applications into their own set of classes. This is simple wrapper around the RealGetWindowClass Windows function. Windows function.
get_window_style HWIN
Returns a list containing the style and the extended style bits respectively followed by symbolic window style attributes corresponding to the style bits. The window styles attributes that may be returned are shown below. Refer to the Windows SDK documentation for the meaning of these styles.

overlapped | The window is an overlapped window - this is a toplevel window without a parent. This attribute is mutually exclusive with popup and child.
popup | The window is popup window like a dialog box. This attribute is mutually exclusive with overlapped and child.
child | The window is the child of some other window. This attribute is mutually exclusive with popup and overlapped.
caption | The window has a caption or title bar and a border.
border | The window has a normal border and no title bar.
dlgframe | The window has a double border as used for dialogs and no title bar.
dlgmodalframe | The window has a double border as used for a dialog and may have a caption as well.
minimize | The window is minimized. Windows with neither minimize or maximize attributes are normal windows.
minimizebutton | The window has a minimize button on the title bar.
maximize | The window is maximized. Windows with neither minimize or maximize attributes are normal windows.
maximizebutton | The window has a maximize button on the title bar.
visible | The window is visible. If this attribute is not present, the window is hidden.
disabled | The window is disabled and does not accept input.
clipsiblings | Indicates that the screen area occupied by sibling windows that overlap will not be overwritten when the window is drawn.
clipchildren | Indicates that the screen area occupied by child windows will not be overwritten when the window is drawn.
vscroll | The window displays a vertical scrollbar.
hscroll | The window displays a horizontal scrollbar.
sysmenu | The window displays a system menu.
thickframe | The window has a thick border that allows for resizing.
noparentnotify | The window is a child window that does not send WM_PARENTNOTIFY messages to its parent.
topmost | The window is a topmost window that is displayed above all non-topmost windows even when it is not active.
acceptfiles | The window accepts files that are dragged and dropped into it.
transparent | The window is transparent and does not obscure windows below it.
mdichild | The window is an MDI child window.
toolwindow | The window is a floating toolbar. The title bar and caption are shrunk. The window does not appear in the task bar and will not show up with the ALT-TAB hotkey.
windowedge | The window has a border with a raised edge.
clientedge | The window has a border with a sunken edge.
contexthelp | The window has a context help button in the caption bar.
controlparent | The window allows navigation between child windows using the TAB key.
staticedge | The window has a 3-D border.
appwindow | The window is forced on the task bar when visible. Note that this does not mean that windows without this attribute will not show up on the task bar. It does mean that windows with this attribute will definitely show up on the task bar.

get_window_text HWIN
Gets the title of a window or the text associated with a control. In the latter case, the control must belong to the same application.
get_window_thread HWIN
Returns the id of the thread that owns the specified window.
get_window_userdata HWIN
Returns the longword associated as user data with the specified window. This maps to the Windows GetWindowLong call with an argument of GWL_USERDATA.
hide_caret
Hides the caret. Note that calls to hide_caret or twapi::HideCaret must be matched by an equivalent number of calls to show_caret or twapi::ShowCaret.
hide_owned_popups HWIN
Hides all popup windows that are owned by the specified window.
hide_window HWIN ?-sync?
Hides the specified window so it does not appear on the display or as an icon. If option -sync is specified, the command will execute synchronously and only return when the window procedure of the target window has handled the request. Note that if the target window is hung, the command will never return.

Returns 1 if the window was previously visible, else 0. The return value is valid only if the -sync option is specified.

Example: Hide all windows for an application
invalidate_screen_region ?options?
Marks a region of the screen as invalid. If no options are specified, all windows are marked invalid, forcing them to be redrawn. The following options may be used with the command:

-hwin HWIN | Indicates the specific window whose client region is to be invalidated.
-rect RECT | If specified, this should be a list of four integers indicating the coordinates of the left, top, right, bottom sides of the region in the window's client area that is to be invalidated. If unspecified or an empty list, the entire client region is marked invalid.
-bgerase | If specified, the background within the invalidated region is erased. Otherwise, it remains unchanged.

maximize_window HWIN ?-sync?
Maximizes the specified window. If option -sync is specified, the command will execute synchronously and only return when the window procedure of the target window has handled the request. Note that if the target window is hung, the command will never return.

The command returns 1 if the window was previously visible, else 0. The return value is valid only if the -sync option is specified.
minimize_window HWIN ?options?
Minimizes the specified window.

-sync | If specified, the command will execute synchronously and only return when the window procedure of the target window has handled the request. Note that if the target window is hung, the command will never return.
-activate | If specified, in addition to being shown, the window is also activated.
-shownext | If specified, the next window in the Z-order is activated.
The command returns 1 if the window was previously visible, else 0. The return value is valid only if the -sync option is specified.

Example: Minimize all windows for an application

move_window HWIN X Y ?-sync?
Moves the specified window such that it's left side is at position X and its top side is at position Y. The window is moved asynchronously unless the -sync option is specified. Note that in this case, the command will never return if the target window is hung.

Example: Move a window to top left corner of the screen
redraw_window HWIN ?-force?
This command causes the invalidate regions of the specified window to be redrawn. If -force is specified, the entire window is redrawn.
redraw_window_frame HWIN
This command causes the frame of the specified window to be redrawn.
resize_window HWIN W H ?-sync?
Resizes the specified window to be W pixels in width and H pixels in height. The resizing is done asynchronously unless the -sync option is specified. Note that in this case, the command will never return if the target window is hung.
restore_window HWIN ?options?
Restores a window to its original size and position if it is maximized or minimized. The command returns 1 if the window was previously visible, else 0. The return value is valid only if the -sync option is specified.

-sync | If specified, the command will execute synchronously and only return when the window procedure of the target window has handled the request. Note that if the target window is hung, the command will never return.
-activate | In addition to being shown, the window is also activated.

set_active_window_for_thread HWIN
Sets the specified window to be the active window for its owning thread. The window is brought to the foreground if the owning thread belongs to the foreground application. Returns the handle of the window that was previously active.
set_caret_blink_time MILLISECONDS
Sets the blink time of the caret to MILLISECONDS milliseconds.
set_caret_location POINT
Sets the caret's location to POINT which must be a list of two integers specifying the caret's coordinates.
set_desktop_wallpaper PATH ?-persist?
Sets the desktop wallpaper to that specified by the file PATH. The file must be in BMP format. If PATH is specified as an empty string or none, no wallpaper is displayed on the desktop. If PATH is default, the default wallpaper is restored to the desktop. If the option -persist is specified, the new setting is written to the user's profile.
set_focus HWIN
Sets the focus to the specified window. The window, or its parent, is also activated. The command returns the window that previously had the focus.
set_foreground_window HWIN
Sets the specified window to be the foreground window. Returns 1 if successful, and 0 otherwise.

Example: Bring a window to the foreground
set_window_long HWIN INDEX VALUE
This is a direct call to the SetWindowsLong function. Refer to Windows SDK documentation for details. Several other TWAPI functions act as wrappers and provide more straightforward access to the values set by this function.
set_window_style HWIN style exstyle
Sets the style and extended style bits for the specified window. style and exstyle are bitmasks. Refer to the Windows SDK documentation for details.

Example: Remove the title bar from a window
set_window_text HWIN TEXT
Sets the title of a window or the text associated with a control. In the latter case, the control must belong to the same application.

Example: Change the title bar of a window
set_window_userdata HWIN INTEGER
Sets the longword associated as user data with the specified window. This maps to the Windows SetWindowLong call with an argument of GWL_USERDATA.
set_window_zorder HWIN POS
Sets the position of the specified window in the Z-order. POS may be either a window handle or a keyword. In the former case, the window is placed right after the window specified by POS. Otherwise, POS must be one of the following keywords:

top | Places the window at the top of the Z-order.
bottom | Places the window at the bottom of the Z-order.
toplayer | Refer to explanation of HWND_TOPMOST in the documentation of the function SetWindowsPos in the Windows SDK.
bottomlayer | Refer to explanation of HWND_NOTOPMOST in the documentation of the function SetWindowsPos in the Windows SDK.
Example: Keep a window on top

show_caret
Shows the caret. Note that calls to hide_caret or twapi::HideCaret must be matched by an equivalent number of calls to show_caret or twapi::ShowCaret to make the caret visible.
show_owned_popups HWIN
Shows all popup windows owned by the specified window that were hidden by a previous call to hide_owned_popups. Note that popups that were hidden using other functions such as hide_window will not be shown by this call.
show_window HWIN ?options?
Makes the specified window visible. Note that a visible window may still be obscured by other windows or clipped. The command returns 1 if the window was previously visible, else 0. The return value is valid only if the -sync option is specified.

-sync | If specified, the command will execute synchronously and only return when the window procedure of the target window has handled the request. Note that if the target window is hung, the command will never return.
-activate | In addition to being shown, the window is also activated.
-normal | If a window is minimized or maximized, restores it to its original position.
-startup | Shows the window based on the contents of the STARTUPINFO structure when the process was created.

If both -normal and -startup are specified, -startup takes precedence. If neither is specified, the window is shown in its current form, which may be minimized, maximized or normal.

Example: Show all windows for an application

window_exists HWIN
Returns 1 if the specified window exists, else 0.
window_input_enabled HWIN
Returns 1 if the specified window has mouse and keyboard input enabled, else 0.
window_is_child PARENTHWIN CHILDHWIN
Returns 1 if the window CHILDHWIN is a child of the window PARENTHWIN, else 0.
window_maximized HWIN
Returns 1 if the specified window is maximized, else 0.
window_minimized HWIN
Returns 1 if the specified window has been minimized, else 0.
window_visible HWIN
Returns 1 if the specified window is visible, else 0. Note that visible does not imply user can actually see the window (it may be obscured or clipped).
window_unicode_enabled HWIN
Returns 1 if the specified window is a native Unicode window, else 0.

COPYRIGHT

Copyright © 2003-2009 Ashok P. Nadkarni


Desktops and Window stations - Desktop and window stations

Desktops and Window stations

Commands related to desktops and window stations

SYNOPSIS

package require twapi

close_desktop_handle HDESK
close_window_station_handle HWINSTA
find_desktops ?-winsta HWINSTA?
find_window_stations
get_current_window_station_handle
get_desktop_handle DESKTOP ?-inherit BOOL? ?-access ACCESSRIGHTS? ?-allowhooks BOOL?
get_window_station_handle WINDOWSTATION ?-inherit BOOL? ?-access ACCESSRIGHTS?
set_process_window_station HWINSTA

DESCRIPTION

This package provides procedures related to desktops and window stations on Windows platforms.

Window Stations

TBD

Desktops

TBD

Commands

close_desktop_handle HDESK
Closes a desktop handle that was previously returned by a call to get_desktop_handle and frees and associated resources.
close_window_station_handle HWINSTA
Closes a window station handle that was previously returned by a call to get_window_station_handle.
find_desktops ?-winsta HWINSTA?
Returns a list of desktops. By default, the desktops from the current window station are returned. The -winsta option may be used to specify a different window station.
find_window_stations
Returns a list of identifiers for all window stations in the system for which the caller has the WINSTA_ENUMERATE privilege.
get_current_window_station_handle
Returns a handle to the window station for the calling process. This handle need not (and should not) be closed.
get_desktop_handle DESKTOP ?-inherit BOOL? ?-access ACCESSRIGHTS? ?-allowhooks BOOL?
Returns a handle to the specified desktop.

The -inherit option determines whether the returned handle will be inherited by child processes. This is false by default.

The access rights associated with the handle default to GENERIC_READ unless the -access option is specified. ACCESSRIGHTS specifies the desired access rights and may be specified as a list of integer access rights flags or symbols as described in Access Rights.

If the option -allowhooks is specified as true, processes running in other accounts on the desktop will be allowed to set hooks in the calling process.

When no longer needed, the returned handle should be closed with a call to to close_desktop_handle.
get_window_station_handle WINDOWSTATION ?-inherit BOOL? ?-access ACCESSRIGHTS?
Returns a handle to the window station identified by WINDOWSTATION.

The access rights associated with the handle default to GENERIC_READ unless the -access option is specified. ACCESSRIGHTS specifies the desired access rights and may be specified as a list of integer access rights flags or symbols as described in Access Rights.

The -inherit option determines whether the returned handle will be inherited by child processes. This is false by default.

When no longer needed, the returned handle should be closed with a call to to close_window_station_handle.
set_process_window_station HWINSTA
Assigns the window station identified by HWINSTA to the calling process. HWINSTA should be a window station handle previously returned by get_window_station_handle. See the description of SetProcessWindowStation in the Windows SDk for more details.

COPYRIGHT

Copyright © 2003-2009 Ashok P. Nadkarni


COM - COM client support

COM

Commands for accessing COM servers

SYNOPSIS

package require twapi

clsid_to_progid CLSID
comobj PROGID_OR_CLSID ?options?
COMOBJ
COMOBJ NAME ?parameter ...?
COMOBJ -bind SCRIPT
COMOBJ -call METHOD ?parameter ...?
COMOBJ -destroy
COMOBJ -get PROPERTY ?parameter ...?
COMOBJ -interface
COMOBJ -isnull
COMOBJ -iterate VARNAME SCRIPT
COMOBJ -print
COMOBJ -queryinterface IID
COMOBJ -set PROPERTY VALUE ?parameter ...?
COMOBJ -unbind BINDID
COMOBJ -with METHODLIST ?parameters ...?
progid_to_clsid PROGID
timelist_to_variant_time TIMELIST
variant_time_to_timelist DOUBLE

DESCRIPTION

This module provides commands for supporting COM clients. TWAPI's COM support is limited to client side calls only and is not intended to compete with the OpTcl or TCOM packages. It was added to allow TWAPI access to some of the simpler COM based API's in Windows including WMI and ADSI.

Creation and Destruction of COM objects

A COM object can be created through the command comobj using the PROGID or CLSID of the corresponding COM class. This returns a Tcl command that may be used to access the object through subcommands. The example below creates a COM object using the PROGID for Internet Explorer.

set ie [comobj InternetExplorer.Application -enableaaa]

Alternatively, the comobj_object command can be used to bind to a COM object identified by its display name. For example, the following creates a COM object for an Excel file.

set xlso [comobj_object c:\\data\\myspreadsheet.xls]

When an object is no longer required, it must be explicitly destroyed by calling the command with the -destroy subcommand.

Properties and Methods

The properties and methods of a COM object can be accessed as subcommands of the Tcl command representing that object. The names of properties and methods can in theory overlap. Althouth TWAPI can usually figure out whether a property is being retrieved/set or a method is being called, you can explicitly control this by using the -get, -set or -call subcommands followed by the actual name. The following sequence of commands shows a sample session that drives Internet Explorer through its properties and methods.

Start up Internet Explorer (note it will not be visible yet)

set ie [comobj InternetExplorer.Application -enableaaa]

Make its window visible by changing its Visible property.

$ie Visible true

This could also have been written as

$ie -set Visible true

to explicitly indicate we want to set the property called Visible as opposed to making a call to the COM object's method of the same name (if there was one).

To go to the TWAPI home page, invoke the Navigate method

$ie Navigate http://twapi.sf.net

Get the LocationURL property to find the URL after redirection

$ie LocationURL

Not specifying any parameters gets the default value of the object. This is the property marked as the default value in the COM object's IDL definition.

$ie

Ask the application to exit by calling its Quit method.

$ie Quit

Finally, destroy the COM object.

$ie -destroy

COM Collections

Some COM objects are collection of items which may even be other COM objects. The items within these collections can be accessed by their index (which is not necessarily an integer) but it is often easier to iterate over them using the -iterate operator on the collection object. The following example illustrates this.

set fso_obj [comobj Scripting.FileSystemObject]
set drives_obj [$fso_obj Drives]
$drives_obj -iterate drive_obj {
    puts [$drive_obj DriveLetter]
    $drive_obj -destroy
}
$drives_obj -destroy
$fso_obj -destroy

The Drives method of the Scripting.FileSystemObject returns a collection drives_obj. The -iterate operator on the collection then loops through each item in the collection, assigning the item to drive_obj. In this case, each item is itself a COM object from which we get the DriveLetter property. Note that the drive_obj object generated in each iteration has to be explicitly destroyed.

Navigating Objects

In many cases, the desired objects have to be created by navigating through other objects. For example, the following example sets all cells within a range in a spreadsheet to 12345.

set xl [comobj Excel.Application]
$xl Visible true
set workbooks [$xl Workbooks]
set workbook [$workbooks Add]
set sheets [$workbook Sheets]
set sheet [$sheets Item 1]
set cells [$sheet range a1 c3]
$cells Value 12345
$cells -destroy
$sheet -destroy
$sheets -destroy
$workbook -destroy
$workbooks -destroy
$xl Quit
$xl -destroy

In the above example, in order to get to the range we have to navigate through a hierarchy of objects, starting with the application, the workbook collection, a workbook within the collection, the worksheets collection, a worksheet within that collection and finally the cell range. After setting the value, all the created objects have to be deleted.

As an alternative, the -with subcommand can be used to navigate through the intermediate objects as follows:

set xl [comobj Excel.Application]
$xl Visible true
$xl -with {
    Workbooks
    Add
    Sheets
    {Item 1}
    {range a1 c3}
} Value 12345
$xl -destroy

The -with subcommand takes a list of intermediate methods and associated parameters each of which should return a new object. Each element in the list is invoked on the previously created object and in turn should return a new COM object. The final object created from this list is passed the remaining arguments in the command. All intermediate objects are automatically destroyed.

COM Events

Some COM objects may generate notifications when certain events occur. A callback script may be registered using the -bind subcommand on a COMOBJ object. This script is invoked for every notification event generated by the COM object. The event name and parameters provided by the COM event source are appended to the script.

The following example receives events from Internet Explorer and prints them.

proc print_event args {puts "Received: [join $args ,]"}
set ie [comobj InternetExplorer.Application -enableaaa]
$ie Visible true
set bind_id [$ie -bind print_event]
$ie Navigate http://www.tcl.tk
after 2000
$ie -unbind $bind_id
$ie Quit
$ie -destroy

Note that the script is unregistered using the -unbind subcommand when no longer needed.

Commands

clsid_to_progid CLSID
Returns the PROGID for a given CLSID. For example,

(tclsh) 53 % clsid_to_progid "{0002DF01-0000-0000-C000-000000000046}"
InternetExplorer.Application.1

comobj PROGID_OR_CLSID ?options?
Creates a COM object and returns the name of a Tcl command that can be used to access it. PROGID_OR_CLSID is either the PROGID or the CLSID for the COM object.

The returned value COMOBJ is itself a Tcl command object that can be used to access the COM object. When the object is no longer required it should be deleted by calling the command with the -destroy subcommand. You should not delete the command simply by calling the Tcl rename command as this will lead to memory and resource leaks. options may contain one or more of the options in the table below. Refer to the CLSCTX documentation in the Windows SDK for details regarding these options.

-disablelog BOOLEAN | If specified as true, disables logging of failures. Corresponds to the flag CLSCTX_NO_FAILURE_LOG in the SDK.
-download BOOLEAN If specified as true, allows downloading of code from the Internet or Directory Service. This corresponds to setting the flag CLSCTX_ENABLE_CODE_DOWNLOAD. If specified as false, disallows downloading of code from the Internet or Directory Service. This corresponds to setting the flag CLSCTX_DISABLE_CODE_DOWNLOAD.

If this option is not specified, neither of the flags is set in the underlying call to CoCreateInstance.
-enableaaa BOOLEAN If specified as true, enables activate-as-activator activations where a server process is launched under the caller's identity. This corresponds to setting the flag CLSCTX_ENABLE_AAA. If specified as false, disables activate-as-activator activations. This corresponds to setting the flag CLSCTX_DISABLE_AAA.

If this option is not specified, neither of the flags is set in the underlying call to CoCreateInstance.
-model MODELLIST | Specifies which of the COM hosting models are acceptable. MODELLIST must be a list containing one or more of the symbols localserver, remoteserver, inprocserver, inprochandler, or any signifying any model is acceptable.
-nocustommarshal BOOLEAN | If true, the object creation will fail if it uses custom marshalling. Corresponds to the flag CLSCTX_NO_CUSTOM_MARSHAL.

COMOBJ
Without any arguments, returns the value of the default property of the COM object.
COMOBJ NAME ?parameter ...?
The command interprets NAME as a property or method name of the COM object. In case of ambiguity (the object has read and write properties or a method of the same name), the command is interpreted as a property get if no additional parameters are specified, as a property put if exactly one additional parameters is specified and a method invocation otherwise.
COMOBJ -bind SCRIPT
Registers SCRIPT as a script to be invoked in the global scope whenever COMOBJ generates an event notification. The name of the event and any additional parameters in the notification are appended to the script.

The command returns an id. This id must be passed to the -unbind subcommand to unregister the script.

The binding is automatically deleted when COMOBJ is destroyed or may be removed explicitly through the -unbind subcommand.

See COM Events for an example.
COMOBJ -call METHOD ?parameter ...?
Calls the specified COM object method with the given parameters and returns the result if any.
COMOBJ -destroy
Destroys the COM object, removing any bindings and releasing resources.
COMOBJ -get PROPERTY ?parameter ...?
Returns the value of the specified property. Optional parameters may be specified if the property is an indexed property.
COMOBJ -interface
Returns the internal IDispatch pointer. Used for debugging purposes.
COMOBJ -isnull
Returns true if the object is a NULL COM object, false otherwise. This corresponds to a NULL IDispatch pointer that might be returned in some COM operations, for example, to indicate the end of a collection.
COMOBJ -iterate VARNAME SCRIPT
Iterates over items in COMOBJ which must be a COM collection. In each iteration, SCRIPT is executed in the caller's context with VARNAME being set to the value of the current item.

Note that if the item is itself a COM object, VARNAME will contain the name of a TCL command corresponding to that object and must be destroyed when no longer needed (not necessarily within SCRIPT).

See COM Collections for an example.
COMOBJ -print
Prints to stdout the methods and properties of the object. Used for debugging.
COMOBJ -queryinterface IID
Queries the object for a pointer to another interface for the object. Returns a raw handle to the interface.
COMOBJ -set PROPERTY VALUE ?parameter ...?
Sets the value of the specified property. The optional parameters may be specified if the property is an indexed property.
COMOBJ -unbind BINDID
Deletes the COM event binding identified by BINDID.
COMOBJ -with METHODLIST ?parameters ...?
The -with subcommand takes a list of intermediate methods and associated parameters. Each element of this list should itself be a list the first element being the method or property name and remaining elements being the parameters to pass when that method/property is invoked. The method or property should return a new object and the next element in the list is invoked on the previously returned object. The final object created from this list is passed the remaining arguments in the command.

All the intermediate objects created are automatically destroyed.

See Navigating Objects for an example.
progid_to_clsid PROGID
Returns the CLSID for a given PROGID. For example,

(wish) 51 % progid_to_clsid InternetExplorer.Application
{0002DF01-0000-0000-C000-000000000046}

timelist_to_variant_time TIMELIST
Several COM applications store date and time information as type double with the integral part representing the number of days since an epoch and the fractional part representing the time in the day. This command converts TIMELIST to this format. TIMELIST must be a list of 7 elements representing the year, month, day, hour, minutes, seconds and milliseconds.
variant_time_to_timelist DOUBLE
Several COM applications store date and time information as type double with the integral part representing the number of days since an epoch and the fractional part representing the time in the day. This command takes such a time value and returns a list of 7 elements representing the year, month, day, hour, minutes, seconds and milliseconds.

COPYRIGHT

Copyright © 2006-2009 Ashok P. Nadkarni


Windows Shell - Windows Shell

Windows Shell

Windows shell commands

SYNOPSIS

package require twapi

get_shell_folder CSIDL ?-create?
CloseThemeData
GetCurrentThemeName
GetThemeColor
GetThemeFont
invoke_url_shortcut SHORTCUTPATH ?options?
IsAppThemed
IsThemeActive
OpenThemeData
read_shortcut SHORTCUTPATH ?options?
read_url_shortcut SHORTCUTPATH
recycle_file FILENAME ?-confirm BOOLEAN? ?-showerror BOOLEAN?
shell_object_properties_dialog OBJECTPATH ?options?
write_shortcut SHORTCUTPATH ?options?
write_url_shortcut SHORTCUTPATH URL ?-missingprotocol usedefault|guess?

DESCRIPTION

This module provides procedures related to the Windows shell.

Item Identifiers

The Windows shell identifies objects in its namespace, including non-file objects such as Control Panel applets and printers, using an item ID. Similar to a file system path, an object resides within the shell namespace object hierarchy and the entire path to the object is defined by item identifier list.

Folder Paths

The command get_shell_folder returns the path to the directory specified by a Windows Shell CSIDL.

File Operations

The command recycle_file sends the specified file to the Windows Recycle Bin.

Shell Dialogs

The command shell_object_properties_dialog displays the property page dialogs for the specified shell objects.

Themes

The commands OpenThemeData, CloseThemeData, IsThemeActive, IsAppThemed, GetCurrentThemeName, GetThemeColor and GetThemeFont provide access to information related to the current theme if the underlying platform supports themes. See the Windows SDK for documentation about these. TwapiThemeDefineValue is a utility function that translates various theme-related symbols described in the SDk to their integer values to be passed to the above functions.

Shortcuts

The commands read_shortcut and write_shortcut allow reading and writing of shell shortcuts.

The commands read_url_shortcut and write_url_shortcut allow reading and writing of URL shortcuts. A URL shortcut can be invoked by invoke_url_shortcut.

Commands

get_shell_folder CSIDL ?-create?
Returns the path to the file system directory corresponding to the Windows shell folder identified by CSIDL. The path is always returned in native format.

CSIDL must be one of the following symbols or the corresponding integer values values as defined in the Windows SDK: csidl_admintools, csidl_common_admintools, csidl_appdata, csidl_common_appdata, csidl_common_desktopdirectory, csidl_common_documents, csidl_common_favorites, csidl_common_music, csidl_common_pictures, csidl_common_programs, csidl_common_startmenu, csidl_common_startup, csidl_common_templates, csidl_common_video, csidl_cookies, csidl_desktopdirectory, csidl_favorites, csidl_history, csidl_internet_cache, csidl_local_appdata, csidl_mymusic, csidl_mypictures, csidl_myvideo, csidl_nethood, csidl_printhood, csidl_profile, csidl_profiles, csidl_programs, csidl_program_files, csidl_program_files_common, csidl_recent, csidl_sendto, csidl_startmenu, csidl_startup, csidl_system, csidl_templates, csidl_windows.

Refer to the documentation in the Windows SDK for the meaning of each of these identifiers.

If the option -create is specified, the folder will be created if it does not currently exist.

On some platforms, some of the above CSIDL's may be invalid. In this case, the command will attempt to return equivalent paths through other means such as environment variable settings.

The command will return an empty string if the CSIDL does not exist on the platform or if its value cannot be retrieved.
CloseThemeData
See Themes.
GetCurrentThemeName
See Themes.
GetThemeColor
See Themes.
GetThemeFont
See Themes.
invoke_url_shortcut SHORTCUTPATH ?options?
Invokes a URL shortcut. SHORTCUTPATH specifies the path of the URL shortcut itself. The following options may be specified.

-allowui | Allows user interaction.
-hwin HWIN | Specifies the parent window handle for user interaction. This is ignored if -verb is specified or if -allowui is not specified.
-verb VERB | Specifies the verb to invoke on the shortcut, for example open, edit etc.

IsAppThemed
See Themes.
IsThemeActive
See Themes.
OpenThemeData
See Themes.
read_shortcut SHORTCUTPATH ?options?
Reads a shortcut. SHORTCUTPATH specifies the path of the shortcut itself. The contents of the shortcut are returned as a keyed list with the following fields.

-args | Command line arguments for the link.
-desc | Description of the shortcut. This is the string that is visible to the user as the label of the shortcut.
-hotkey | The hotkey associated with the shortcut. This is an integer as described in the documentation of the IShellLink::Hotkey command in the Platform SDK.
-iconindex | The index of the icon within the icon file specifies by the -iconpath field.
-iconpath | The path to the file from which the icon for the shortcut is to be taken.
-idl | The item identifier list for the object pointed to by the shortcut.
-path | The file system path in the case that the shortcut points to a file.
-showcmd | The initial state of the window.
-workdir | The working directory of the shortcut.
Note that the field names are the same as the options for the write_shortcut command so you can modify a shortcut by reading it, changing the specific fields and passing the same list to write_shortcut.

The content format and operation of the command may be controlled through the following options.

-hwin HWIN | Identifies the window to be used as the parent of the dialog box that pops up to ask the user for more information when the shortcut cannot be resolved.
-install | Calls the MSI installer if the shortcut is an advertised shortcut and the target has not been installed yet.
-nolinkinfo | Disables distributed link tracking.
-nosearch | Normally, the command will search for the target if it cannot be found in the location pointed to by the shortcut. Specifying this option disables this search.
-notrack | Specifies that distributed link tracking to be not used.
-noui | Specifies that no dialog box should be displayed even if the link cannot be resolved.
-rawpath | Normally, the command resolves any embedded environment variables contained in the returned -path field and verifies the path exists. Specifying this option disables both these features and returns raw path contained in the shortcut.
-shortnames | The path contained in the returned -path field uses short name (8.3) format.
-timeout TIMEOUT | Specifies the timeout, in milliseconds, for resolving the link. This option has no effect unless the -noui is also specified.
-uncpath | The path contained in the returned -path field is in UNC format.

read_url_shortcut SHORTCUTPATH
Returns the URL pointed to by a URL shortcut. SHORTCUTPATH specifies the path of the URL shortcut itself.
recycle_file FILENAME ?-confirm BOOLEAN? ?-showerror BOOLEAN?
Sends the specified file to the Windows Recycle Bin. Returns true on success and false if user aborted the command. Any errors will generate a Tcl exception.

-confirm BOOLEAN | If true, a confirmation dialog is displayed to the user. Default is false.
-showerror BOOLEAN | If true, an error dialog is displayed to the user in case of errors. Default is false.

shell_object_properties_dialog OBJECTPATH ?options?
Displays the shell property dialog for the specified object which may be a file, a printer or a volume. OBJECTPATH is the path or the name of the object. The following options may be specified:

-hwin HWIN | If specified, HWIN is the handle to the window to be used as the parent for the dialog.
-page PAGENAME | Specifies the name of the property sheet page to be displayed. If unspecified, the default page is displayed.
-type file|printer|volume | Specifies the type of the object identified by OBJECTPATH. If this option is not specified, the command will attempt to figure out the object type and display the appropriate dialog.

write_shortcut SHORTCUTPATH ?options?
Writes or creates a shortcut. SHORTCUTPATH specifies the path of the shortcut itself. The following options control the contents of the shortcut.

-args ARGUMENTS | Specifies the command line arguments for the link.
-desc DESCRIPTION | Specifies the description of the shortcut. This is the string that is visible to the user as the label of the shortcut.
-hotkey HOTKEY | Specifies the hotkey to be associated with the shortcut. HOTKEY should be an integer as described in the documentation of the IShellLink::Hotkey command in the Platform SDK or a symbolic string as described in the register_hotkey command.
-iconindex INDEX | Specifies INDEX as the index of the icon within the icon file specifies by the -iconpath option.
-iconpath ICONPATH | Specifies ICONPATH as the path to the file from which the icon for the shortcut is to be taken.
-idl IDL | Specifies that the shortcut should point to the object identified by the item identifier list IDL. This is useful in cases where the target of the short cut is not a file.
-path TARGETPATH | Specifies TARGETPATH as the file system path that the shortcut to which the shortcut points.
-showcmd WINDOWSTATE | Specifies the initial state of the window. WINDOWSTATE should be one of minimized, maximized or normal.
-workdir DIRPATH | Specifies DIRPATH as the working directory of the shortcut.

write_url_shortcut SHORTCUTPATH URL ?-missingprotocol usedefault|guess?
Writes or creates a URL shortcut. SHORTCUTPATH specifies the path of the URL shortcut itself. URL is the URL to which the shortcut should point.

If the -missingprotocol option is specified, the system will attempt to fill in the protocol if URL itself does not specify a protocol. If the value of this option is guess, the system will attempt to guess the protocol based on the URL string. If the option value is usedefault, the system will use the default protocol scheme.

COPYRIGHT

Copyright © 2004-2009 Ashok P. Nadkarni


Keyboard and mouse input - Keyboard and mouse input

Keyboard and mouse input

Simulation of user input and support for system-wide hotkeys

SYNOPSIS

package require twapi

block_input
click_mouse_button BUTTON
get_input_idle_time
get_mouse_location
move_mouse XPOS YPOS ?-relative?
register_hotkey HOTKEY SCRIPT
send_input INPUTLIST
send_input_text TEXT
send_keys KEYSEQUENCE
turn_mouse_wheel WHEELUNITS
unblock_input
unregister_hotkey HOTKEY_ID

DESCRIPTION

This package provides procedures related to user input on Windows platforms. The commands send_input, send_keys, send_input_text, move_mouse, click_mouse_button and turn_mouse_wheel can be used to simulate user input. The mouse position can be retrieved using get_mouse_location. The commands block_input and unblock_input can be used to prevent interference from real user input while simulating input.

The commands register_hotkey and unregister_hotkey can be used to register scripts to be invoked when the user presses a hotkey combination.

The amount of time elapsed since the last keyboard or mouse input event can be obtained through get_input_idle_time.

Commands

block_input
This command blocks real physical input events and simulated events from threads other than the caller from being entered into the input queue. The command can be used to prevent interference when the commands such as send_input, send_input_text, click_mouse_button are used to simulate user input. The command unblock_input should be called to renable input.

The return value of block_input is 1 if the input was previously unblocked and 0 if the input was already blocked.
click_mouse_button BUTTON
Generates input to simulate clicking the specified mouse button. BUTTON may have one of the values left, right, middle, x1 or x2 to specify the button that was clicked.

Example: Open the system menu with the mouse
get_input_idle_time
Returns the elapsed time in milliseconds since the last keyboard or mouse input event.
get_mouse_location
Returns a pair of integers containing the mouse cursor's X and Y screen coordinates in pixels.
move_mouse XPOS YPOS ?-relative?
Generates input to simulate mouse movement. Movement is in absolute mouse coordinates unless the option -relative is specified. See description of send_input for more details.

Example: Move mouse to system menu
register_hotkey HOTKEY SCRIPT
Registers a script to be invoked when the user presses the hotkey specified by HOTKEY. Note that the script is invoked when the hotkey is pressed even if some other application had the input focus. If the caller had previously registered a script for the same hotkey, it is replaced by SCRIPT.

HOTKEY is a string describing the key combination and consists of 0-4 modifiers followed by the key code, all separated by the - character. A modifier may be one of ctrl (or control), alt (or menu), shift or win. The key code itself may be a single alphanumeric character, one of the virtual key names, such as F9, listed in send_input, or the actual virtual key code itself. Examples are ctrl-alt-a, shift-f9 and ctrl-alt-65.

The command returns an identifier corresponding to the specified hotkey registration. It should be deregistered when no longer needed by calling the unregister_hotkey function.

Example: Start a program when a hotkey is pressed
send_input INPUTLIST
Simulates user input by generating keyboard and mouse events based on INPUTLIST. This must be in the form of a list of sublists, each sublist being a keyboard or mouse input event specification.

A keyboard input specification takes the form

"KEYTYPE VK SCANCODE ?keyopts?".

KEYTYPE may have one of the following values:

key | Specifies a virtual key being pressed and released. This is a more convenient form of specifying consecutive keydown, keyup events. VK should be an integer in the range 1-254 and specifies the virtual key. SCANCODE specifies a hardware scancode for the key. If -usescan is specified in keyopts, the specified scan code is used and VK will be ignored by the system. If -extended is specified in keyopts, the key is treated as an extended key with the scan code being preceded by a byte that has value 0xE0.
keydown | Specifies a virtual key being pressed. VK should be an integer in the range 1-254 and specifies the virtual key. SCANCODE specifies a hardware scancode for the key. keyopts may have the same values as specified for vkey.
keyup | Specifies a virtual key being released. VK should be an integer in the range 1-254 and specifies the virtual key. SCANCODE specifies a hardware scancode for the key. keyopts may have the same values as specified for vkey.
unicode | Specifies a unicode character. SCANCODE should contain the integer corresponding to the unicode character. VK and any keyopts are ignored if specified.

For more detailed information, refer the the documentation of the KEYBDINPUT structure in the Windows SDK.

send_input should generally be used only for the most low level input sequences involving both keyboard and mouse input. The commands send_input_text and send_keys provide more convenient alternatives for sending pure text and a combination of text and special keys respectively.

A mouse input specification takes the form

"mouse XPOS YPOS ?mouseopts?".

Arguments XPOS and YPOS specify the position of the mouse in absolute (default) or relative coordinates. In the former case, the values range from 0 to 65535 and are in mouse coordinates. In the latter case, the values are in pixels. Note when relative mode is used, the system will take into account the mouse speed and acceleration settings. The command move_mouse is much simpler to use unless you have a need to send complex mouse input sequences.

mouseopts may contain one or more of the following options:

-relative | Indicates that XPOS and YPOS should be treated as relative to the last reported position, and not as absolute coordinates.
-ldown | Indicates that the left mouse button has been pressed since the last reported event.
-lup | Indicates that the left mouse button has been released since the last reported event.
-rdown | Indicates that the right mouse button has been pressed since the last reported event.
-rup | Indicates that the right mouse button has been released since the last reported event.
-mdown | Indicates that the middle mouse button has been pressed since the last reported event.
-mup | Indicates that the middle mouse button has been released since the last reported event.
-x1down | Indicates that the first X button has been pressed since the last reported event.
-x1up | Indicates that the first X button has been released since the last reported event.
-x2down | Indicates that the second X button has been pressed since the last reported event.
-x2up | Indicates that the second X button has been released since the last reported event.
-moved | Indicates that the mouse has moved since the last reported event.
-wheel WHEELUNITS | Indicates that the mouse wheel was rotated by WHEELUNITS. This may be a positive integer for forward rotation, or a negative integer for backward rotation. This option may not be used with any of the X button options.
For more detailed information, refer the the documentation of the MOUSEINPUT structure in the Windows SDK.

The commands move_mouse, click_mouse_button and turn_mouse_wheel may be more convenient for common cases.

Example: Draw a square in MS Paint using the mouse

send_input_text TEXT
Simulates user input by generating keyboard events corresponding to TEXT.

Example: Send a text string to a specified window
send_keys KEYSEQUENCE
Simulates user input of keyboard events. This function differs from send_input_text in that the keys generated may include non-text keys such as function keys, modifier keys etc.. KEYSEQUENCE indicates the keys to be generated and is specified with the syntax defined below. This syntax is a superset of the syntax used by the Visual Basic SendKeys command.

All characters in KEYSEQUENCE result in the corresponding keystroke being generated except for the following characters which have a special meaning:

The ~ character stands for the ENTER key.

The +, ^ and % characters are used as key modifiers for the following character or character groups. The + character is used to indicate the following character should be entered as though the SHIFT key was pressed while entering the character. Similarly, ^ and % indicate the CTRL and ALT modifiers respectively. For example, the sequence +ab will result in the following key stroke sequence being generated: SHIFT is pressed and held down, the a key is pressed and released, the SHIFT key is released, and finally the b key is pressed and released.

The ( and ) characters are used to group a set of characters together. This is used for applying a key modifier to a sequence of characters. For example, the sequence +(abc) will result in the following key stroke sequence being generated: SHIFT is pressed and held down and then the keys a, b and c are pressed and released before the SHIFT key is released.

The { and } keys are used to indicate special keys such as function keys and to enter the special characters such as +. Thus, {+} will result in the key + being pressed and released. Similarly, {(} and {}} indicate the character ( and } being entered. As a special case, the form {C N} results in the character C being entered N times. Note that the character may be any character, not just a special character that needs to be escaped.

The other use of the braced escape sequence is to enter special keys. These special sequences and the corresponding generated keystrokes are:

{BACKSPACE} | Backspace
{BACK} | (same as {BACKSPACE})
{BS} | (same as {BACKSPACE})
{BKSP} | (same as {BACKSPACE})
{TAB} | Tab
{CLEAR}
{ENTER} | Enter key on the main keyboard
{RETURN} | (same as {ENTER})
{SHIFT} | Shift (see note below on difference between this and use of the + modifier).
{CONTROL} | Shift (see note below on difference between this and use of the ^ modifier).
{ALT} | Shift (see note below on difference between this and use of the % modifier).
{MENU} | (same as {ALT})
{PAUSE} | Pause
{BREAK} | Break
{CAPSLOCK} | Caps Lock
{CAPITAL} | (same as {CAPSLOCK})
{KANA}
{HANGEUL}
{HANGUL}
{JUNJA}
{FINAL}
{HANJA}
{KANJI}
{ESCAPE} | Escape
{ESC} | (same as {ESCAPE})
{CONVERT}
{NONCONVERT}
{ACCEPT}
{MODECHANGE}
{SPACE} | Spacebar
{PGUP} | Page Up
{PRIOR} | (same as {PGUP})
{PGDN} | Page Down
{NEXT} | (same as {PGDN})
{END} | End
{HOME} | Home
{LEFT} | Left arrow
{UP} | Up arrow
{RIGHT} | Right arrow
{DOWN} | Down arrow
{SELECT}
{PRTSC} | Print Screen key
{PRINT} | Print key
{EXECUTE}
{SNAPSHOT}
{INSERT} | Insert
{INS} | (same as {INSERT})
{DELETE} | Delete
{DEL} | (same as {DELETE})
{HELP} | Help
{LWIN} | Left Windows key
{RWIN} | Right Windows key
{APPS}
{SLEEP}
{NUMPAD0} | Numeric keypad 0
{NUMPAD1} | Numeric keypad 1
{NUMPAD2} | Numeric keypad 2
{NUMPAD3} | Numeric keypad 3
{NUMPAD4} | Numeric keypad 4
{NUMPAD5} | Numeric keypad 5
{NUMPAD6} | Numeric keypad 6
{NUMPAD7} | Numeric keypad 7
{NUMPAD8} | Numeric keypad 8
{NUMPAD9} | Numeric keypad 9
{MULTIPLY} | Numeric keypad *
{ADD} | Numeric keypad +
{SEPARATOR}
{SUBTRACT} | Numeric keypad -
{DECIMAL} | Numeric keypad .
{DIVIDE} | Numeric keypad /
{F1} | Function key F1
{F2} | Function key F2
{F3} | Function key F3
{F4} | Function key F4
{F5} | Function key F5
{F6} | Function key F6
{F7} | Function key F7
{F8} | Function key F8
{F9} | Function key F9
{F10} | Function key F10
{F11} | Function key F11
{F12} | Function key F12
{F13} | Function key F13
{F14} | Function key F14
{F15} | Function key F15
{F16} | Function key F16
{F17} | Function key F17
{F18} | Function key F18
{F19} | Function key F19
{F20} | Function key F20
{F21} | Function key F21
{F22} | Function key F22
{F23} | Function key F23
{F24} | Function key F24
{NUMLOCK} | Numlock
{SCROLL} | Scroll lock
{SCROLLLOCK} | Scroll lock
{LSHIFT} | Left Shift
{RSHIFT} | Right Shift
{LCONTROL} | Left Control
{RCONTROL} | Right Control
{LALT} | Left Alt
{LMENU} | (same as {LALT})
{RALT} | Right Alt
{RMENU} | (same as {RALT})
{BROWSER_BACK} | Back
{BROWSER_FORWARD} | Forward
{BROWSER_REFRESH}
{BROWSER_STOP} | Stop
{BROWSER_SEARCH} | Search
{BROWSER_FAVORITES} | Favorites
{BROWSER_HOME} | Web Home
{VOLUME_MUTE}
{VOLUME_DOWN}
{VOLUME_UP}
{MEDIA_NEXT_TRACK}
{MEDIA_PREV_TRACK}
{MEDIA_STOP}
{MEDIA_PLAY_PAUSE}
{LAUNCH_MAIL}
{LAUNCH_MEDIA_SELECT}
{LAUNCH_APP1}
{LAUNCH_APP2}
Note that use of the braced sequences for the modifier keys such as SHIFT is not the same as the corresponding special characters. For example, the string {SHIFT}a results in the key sequence where the SHIFT key is pressed and released before the a key is pressed. The string +a on the other hand results in a key sequence where the SHIFT key is released after the a is pressed and released.

Example: Send an exit command using menu shortcuts

turn_mouse_wheel WHEELUNITS
Generates input to simulate turning the wheel. A positive value of WHEELUNITS simulates forward rotation by the specified number of units, a negative value simulates backward rotation.
unblock_input
This command reverses the effect of a previous call to block_input.

The return value of unblock_input is 1 if the input was previously blocked and 0 if the input was already unblocked.
unregister_hotkey HOTKEY_ID
Unregisters a hot key that was previously registered. HOTKEY_ID should be a hotkey identifer returned by a previous call to register_hotkey.

Example: Start a program when a hotkey is pressed

COPYRIGHT

Copyright © 2003, 2004, Ashok P. Nadkarni


Sound - Playing sounds

Sound

Basic sound functions

SYNOPSIS

package require twapi

beep ?options?
play_sound NAME ?options?
stop_sound

DESCRIPTION

This package provides commands for playing sounds on Windows platforms. Overview The commands beep, play_sound and stop_sound provide basic functions for generating sound. For more sophisticated needs, there are other Tcl extensions available, such as the Snack Sound Toolkit.

Commands

beep ?options?
Generates a sound on the system speaker. The following options may be specified:

-frequency FREQUENCY | The frequency of the sound to be produced (default 1000 Hz).
-duration MILLISECONDS | The duration of the sound to be produced (default 100 milliseconds).
-type SOUNDIDENTIFIER | Specifies the type of sound to produce. SOUNDIDENTIFIER may be one of ok, hand, question, exclamation or asterisk. These will produce the corresponding sounds configured in the Windows control panel. If this option is specified, the options -duration and -frequency are ignored.
Example: Generate a continuous tone

play_sound NAME ?options?
Plays a sound on the system audio device. The sound may either be a WAV file or a system defined sound (if the -alias option is specified). The command returns 1 if successful else 0.

The following options may be specified to control the sound:

-alias | By default, NAME is assumed to be the path of a WAV file. If -alias is specified, NAME is assumed to be the name of a system sound. The following system defined sounds are guaranteed to be present on all systems: SystemAsterisk, SystemExclamation, SystemExit, SystemHand, SystemQuestion and SystemStart. Other system defined names can be located under the HKEY_CURRENT_USER\AppEvents\EventLabels registry key. Note that a sound will only be played if a WAV file has been associated with it through the control panel.
-async | If specified, the sound is played asynchronously and command will return immediately. By default, the command will return only after the sound has completed playing.
-loop | Specification of this option causes the sound to be played repeatedly until stopped through a stop_sound command. This option also automatically enables the -async option.
-nodefault | If the system cannot find the specified sound, it plays a default sound file. If this option is specified, the command will return without playing any sound if the specified sound file is not found.
-nostop | Normally, the audio device is playing some other file, the command will attempt to stop the currently playing sound. If -nostop is specified, the command will return immediately without attempting to stop the current sound.
-wait | If the audio driver is busy, the command will return right away. If this option is specified, the command will wait for the driver to become available.
Example: Play a system sound

Example: Play a continous system sound

Example: Play a WAV file

stop_sound
Stops all currently playing sounds that have been started by the current task. Returns 1 if successful, else 0.

Example: Play a continous system sound

COPYRIGHT

Copyright © 2003, Ashok P. Nadkarni


Clipboard - Clipboard access

Clipboard

Commands related to accessing the clipboard

SYNOPSIS

package require twapi

clipboard_format_available FORMAT
close_clipboard
get_clipboard_formats
get_registered_clipboard_format_name FORMAT
open_clipboard
read_clipboard FORMAT
read_clipboard_text ?-raw?
register_clipboard_format FORMATNAME
start_clipboard_monitor SCRIPT
stop_clipboard_monitor MONITOR_ID
write_clipboard FORMAT DATA
write_clipboard_text TEXT

DESCRIPTION

This module provides procedures to read and write the clipboard.

Overview

The command read_clipboard and write_clipboard allow reading and writing to the Windows clipboard. Tcl/Tk has a clipboard command that provides similar functionality. The TWAPI commands are useful in two circumstances:

  • The Tcl clipboard command is not available in console-based Tcl programs that do not load Tk. The TWAPI command may be used to access the clipboard in this case.
  • More control is desired over the specific format of the data stored into the clipboard.
In other cases, the Tcl/Tk clipboard command should be preferred.

Clipboard formats

Data may be stored in the clipboard in any number for formats identified by integer values. When reading clipboard data, applications must check in what formats the current clipboard data is currently available and specify one of these formats when reading the data. Similarly, when writing data to the clipboard, applications need to specify the format in which data is to stored in the clipboard. In some cases, Windows will automatically make multiple formats available. For example, storing text in format type 1 (text) will also make format type 13 (Unicode) available in the clipboard.

In addition to the standard set of formats defined by Windows applications may register their own formats with the system. The format values associated with these are created the first time the format name is registered through register_clipboard_format and can be retrieved later with the same call. Conversely, the name associated with a format can be obtained through the get_registered_clipboard_format_name command. An example of a registered application format name is "HTML Format" which is used by Internet Explorer to store HTML fragments on the clipboard.

Multiple formats may be simultaneously stored into the clipboard. The formats currently stored in the clipboard may be obtained through the get_clipboard_formats command.

When reading or writing data, the application is responsible for formatting data appropriately, possibly through the use of Tcl's binary command. The exceptions to this are the read_clipboard_text and write_clipboard_text commands which assume the data is just text.

Reading and Writing Data

In the general case, the clipboard must first be opened with the open_clipboard call before data can be read or written to it. Data may be read and written using the read_clipboard and write_clipboard commands respectively. The clipboard must then be closed by calling close_clipboard. There may be multiple write commands between the clipboard open and close to store data in multiple formats.

For the simple case of reading and storing text data, the commands write_clipboard and write_clipboard_text may be used.

Monitoring clipboard changes

An application can monitor the clipboard by calling start_clipboard_monitor to set up a notification callback that is invoked when the contents of the clipboard change.

Commands

clipboard_format_available FORMAT
Returns 1 if the clipboard contains data in the specified format, and 0 otherwise. This command does not require the clipboard to have been opened.
close_clipboard
Closes the clipboard which must have been previously opened with open_clipboard.

Example: Copy standard input to the clipboard
get_clipboard_formats
Returns a list of the formats currently available in the clipboard. The clipboard must have been opened before this function is called.

Example: Get HTML format data from the clipboard
get_registered_clipboard_format_name FORMAT
Returns the name associated with a registered clipboard format. FORMAT identifies the format and must correspond to a registered format. An exception will be raised if FORMAT is a standard Windows format or a unregistered private format.
open_clipboard
Opens the clipboard for reading or writing. Most clipboard operations require the clipboard to have been previously opened. The clipboard must be closed once the operations are done by calling close_clipboard.

Example: Copy standard input to the clipboard
read_clipboard FORMAT
Reads the contents of the clipboard in the given format and returns it. The clipboard must have been previously opened through open_clipboard and remains open when the command returns except in the case of any Tcl exceptions. In these cases, the clipboard is closed before the exception is thrown.

FORMAT must be one of the clipboard formats as defined in Clipboard formats. The content is an exact copy of the contents of the clipboard in binary format. Callers will need to use Tcl commands such as binary and encoding to parse the data.

Example: Get HTML format data from the clipboard
read_clipboard_text ?-raw?
Retrieves the content of the clipboard as text. The clipboard must have been previously opened through open_clipboard and remains open when the command returns except in the case of any Tcl exceptions. In these cases, the clipboard is closed before the exception is thrown.

Normally the command converts CR-LF line terminators in clipboard content to LF line terminators. If the -raw option is specified, the command does no conversion of the clipboard data.

Example: Copy clipboard contents to standard output
register_clipboard_format FORMATNAME
Registers an application defined format with the system (see Clipboard Formats). FORMATNAME is the name associated with the format. The command returns an integer format identifier that may be used in calls to read and write data. If the format name is already registered, the same integer format value is returned. This command does not require the clipboard to be open.

Example: Get HTML format data from the clipboard
start_clipboard_monitor SCRIPT
Begins monitoring of clipboard contents. SCRIPT will be invoked when the clipboard is written to by any application.

The command returns a handle. When no longer required, this handle must be passed to the command stop_clipboard_monitor.

Multiple clipboard monitoring scripts may be active at the same time. However, all returned handles must be passed to stop_clipboard_monitor. before the application exits.
stop_clipboard_monitor MONITOR_ID
Stops a previously registered script that monitors clipboard contents. MONITOR_ID is monitoring handle previously returned by start_clipboard_monitor.
write_clipboard FORMAT DATA
Writes DATA to the clipboard in the given format. The clipboard must have been previously opened through open_clipboard and remains open when the command returns except in the case of any Tcl exceptions. In these cases, the clipboard is closed before the exception is thrown.

FORMAT must be one of the clipboard formats as defined in Clipboard formats. The content is an exact copy of the contents of the clipboard in binary format. Callers will need to use Tcl commands such as binary and encoding to parse the data.

Multiple write_clipboard commands may be executed between a open_clipboard and close_clipboard pair as long as the specified formats are different for each. Writing a format previously specified in the sequence overwrites the previous contents of that format.
write_clipboard_text TEXT
Writes the given text string to the clipboard. The clipboard must have been previously opened through open_clipboard and remains open when the command returns except in the case of any Tcl exceptions. In these cases, the clipboard is closed before the exception is thrown.

Example: Copy standard input to the clipboard

COPYRIGHT

Copyright © 2004-2009 Ashok P. Nadkarni


System - System and processor

System

Operating system and machine configuration and control

SYNOPSIS

package require twapi

abort_system_shutdown ?-system SYSTEM?
find_domain_controller ?options?
get_active_processor_mask
get_computer_name ?NAMETYPE?
get_computer_netbios_name
get_memory_info ?options?
get_primary_domain_controller ?options?
get_primary_domain_info ?options?
get_os_description
get_os_info
get_os_version
get_processor_count
get_processor_info PROCESSOR ?options?
get_system_info ?options?
get_system_parameters_info PARAMETER
get_system_time
get_system_uptime
lock_workstation
logoff ?-force? ?-forceifhung?
min_os_version osmajor ?osminor? ?spmajor? ?spminor?
set_system_parameters_info PARAMETER VALUE ?-persist? ?-notify?
shutdown_system ?options?
suspend_system ?options?

DESCRIPTION

This module provides commands related to the system configuration including operating system functions and hardware configuration.

Overview

The commands get_os_version and min_os_version get and verify operating system version information.

The commands get_os_info and get_os_description allow retrieval of more detailed operating system information than the standard Tcl commands which do not distinguish between service packs, Professional versus Server versions and so on.

The command get_system_info returns information about the current system.

The command get_computer_name returns one of several forms of the system name. The command get_computer_netbios_name returns the NETBIOS name of the computer. Domain and workgroup information about the system can be obtained through the get_primary_domain_info command. find_domain_controller returns information about a domain controller with specified characteristics. get_primary_domain_controller returns the name of the primary domain controller of the computer.

The commands get_processor_count, get_active_processor_mask and get_processor_info retrieve information about the processors in the system including type and utilization.

The command get_memory_info returns the physical and virtual memory configuration of the system.

The command get_system_time returns the current system time in high resolution. The command get_system_uptime returns the how long the system has been running. The command shutdown_system may be used to shutdown or reboot the system. The command abort_system_shutdown may be used to abort an ongoing system shutdown. The commands logoff and lock_workstation may be used to log out of a user account and to lock a workstation respectively.

Various system settings related to the user experience can be retrieved and set through the get_system_parameters_info and set_system_parameters_info commands.

Commands

abort_system_shutdown ?-system SYSTEM?
Aborts a previously initiated system shut down or reboot. Note this is only possible if the system shutdown was initiated with a non-zero timeout value. The command enables any required privileges and restores the original privileges before returning.
find_domain_controller ?options?
Returns the name of a domain controller with specified characteristics and optionally, details about its characteristics and capabilities.

-allowstale BOOLEAN | If specified as true, the system will return cached domain controller information even if it is marked as expired. Default is false. This option has no effect if -rediscover is specified as true.
-avoidself BOOLEAN | If specified as true, and the command is run on a domain controller, the domain controller will return the name of another domain controller, not itself. Default is false.
-domain DOMAINNAME | Specifies the domain whose domain controller is to be retrieved. If unspecified, defaults to the primary domain of the computer.
-domainguid GUID | If the domain specified by the -domain option or the primary domain of system cannot be found, the command will attempt to return the domain controller for the domain with the specified GUID.
-getdetails | By default, the command returns the name of the domain controller. If this option is specified, the command returns detailed information whose format is described below.
-inputnameformat NAMEFORMAT | Specifies the format of the specified domain name. NAMEFORMAT may be one of dns, which implies DNS format, flat which implies flat Netbios format, or any (default) which results in the command searching both namespaces.
-justldap BOOLEAN | If specified as true, the command searches for a LDAP server without caring if it is a domain controller.
-rediscover BOOLEAN | If specified as true, the system ignores any cached domain controller data. Default is false. Note specifying this option as true significantly increases the time to execute the command.
-outputaddrformat ADDRFORMAT | If ADDRFORMAT is specified as ip, the -dcaddr field in the returned information is the Internet address.
-outputnameformat NAMEFORMAT | Specifies the format in which the domain controller and domain names should be returned. NAMEFORMAT may be one of dns, which implies DNS format, flat which implies flat Netbios format, or any (default). The command will raise an error if the name is not available in the specified format.
-prefer FEATURELIST | Indicates that the domain controller that support the specified features and services is returned in preference to one that does not. FEATURELIST is a list of zero or more elements from directoryservice and timeserver (see below).
-require FEATURELIST | Indicates that the domain controller to be returned must support the specified features and services. FEATURELIST is a list of zero or more features from the following: directoryservice (Active Directory support), globalcatalog (global catalog server for the forest rooted by this domain), pdc (primary domain controller for this domain) kdc (Kerberos Key Distribution center service) timeserver (running Windows Time Service) writable (must not be read-only). Note that the features pdc, kdc and globalcatalog are mutually exclusive and must not be specified together.
-site SITENAME | Specifies the name of the site where the domain controller should be physically located. If an empty string (default), the command will attempt to return a controller in a site that is closest to the site of the system specified by the -system option.
-system COMPUTERNAME | Specifies the DNS or NETBIOS name of the computer on which the lookup is to be done. If unspecified, defaults to the local system.
If the -getdetails option is specified, the command returns detailed information about the controller instead of just its name. The returned information is a flat list of key value pairs with the following elements:

-clientsite | The name of the site containing the system specified by the -system option.
-dcname | Name of the domain controller which may be either in DNS or Netbios format.
-dcnameformat | Either dns if the -dcname field is in DNS format, or netbios if it is a Netbios name.
-dcaddr | Address of the domain controller. This may be either the Netbios address or the IP address depending on the value of the specified -outputaddrformat option.
-dcaddrformat | Either ip if the -dcaddr field is in IP address format, or netbios if it is a Netbios address.
-dcsite | The name of the site containing the domain controller.
-dnsforest | Name of the domain that is at the root of the directory service tree.
-dnsforestformat | Either dns if the -dnsforestformat field is in DNS format, or netbios if it is a Netbios name.
-domainguid | GUID of the domain.
-domain | Name of the domain.
-domainformat | Either dns if the -domain field is in DNS format, or netbios if it is a Netbios name.
-features | Contains a list describing domain controller features. This list may contain zero or more of the following: directoryservice (Active Directory support), globalcatalog (global catalog server for the forest rooted by this domain), pdc (primary domain controller for this domain), kdc (Kerberos Key Distribution center service), timeserver (running Windows Time Service), goodtimeserver (running Windows Time Service with a physical clock), writable (is not read-only).
Note that any of these fields may have empty string values if the information is not relevant or cannot be found.

get_active_processor_mask
Returns a mask representing the processors configured into the system.
get_computer_name ?NAMETYPE?
Returns the name of the computer. NAMETYPE must be one of the following:

netbios | Returns the NETBIOS name of the local computer or the cluster virtual server if it is in a cluster.
dnshostname | Returns the DNS host name of the local computer or the cluster virtual server if it is in a cluster.
dnsdomain | Returns the DNS domain of the local computer or the cluster virtual server if it is in a cluster.
dnsfullyqualified | Returns the fully qualified DNS domain of the local computer or the cluster virtual server if it is in a cluster.
physicalnetbios | Returns the NETBIOS name of the local computer.
physicaldnshostname | Returns the DNS host name of the local computer.
physicaldnsdomain | Returns the DNS domain of the local computer.
physicaldnsfullyqualified | Returns the fully qualified DNS name of the local computer.
If NAMETYPE is not specified, it defaults to netbios.

get_computer_netbios_name
Returns the NETBIOS name of the computer.

Example: print the computer name
get_memory_info ?options?
Returns various information about the physical and virtual memory configuration of the system. The information returned is in the form of a flat list of the form "field1 value1 field2 value2 ..." depending on which of the following options are specified:

-all | Returns all the options listed below.
-allocationgranularity | Returns the granularity with which virtual memory is allocated.
-availcommit | Returns the amount of free virtual memory available to commit.
-availphysical | Returns the amount of free physical memory.
-maxappaddr | Returns the highest address that may be mapped into an application's address space.
-minappaddr | Returns the lowest address that may be mapped into an application's address space.
-pagesize | Returns the size of a virtual memory page
-swapfiles | Returns a list of the swap files for the system.
-swapfiledetail | Returns a flat list of pairs corresponding to the swap files. The first element of each pair is the name of the swap file. The second element is a list of consisting of the current size of the file (in pages), the number of pages in use, and the peak number of pages that have been used in the file.
-totalcommit | Returns the maximum amount of virtual memory that can be committed without extending the swap files.
-totalphysical | Returns the total amount of physical memory installed in the system.
Example: Show virtual memory statistics

get_primary_domain_controller ?options?
Returns the primary domain controller (PDC) for a domain. The command find_domain_controller should be preferred to this command.

The following options may be specified:

-domain DOMAINNAME | Specifies the domain whose PDC is to be retrieved. If unspecified, defaults to the primary domain.
-system COMPUTERNAME | Specifies the DNS or NETBIOS name of the computer on which the lookup is to be done. If unspecified, defaults to the local system.

get_primary_domain_info ?options?
Returns information about the primary domain or workgroup of the system as a flat list of option value pairs. The following options control what information is returned.

-all | Equivalent to specifying all options.
-dnsdomainname | Returns the DNS name of the primary domain.
-dnsforestname | Returns the DNS forest name of the primary domain.
-domainguid | Returns the GUID of the primary domain.
-name | Returns the domain or workgroup name.
-sid | Returns the SID of the primary domain.
-type | Returns workgroup or domain depending on whether the system belongs to a workgroup or a domain.
If the system belongs to a workgroup, all options will return empty values except -name and -type.

get_os_description
This commmand returns the same operating system information as returned by get_os_info but in a form suitable for displaying to a user.
get_os_info
This command retrieves operating system version and configuration information and returns a keyed list with the following fields:

platform | String identifying the operating system base platform. Currently this is always NT.
os_major_version | Major operating system version.
os_minor_version | Minor operating system version.
sp_major_version | Major service pack version.
sp_minor_version | Minor service pack version.
os_build_number | Contains the operating system build number.
system_type | Indicates the operating system base type. This is workstation for Windows NT 4.0 Workstation, Windows 2000 Professional, or any Windows XP operating system versions. If the system is a domain controller, this value is domain_controller. In all other cases, this value is server.
suites | Contains a list of values (see below) that indicate various options that may be installed as part of the operating system.
The suites element in the returned array contains a list of values from the following set that indicates additional operating system components that are present:

backoffice | Microsoft BackOffice components are installed
blade | Windows .NET Server 2003 family Web Edition is installed
terminal | Terminal Services are installed
datacenter | Windows 2000 Datacenter Server or Windows .NET Server 2003 family Datacenter Edition is installed
enterprise | Windows NT 4.0 Enterprise Edition, Windows 2000 Advanced Server, or Windows .NET Server 2003 family Enterprise Edition is installed
smallbusiness | Microsoft Small Business Server is installed
smallbusiness_restricted | Microsoft Small Business Server is installed with the restrictive client license in force
personal | Windows XP Home Edition is installed
pagesize | Contains the number of bytes in a page
min_app_addr | Contains the lowest possible address in the application's virtual memory space.
max_app_addr | Contains the highest possible address in the application's virtual memory space.
allocation_granularity | Contains the granularity of virtual memory allocation.
Example: check if terminal services are present

get_os_version
This command returns the operating system version as list of four elements - the operating system major version number, the operating system minor version number, the service pack major version number, the service pack minor version number.

Example: verify if a service pack is installed
get_processor_count
Returns the number of processors in the system.
get_processor_info PROCESSOR ?options?
Returns various pieces of information related to the processors in the system. PROCESSOR identifies the processor whose information is to be retrieving. If specified as an empty string, information across all processors in the system is returned. The information returned is in the form of a flat list of the form "field1 value1 field2 value2 ...". The fields returned depend on the specified options and their values may be scalars (e.g. -name) or rate based measured over an interval (e.g. -processorutilization). The option -interval may be used to indicate the interval over which the rate based fields are measured. One of more of the following options may be specified with the command:

-all | Returns all fields listed below.
-apcbypassrate | Returns the field apcbypassrate which is the rate (per second) that kernel APC interrupts were bypassed as computed over the measured interval.
-arch | Returns the processor architecture.
-dpcbypassrate | Returns the field dpcbypassrate which is the rate (per second) that deferred procedure calls were avoided as computed over the measured interval.
-dpcqueuerate | Returns the field dpcqueuerate containing the rate at which deferred procedure calls are being added to the DPC queue as measured over the specified interval.
-dpcrate | Returns the field dpcrate containing the rate at which deferred procedure calls are being added to the DPC queue. This rate is based on the observed value over the last two timer ticks of the processor clock, and not that over the measured interval.
-dpctime | The amount of CPU time in 100ns units spent in servicing deferred procedure calls. Note this value is included in the -privilegedtime value.
-dpcutilization | Returns the field dpcutilization containing the percentage of time that this processor has spent servicing deferred procedure calls over the measured interval. This is included in the privilegedutilization value.
-idletime | The amount of idle CPU time in 100ns units since system start. Note this value is included in the -privilegedtime value.
-interrupts | Returns the total number of interrupts serviced since system start.
-interruptrate | Returns the field interruptrate containing the number of hardware interrupts being processed per second over the measured interval.
-interrupttime | The amount of CPU time in 100ns units spent in servicing interrupts. Note this value is included in the -privilegedtime value.
-interruptutilization | Returns the field interruptutilization containing the percentage of time that this processor has spent servicing interrupts over the measured interval. This is included in the privilegedutilization value.
-privilegedtime | The amount of privileged (kernel) context CPU time since system start in 100ns units. Note this includes the DPC, interrupt and idle CPU cycles.
-privilegedutilization | Returns the field privilegedutilization containing the percentage of time that this processor has spent executing a non-idle thread in privileged mode during the measured interval.
-processormodel | Returns the processor model. PROCESSOR must not be an empty string if this option is specified.
-processorname | Returns a human readable form of the processor description. PROCESSOR must not be an empty string if this option is specified.
-processorrev | Returns the processor revision as defined by the CPU manufacturer. PROCESSOR must not be an empty string if this option is specified.
-processorspeed | Returns the nominal speed in Mhz of the processor PROCESSOR must not be an empty string if this option is specified.
-processorutilization | Returns the field processorutilization containing the percentage of CPU time that this processor has been executing a non-idle thread over the measured interval.
-processorlevel | Returns the processor level as defined by the CPU manufacturer.
-usertime | The amount of user context CPU time in 100ns units since the system was started.
-userutilization | Returns the field userutilization containing the percentage of time that this processor has spent executing a non-idle thread in user mode during the measured interval.

get_system_info ?options?
Returns various pieces of information related to the system. The information returned is in the form of a flat list of the form "field1 value1 field2 value2 ...". One of more of the following options may be specified with the command to control what information is returned:

-all | Returns all fields listed below.
-eventcount | Returns the number of synchronization events in use.
-handlecount | Returns the number of handles that are currently open.
-mutexcount | Returns the number of synchronization mutexes in use.
-processcount | Returns the number of processes that are currently running.
-sectioncount | Returns the number of sections in use.
-semaphorecount | Returns the number of synchronization semaphores in use.
-sid | Returns the SID of the system.
-threadcount | Returns the number of threads that are currently running.
-uptime | Returns the number of seconds elapsed since the system was booted.

get_system_parameters_info PARAMETER
This command wraps the Windows SystemParametersInfo function and allows retrieval of various user interface settings such as screensaver timeout, mouse speed etc. The information retrieved depends on the PARAMETER which must be one of the SPI_ symbols listed in the SystemParametersInfo documentation.
get_system_time
Returns the current system time in UTC as the number of 100 nanosecond units since Jan 1, 1601. This can be converted to a format suitable for use with the clock command through the use of the command large_system_time_to_secs_since_1970.
get_system_uptime
Returns the number of seconds elapsed since the system was booted.
lock_workstation
Initiates a request to lock the work station display.
logoff ?-force? ?-forceifhung?
Logs off the current session. If -force is specified, it forces processes to terminate without notifying them. This options should generally not be specified as it can result in data loss. If -forceifhung is specified, it only terminates processes if they do not respond to the session end notifications.
min_os_version osmajor ?osminor? ?spmajor? ?spminor?
This function checks that the operating system version meets the specified minimum version. It returns 1 if the operating system version is greater than osmajor.osminor.spmajor.spminor. Otherwise it returns 0. Any unspecified optional arguments default to 0.
set_system_parameters_info PARAMETER VALUE ?-persist? ?-notify?
This command wraps the Windows SystemParametersInfo function and allows setting of various user interface settings such as screensaver timeout, mouse speed etc. The information retrieved depends on the PARAMETER which must be one of the SPI_ symbols listed in the SystemParametersInfo documentation. The corresponding setting is assigned VALUE.

If the -persist is specified, the changed setting is written to the user's profile. If -notify is specified, all applications are notified of the change. Note -notify only has effect if -persist is also specified since other applications will update based on the user's persistent profile.
shutdown_system ?options?
Initiates a system shut down or reboot. The command enables any required privileges and restores the original privileges before returning.

The following options may be specified:

-system SYSTEMNAME | Specifies the system to be shut down. By default, this is the local system.
-timeout SECONDS | Specifies the amount of time to wait before shutting down the system. During this time, a shutdown dialog is displayed to the user. If a value of 0 is specified, the system is shut down immediately and no dialog is displayed to the user.
-message MESSAGE | Specifies a message to be displayed to the user in the shutdown dialog.
-force | Normally, the system displays a dialog box asking the user to close any applications with unsaved data. If the -force option is specified, applications are forcible closed resulting in possible data loss.
-restart | If specified, the system is restarted after the shut down.

suspend_system ?options?
Places the system in a stand by or hibernate state. The command takes the following options:

-state STATE | STATE must be one of standby (default) or hibernate depending on whether the state into which the system is to be placed.
-force BOOLEAN | If false (default), the system sends a PBT_ATMQUERYSUSPEND message to all applications before placing the system in stand by or hibernate states. If this option is specified as true, the message is not sent and the system is immediately placed into the appropriate state.
-disablewakeevents BOOLEAN | If false (default), system wake events remain enabled. If true they are disabled.

COPYRIGHT

Copyright © 2003-2009 Ashok P. Nadkarni


Processes, threads and DLLs - Processes, threads and shared libraries

Processes, threads and DLLs

Commands related to processes, threads and dynamic link libraries

SYNOPSIS

package require twapi

create_process PROGRAM ?options?
end_process PID ?options?
free_library HMODULE
get_current_process_id
get_current_thread_id
get_device_drivers ?options?
get_priority_class PID
get_process_commandline PID
get_process_exit_code HPROCESS
get_process_handle PID ACCESSRIGHTS ?INHERITMODE?
get_process_ids ?options?
get_process_info PID ?options?
get_process_modules PID ?options?
get_process_name PID
get_process_parent PID
get_process_path PID
get_process_thread_ids PID
get_thread_handle TID ACCESSMODE ?INHERITMODE?
get_thread_info TID ?options?
get_thread_relative_priority TID
get_thread_parent_process_id TID
is_idle_pid PID
is_system_pid PID
load_library FILEPATH ?options?
process_exists PID ?options?
process_waiting_for_input PID ?-wait MILLISECONDS?
resume_thread TID
set_priority_class PID PRIORITYCLASS
set_thread_relative_priority TID PRIORITY
suspend_thread TID

DESCRIPTION

This module provides procedures related to process, thread and shared library management.

Overview

The commands get_process_ids and get_current_process_id retrieve process id (PID) information. get_process_parent returns the PID for the parent process. The commands is_system_pid and is_idle_pid determine if the given PID is that of the system or idle process.

The command get_current_thread_id retrieves the current thread id (TID). get_thread_parent_process_id retrieves the PID of the process containing the specified thread. get_process_thread_ids retrieves the TID's of all threads in the specified process.

Process and thread handles with the appropriate access rights may retrieved through the get_process_handle and get_thread_handle commands respectively.

get_process_name and get_process_path get the name and path respectively for a process. The command get_process_info retrieves detailed information about internal process data. Similarly, get_thread_info retrieves detailed information about a thread.

get_process_commandline retrieves the command line with which a process was invoked.

process_exists checks for the existence of a process. The command process_waiting_for_input can be used to check if a process is waiting for input, and more specifically if it has finished initialization.

get_process_modules retrieves information pertaining to the modules and DLL's loaded into a process. The commands load_library and free_library can be used to load and free DLL's.

The commands create_process and end_process allow creation and termination of a process. The exit code from a process can be retrieved with the get_process_exit_code command.

The commands suspend_thread and resume_thread allow threads to be suspended and resumed.

The commands get_priority_class, set_priority_class, get_thread_relative_priority and set_thread_relative_priority deal with retrieving and setting process and thread scheduling priorities.

get_device_drivers retrieves information about the device drivers loaded on the system.

Commands

create_process PROGRAM ?options?
Creates a new child process. PROGRAM specifies the program to be run and must either include the full path to the program or the program must be in the current working directory. The function does not search the PATH environment variable to locate the program. PROGRAM may be specified as an empty string if the -cmdline option is specified and includes the path to the program as the first argument.

The command returns a list of two elements - the process id and the thread id of the child process. If the -returnhandles option is specified, two additional elements are returned - handles to the child process and thread. Both these handles must be closed when no longer required by calling close_handles.

The following arguments control various characteristics of the child process. For all options that take a boolean argument, the default is 0 (false) unless stated otherwise.

-background COLORLIST | Specifies the background color if the child process receives a new console. COLORLIST is a list of one or more of the following values: blue, red, green, bright, white and black. The specified colors are combined to form the foreground color. The default is black.
-cmdline CMDLINE | Specifies the command line to be passed to the created process. This generally includes the program being executed as the first token in CMDLINE. Caller should ensure that CMDLINE is quoted appropriately. The -cmdline option must be specified if the PROGRAM parameter is empty.
-childprocesssecd SECURITY_DESCRIPTOR | Specifies a security descriptor for the child process. If unspecified, the default security descriptor is used.
-childthreadsecd SECURITY_DESCRIPTOR | Specifies a security descriptor for the child thread. If unspecified, the default security descriptor is used.
-createsuspended BOOLEAN | If BOOLEAN is true, the process and thread are created suspended. The process will not run until the thread is resumed with a call to resume_thread.
-debugchild BOOLEAN | If BOOLEAN is true, indicates that the calling thread will be debugging the child process being created. The thread is notified of debug events in the child process. There is currently no way to receive these events.
-dontdebugchild BOOLEAN | If the calling process is itself being debugged, then any debug events from the child process are sent to the debugger if BOOLEAN is false. Otherwise, the child process has no interaction with the debugger.
-desktop DESKTOPNAME | Specifies the desktop, optionally along with the window station, for the new process. By default, this is the same as the current process. If DESKTOPNAME is the empty string, the system determines if a new desktop and window station need to be created.
-detached BOOLEAN | This option only affects console processes. If BOOLEAN is 0, the child process inherits the current process' console. If BOOLEAN is 1, the console is not inherited.
-env LIST | Specifies the environment variables inherited by the child process. LIST is a flat list of the form returned by array get consisting of ENVVARNAME VALUE pairs. By default, the child process inherits the same environment variables as the current process.
-feedbackcursoron BOOLEAN | If true, specifies that the feedback cursor (normally a pointer with an hourglass) is shown while the new process starts up.
-feedbackcursoroff BOOLEAN | If true, specifies that the feedback cursor is not shown while the new process starts up.
-foreground COLORLIST | Specifies the foreground color if the child process receives a new console. COLORLIST is a list of one or more of the following values: blue, red, green, bright, white and black. The specified colors are combined to form the foreground color. The default is white.
-fullscreen BOOLEAN | If true, the child process is run in full screen mode if it is a console process.
-inheritablechildprocess BOOLEAN | If true, the handle to the child process is inheritable by other child processes spawned off later.
-inheritablechildthread BOOLEAN | If true, the handle to the thread in the child process is inheritable by other child processes spawned off later.
-inheriterrormode BOOLEAN | If true (default), the child process inherits the error mode setting of the current process.
-inherithandles BOOLEAN | If true, the child process will inherit all inheritable handles of the current process.
-newconsole BOOLEAN | If true, a new console is created for the child process if it is a console mode program. By default, the child process inherites the console of the current process if that latter is also a console mode program. This option cannot be used with the -detached option.
-priority PRIORITY | Specifies the priority of the child process. This should have one of the values normal, abovenormal, belownormal, high, realtime, or idle.
-returnhandles BOOLEAN | Normally the create_process command returns only the ids of the created process and thread. If this option is specified as true, the command appends handles of the child process and thread to the return value. These must later be closed by calling the close_handles command.
-screenbuffersize XY | For console processes, this controls the initial width and height of the screen buffer in characters. XY can be specified as either a list of two integers or as a X,Y string.
-separatevdm BOOLEAN | If true, child processes that are 16-bit executables are started in a separate virtual machine. By default, the system will follow the setting specified in the registry.
-sharedvdm BOOLEAN | If true, child processes that are 16-bit executables are started in a common virtual machine. By default, the system will follow the setting specified in the registry.
-showwindow WINDOWMODE | Specifies the mode in which the first window of the child process is displayed. WINDOWMODE must be one of normal, minimized, maximized or hidden.
-startdir PATH | Specifies the initial starting directory of the child process. By default the child process starts in the calling thread's current directory.
-stdhandles HANDLELIST Specifies the standard input and output handles for the child process. HANDLELIST is a list of three elements corresponding to the handles to be used for standard input, standard output and standard error respectively. The handle values passed must be Windows handles and must be inheritable. Also, the -inherithandles option must be true if -stdhandles is specified. Note that if these handles correspond to files, the file position pointer is shared with the child process.

This option cannot be used together with the -stdchannels option.
-stdchannels CHANNELS Specifies the standard input and output handles for the child process. CHANNELS is a list of three elements corresponding to the Tcl channels to be used for standard input, standard output and standard error respectively. Note that if these channels correspond to files, the file position pointer is shared with the child process.

This option cannot be used together with the -stdhandles option. Also, the -inherithandles option must be true if -stdchannels is specified.
-title TITLE | Specifies the text to diaplay in the title bar if the child process is a console program and receives a new console. By default, the name of the executable is displayed.
-windowpos XY | Specifies the initial position in pixels of the top left corner of the main window of the child process if the child creates the window using defaults. XY can be specified as either a list of two integers or as a X,Y string.
-windowsize XY | Specifies the initial size in pixels of the main window of the child process if the child creates the window using defaults. XY can be specified as either a list of two integers or as a X,Y string.
For further details, see the documentation of CreateProcess in the Windows SDK documentation.

end_process PID ?options?
Terminates the process with id PID. This function will first try to gracefully end the process by sending all its toplevel windows a WM_CLOSE command. If the process does not have any toplevels or if it does not end by this means and the -force option is specified, it is forcibly terminated.

The function returns 1 if the process ended and 0 otherwise. Note that if -wait has not been specified, or is too short, the function may return a value of 0 in the case where the process is in the process of terminating but has not fully exited by the time the command returns.

The following options may be specified with this command:

-force | If this option is specified, the process will be forcibly terminated if it does not terminate in response to WM_CLOSE messages.
-wait MS | Normally, the function will return without actually waiting for the process to end. If this option is specified, the function returns after waiting for MS milliseconds for the process to end.
-exitcode EXITCODE | Specifies the exit code that should be returned by the terminating process. This is 1 by default. Depending on the application being terminated, this may not be the actual exit code returned on application exit. Caller should not rely on this.
Example: Gracefully exit all programs with a given name or path

Example: Forcibly kill all programs with a given name or path

free_library HMODULE
Frees a loaded module. HMODULE must be a handle previously returned through load_library.
get_current_process_id
Returns the PID of the current process.
get_current_thread_id
Returns the TID of the current thread.
get_device_drivers ?options?
This command returns information about the device drivers loaded in the system. The returned information is in the form of a list of sublist with each sublist corresponding to a loaded driver. Each sublist is a flat list of "option value" pairs. The following options may be specified:

-all | Returns all device driver attributes below.
-base | Returns the base address in memory where the driver is loaded
-path | Returns the path to the file from which the driver was loaded. In some cases, this may not contain a fully qualified path.
-name | Returns the name of the driver - generally the file name portion of the file from which the driver was loaded.

get_priority_class PID
Returns the scheduling priority class of the process with id PID.
get_process_commandline PID
Returns the command line with which the process with id PID was invoked. The following options may be specified with the command.

-noaccess DEFAULTVALUE If a process exists but cannot be accessed to retrieve the name, the command normally returns the string "(unknown)". This option may be used to specify a different string to be returned in such cases.

get_process_exit_code HPROCESS
Returns the exit code for a process. HPROCESS is a handle to the process of interest. If the process is still running, a null string is returned.
get_process_handle PID ACCESSRIGHTS ?INHERITMODE?
Returns a handle to the process with id PID. ACCESSRIGHTS specifies the desired access rights and may be specified as a list of integer access rights flags or symbols as described in Access Rights. If INHERITMODE is non-0, the returned handle can be inherited by child processes. If it is 0 (default), the handle cannot be inherited by child processes.
get_process_ids ?options?
This command returns a list of the process ids. If no options are specified, the list includes all processes on the system. The following options may be specified to return a subset of these:

-glob | This option modifies the meaning of the -path and -name options. Normally, the match is done using case-insensitive, exact comparison. If -glob is specified, the PROCESSNAME and EXECUTABLEPATH are matched using glob-style pattern matching as in Tcl's string match command.
-name PROCESSNAME | If this option is specified, the returned list only includes those processes whose name matches PROCESSNAME. Generally the name is the same as the filename portion of the executable file path. If this information is not available for a process, it is not included in the returned list. This option cannot be used with the -path option.
-path EXECUTABLEPATH | If this option is specified, the returned list only includes those processes created from the executable file matching EXECUTABLEPATH. If this information is not available for a process, it is not included in the returned list. This option cannot be used with the -name option.
-logonsession LUID | If this option is specified, the returned list only includes those processes running inside the logon session identified by the specified LUID.
-user ACCOUNT | If this option is specified, the returned list only includes those processes running under the specified account. ACCOUNT may be either a user name or its SID.
Example: Minimize all windows for an application

Example: Exit all programs with a given name or path

get_process_info PID ?options?
Returns various pieces of information related to the process whose id is PID. The information returned depends on the options specified and is in the form of a flat list of the form "option1 value1 ...". The values returned may be scalars (e.g. -name) or rate based measured over an interval (e.g. -processorutilization). The option -interval may be used to indicate the interval over which the rate based fields are measured. One of more of the following options may be specified with the command:

-all | Returns all values except those for unsupported options.
-basepriority | Returns the base priority of the process.
-commandline | Returns the command line with which the process was invoked.
-createtime | Returns the time the process was created as the number of 100ns units since Jan 1, 1601. This can be converted to a date and time string by passing it to large_system_time_to_secs and formatting the result using clock format.
-elapsedtime | Returns the total time (seconds) that the process has been running.
-groups | Returns the list of groups that the process belongs to.
-handlecount | Returns the number of handles that the process currently has open.
-handles | Returns the list of open handles in the process as a list of lists. Each sublist contains three elements - the handle value, the type of the handle, and name of the corresponding resource. This an unsupported option that uses undocumented Windows functions and should not be used for production systems.
-interval INTERVAL | Specifies the number of milliseconds over which rate based fields are to be measured. The command will not return until this time has elapsed. By default this is 100ms. If none of the fields requested is a rate based field, this option is ignored and the command returns immediately.
-iodatabytesrate | Returns the rate at which the process is reading and writing bytes.
-iodataopsrate | Returns the rate at which the process is issuing I/O operation.
-iootherbytes | Returns number of non-data bytes the process has read or written through I/O operations.
-iootherbytesrate | Returns the rate at which the process is reading and writing non-data bytes (such as control bytes).
-iootherops | Returns number of non-data I/O operations the process has executed.
-iootheropsrate | Returns the rate at which the process is issuing non-data I/O operations.
-ioreadbytes | Returns number of data bytes the process has read through I/O operations.
-ioreadbytesrate | Returns the rate at which the process is reading bytes through I/O operations.
-ioreadops | Returns number of data read I/O operations the process has executed.
-ioreadopsrate | Returns the rate at which the process is issuing read I/O operations.
-iowritebytes | Returns number of data bytes the process has written through I/O operations.
-iowritebytesrate | Returns the rate at which the process is writing bytes through I/O operations. All types of I/O operations are including in this rate.
-iowriteops | Returns number of data write I/O operations the process has executed.
-iowriteopsrate | Returns the rate at which the process is issuing write I/O operations.
-logonsession | Returns the LUID of the logon session for the process.
-name | Returns the name of the process. This is identical to the value returned by the get_process_name function.
-noaccess DEFAULTVALUE | If a process exists but cannot be accessed to retrieve the name, the command normally returns the string "(unknown)". This option may be used to specify a different string to be returned in such cases.
-noexist DEFAULTVALUE | If a process does not exist, the command returns the string "(no such process)". This option may be used to specify a different string to be returned for non-existent processes.
-pagefaultrate | Returns the rate at which the process is generating page faults.
-pagefilebytes | Returns total number of bytes in use for this process in all the system paging files.
-pagefilebytespeak | Returns the maximum number of bytes that have been used for this process in the system paging file since the process started.
-parent | Returns id of the process that invoked this process. For the system and system idle processes, an empty string is returned since they have no parent process.
-path | Returns the path to the executable file from which this process was invoked. This value is the same as that returned by the get_process_path command.
-pid | Returns the process id of this process (which should be identical to that passed in as the PID argument.
-poolnonpagedbytes | Returns the number of bytes of nonpaged pool memory in use for the process.
-poolpagedbytes | Returns the number of bytes of paged pool memory in use for the process.
-primarygroup | Returns the primary group that the process belongs to.
-priorityclass | Returns the priority class of the process.
-privatebytes | Returns the number of bytes allocated for this process' private use.
-privilegedtime | The amount of privileged context CPU time used by the process in 100ns units.
-privilegedutilization | Returns the percentage of elapsed time that this process has spent executing in privileged mode.
-privileges | Returns the list of enabled and disabled process privileges in the same format as get_token_privileges.
-processorutilization | Returns the percentage of CPU time that this process has used.
-threadcount | Returns the total number of threads in the process.
-tids | Returns a list of ids of the threads in the process.
-toplevels | Returns a list of the window handles of all toplevel windows owned by the process.
-tssession | Returns the terminal server session id of the process.
-user | Returns the user account under which the process is running.
-usertime | The amount of user context CPU time used by the process in 100ns units.
-userutilization | Returns the percentage of elapsed time that this process has spent executing in user mode.
-virtualbytes | Returns the current size of the process' virtual address space.
-virtualbytespeak | Returns the maximum amount of virtual address space that the process has used in the course of its execution.
-workingset | Returns the number of bytes currently in the process' working set.
-workingsetpeak | Returns the maximum number of bytes in the process' working set since it began execution.
Note that all the information is not retrieved in a single snapshot so there may be discrepancies between various values. For example, the number of thread ids returned via -tids may not match the thread count returned via -threadcount.

The get_process_info command is intended for one-time retrieval of information and is too inefficient for usage in an application like performance monitoring. Direct access to the performance data should be used in those cases.

get_process_modules PID ?options?
This command returns information about the modules loaded in the process with id PID. If no options are specified, the command returns a list of handles to the modules.

If any options are specified, the returned information is in the form of a list of sublists each of which corresponds to a loaded module. The sublist for each module is in the form "option VALUE". The following options may be specified:

-all | Returns the data for all options described below.
-handle | Includes the handle to the module in the returned data for each module.
-path | Includes the full path from which the module was loaded.
-name | Includes the name of the module - generally the file name portion of the path.
-imagedata | Includes the base address in memory where the module is loaded, the size of the module in memory and the address of the entry point to the module as a sublist for each module.
Example: Show the DLL's loaded in a process

get_process_name PID
Returns the name of the process with id PID. This is generally the file name component of the full path of the executable file from which the process was loaded. The following options may be specified to with the command:

-noexist DEFAULTVALUE | If a process does not exist, the command returns the string "(no such process)". This option may be used to specify a different string to be returned for non-existent processes.
-noaccess DEFAULTVALUE | If a process exists but cannot be accessed to retrieve the name, the command normally returns the string "(unknown)". This option may be used to specify a different string to be returned in such cases.
Example: Show the user account for each process

get_process_parent PID
Returns the PID of the process from whom the process with id PID inherited handles and environment. The following options may be specified to with the command:

-noexist DEFAULTVALUE | If a process does not exist, the command returns the string "(no such process)". This option may be used to specify a different string to be returned for non-existent processes.
-noaccess DEFAULTVALUE | If a process exists but cannot be accessed to retrieve the parent, the command normally returns the string "(unknown)". This option may be used to specify a different string to be returned in such cases.

get_process_path PID
Returns the full path of the executable file from which the process with id PID was loaded. The following options may be specified to with the command:

-noexist DEFAULTVALUE | If a process does not exist, the command returns the string (no such process). This option may be used to specify a different string to be returned for non-existent processes.
-noaccess DEFAULTVALUE | If a process exists but cannot be accessed to retrieve the path information, the command normally returns the string (unknown). This option may be used to specify a different string to be returned in such cases.

get_process_thread_ids PID
Returns a list of ids of all threads in the process whose id is PID.
get_thread_handle TID ACCESSMODE ?INHERITMODE?
Returns a handle to the thread with id TID. ACCESSMODE specifies the desired access rights and may be specified as a list of integer access rights flags or symbols. Refer to the documentation of TWAPI Security module for more details. If INHERITMODE is non-0, the returned handle can be inherited by child processes. If it is 0 (default), the handle cannot be inherited by child processes.
get_thread_info TID ?options?
Returns various pieces of information related to the thread whose id is TID. The information returned depends on the options specified and is in the form of a flat list of the form "option1 value1 ...". The values returned may be scalars (e.g. -name) or rate based measured over an interval (e.g. -processorutilization). The option -interval may be used to indicate the interval over which the rate based fields are measured. One of more of the following options may be specified with the command:

-all | Returns all values.
-basepriority | Returns the base priority of the thread.
-contextswitches | Returns the number of context switches done by the thread.
-contextswitchrate | Returns the rate of context switches for the thread.
-createtime | Returns the time the thread was created as the number of 100ns units since Jan 1, 1601. This can be converted to a date and time string by passing it to large_system_time_to_secs and formatting the result using clock format.
-elapsedtime | Returns the total time (seconds) that the thread has been running.
-groups | Returns the list of groups that the thread belongs to.
-interval INTERVAL | Specifies the number of milliseconds over which rate based fields are to be measured. The command will not return until this time has elapsed. By default this is 100ms. If none of the fields requested is a rate based field, this option is ignored and the command returns immediately.
-noaccess DEFAULTVALUE | If a thread but cannot be accessed, the command normally returns the string "(unknown)". This option may be used to specify a different string to be returned in such cases.
-noexist DEFAULTVALUE | If a thread does not exist, the command returns the string "(no such thread)". This option may be used to specify a different string to be returned for non-existent threads.
-pid | Returns the id of the process the thread belongs to.
-primarygroup | Returns the primary group that the thread belongs to.
-priority | Returns the current priority of the thread.
-privilegedtime | The amount of privileged context CPU time used by the thread in 100ns units.
-privilegedutilization | Returns the percentage of elapsed time that this process has spent executing in privileged mode.
-privileges | Returns the list of the current thread privileges.
-processorutilization | Returns the percentage of CPU time that this process has used.
-relativepriority | Returns the priority level of the thread relative to the priority class of the containing process.
-startaddress | Returns the address at which the thread began execution.
-state | Returns the current state of the thread.
-tid | Returns the thread id of this process (which should be identical to that passed in as the TID argument.
-user | Returns the user account under which the thread is running.
-usertime | The amount of user context CPU time used by the thread in 100ns units.
-userutilization | Returns the percentage of elapsed time that this process has spent executing in user mode.
-waitreason | Returns the reason a thread is in wait state. This is only valid when the state field is 5 indicating the thread is in a wait state.
Note that all the information is not retrieved in a single snapshot so there may be discrepancies between various values.

Like the get_process_info command, get_thread_info is intended for one-time retrieval of information and is too inefficient for usage in an application like performance monitoring. Direct access to the performance data should be used in those cases.

get_thread_relative_priority TID
Returns the scheduling priority value of the thread with id TID. This is an integer value relative to the process' priority class as described in the Windows SDK.
get_thread_parent_process_id TID
Returns the id of the parent process of the thread with id TID.
is_idle_pid PID
Returns true if the passed PID is that of the system idle process.
is_system_pid PID
Returns true if the passed PID is that of the system process.
load_library FILEPATH ?options?
Loads a DLL and returns a handle to it. This handle may be passed to other commands, such as format_message that expect a module handle as a parameter. The handle must later be released by calling free_library. The following options may be specified:

-dontresolverefs | Normally, if the module being loaded is a DLL, the system will load any other modules referenced by it and also call its DllMain function to initialize it. If this option is specified, neither of these actions will be done.
-datafile | If specified, the module is loaded as a data file as opposed to an executable module. This is useful when the file is being loaded only to extract resources or messages.
-alteredpath | Uses an alternative search strategy to find modules referenced by this module. See the Windows SDK for more details.

See LoadLibraryEx in the Windows SDK for more details regarding this command.

process_exists PID ?options?
This command returns 1 if a process with id PID exists and 0 otherwise. The following options may be specified to further restrict the match:

-path EXECUTABLEPATH | If this option is specified, the matched process must have been created from the executable file matching EXECUTABLEPATH. This option cannot be used with the -name option.
-name PROCESSNAME | If this option is specified, the matched process must have a name that matches PROCESSNAME. Generally the name is the same as the filename portion of the executable file path. This option cannot be used with the -path option.
-glob | This option modifies the meaning of the -path and -name options. Normally, the match is done using case-insensitive, exact comparison. If -glob is specified, the PROCESSNAME and EXECUTABLEPATH are matched using glob-style pattern matching.

process_waiting_for_input PID ?-wait MILLISECONDS?
Returns 1 if the specified process is idle, waiting for input, and 0 otherwise. The main use of this command is to detect when a process (for example, a child process that has just been created) has finished initialization. Note that a console process will always return 1.

The command normally returns right away. Specifying the -wait option causes the command to wait until either MILLISECONDS have passed or the process is idle before returning. Specifying a value of -1 will cause the command to wait without timing out.
resume_thread TID
The command checks the suspend count (see suspend_thread) of the specified thread. If it is 0, the thread is not suspended and the command has no effect. Otherwise, the suspend count is decremented. If the value is now 0, the thread resumes execution. The command returns thread's previous suspend count - a value of 0 meaning the thread was not suspended, 1 meaning the suspending thread is not resumed, and other values signifying that the thread is still suspended.
set_priority_class PID PRIORITYCLASS
Sets the scheduling priority class of the process with id PID to PRIORITYCLASS. PRIORITYCLASS is an integer value identifying a priority class as described in the Windows SDK.
set_thread_relative_priority TID PRIORITY
Sets the scheduling priority value of the thread with id TID to PRIORITY. PRIORITY is an integer value relative to the process' priority class as described in the Windows SDK.
suspend_thread TID
Suspends execution of the thread with id TID. The system keeps track of a suspend count for each thread. This is incremented every time a call is made to suspend the thread, and decremented every time a call is made to resume it. The command returns thread's previous suspend count.

COPYRIGHT

Copyright © 2003-2009 Ashok P. Nadkarni


Handles - Operating system handles

Handles

Commands for managing operating system handles

SYNOPSIS

package require twapi

close_handles ?HANDLELIST HANDLELIST?
create_file PATH ?options?
duplicate_handle HANDLE ?options?
get_tcl_channel_handle CHANNEL DIRECTION

DESCRIPTION

This module provides commands that deal with operating system handles.

Overview

Several Win32 and TWAPI commands return operating system handles to various types of resources. The following commands allow manipulation and retrieval of information regarding handles.

The command create_file returns a handle to a file or device.

The operating system associated with a Tcl channel can be retrieved using the get_tcl_channel_handle command.

The command duplicate_handle can be used to duplicate a handle, for example to pass down to a child process with different access rights.

The command close_handle closes a operating system handle and frees resources associated with it.

Commands

close_handles ?HANDLELIST HANDLELIST?
This command concatenates its arguments and treats the result as a list of operating system handles. It closes each handle in this list. In case of errors, closing any handles, it continues to try and close the remaining handles before generating an exception.
create_file PATH ?options?
This is a thin wrapper around the Win32 CreateFile function that returns a handle to a file or device. The wrapper primarily provides mnemonics and defaults for the CreateFile parameters. PATH specifies the file or device path. Additional options and default values are shown below.

-access ACCESSRIGHTS | Specifies the desired access rights and may be specified as a list of integer access rights flags or symbols as described in Access Rights. Defaults to generic_read.
-createdisposition DISPOSITION | DISPOSITION must be one of create_always, create_new, open_always, open_existing or truncate_existing. Refer to the Windows SDK for the meaning. Defaults to open_always.
-flags FLAGS | An integer bit mask corresponding to the dwFlagsAndAttributes parameter to CreateFile function. See the Windows SDK for detail. Defaults to 0.
-inherit BOOL | If true, the returned handle is inheritable by child processes. Defaults to false.
-secd SECURITY_DESCRIPTOR | Specifies a security descriptor to be attached to the file or device if it has to be created. Defaults to a null security descriptor which results in the process' default security descriptor being applied.
-share | Specifies the sharing mode of the object. This is list containing zero or more of the constants read, write and delete that control what kind of shared access should be allowed while the file or device is open. Defaults to {read write delete}.
-templatefile | A handle to a template file with the GENERIC_READ access right from which file attributes and extended attributes are to be copied for the file that is being created. Defaults to NULL.
Refer to the Windows SDK for additional details.

duplicate_handle HANDLE ?options?
Duplicates an operating system handle. HANDLE may be either in the form returned by commands such as get_tcl_channel_handle or get_process_handle or may be an actual address (integer) literal corresponding to the handle. The following options specify the context of the handle and control attributes of the duplicated handle:

-access ACCESSRIGHTS | Specifies the access rights desired for the new handle. If unspecified, the new handle is created with the same access rights as the original one. ACCESSRIGHTS is a list of symbolic constants and bit masks as specified in Access Rights.
-closesource | If specified, HANDLE is closed after it is duplicated.
-inherit | If specified, the new handle marked as inheritable. By default, the duplicated handle cannot be inherited by child processes.
-sourcepid SOURCEPID | Specifies the PID of the process in whose context HANDLE is a valid handle. Defaults to the current process.
-targetpid TARGETPID | Specifies the PID of the process in whose context the new handle is to be created. Specifying this also impacts the format of the returned handle value.
If option -targetpid is not specified, the command returns the duplicated handle in symbolic form that can be passed to functions such as close_handle. If -targetpid is specified, the command returns the literal value of the handle. This is true even if the target PID is that of the current process.

get_tcl_channel_handle CHANNEL DIRECTION
Returns the operating system handle corresponding to a Tcl channel identifier (for example, returned by the Tcl open command). If DIRECTION is write, the write-side handle is returned, otherwise the read-side handle is returned. (For many channel types, the two are identical.)

COPYRIGHT

Copyright © 2004-2009 Ashok P. Nadkarni


Services - Windows services configuration

Services

Commands for configuring and monitoring Windows services

SYNOPSIS

package require twapi

continue_service INTERNAL_SERVICE_NAME ?options?
create_service INTERNAL_SERVICE_NAME COMMAND ?options?
delete_service INTERNAL_SERVICE_NAME ?options?
get_dependent_service_status INTERNAL_SERVICE_NAME ?options?
get_multiple_service_status ?options?
get_service_configuration INTERNAL_SERVICE_NAME ?options?
get_service_display_name SERVICE_NAME ?options?
get_service_internal_name SERVICE_NAME ?options?
get_service_state INTERNAL_SERVICE_NAME
get_service_status INTERNAL_SERVICE_NAME ?options?
interrogate_service INTERNAL_SERVICE_NAME ?options?
lock_scm_db ?options?
pause_service INTERNAL_SERVICE_NAME ?options?
query_scm_db_lock_status v_lockinfo ?options?
run_as_service SERVICES ?-interactive BOOLEAN? ?-controls CONTROLLIST?
service_exists SERVICE_NAME ?options?
set_service_configuration INTERNAL_SERVICE_NAME ?options?
start_service INTERNAL_SERVICE_NAME ?options?
stop_service INTERNAL_SERVICE_NAME ?options?
unlock_scm_db SCM_LOCK_HANDLE
update_service_status SERVICENAME SEQNO STATE ?options?

DESCRIPTION

This module provides procedures for managing and controlling Windows services and also allows for writing Windows services in Tcl.

Service Configuration and Monitoring

The commands lock_scm_db, unlock_scm_db and query_scm_db_lock_status allow manipulation of the Service Control Manager (SCM) database lock during configuration changes.

The commands get_service_internal_name and get_service_display_name map back and forth between the internal name and display name of a service.

The command service_exists checks for the existence of a service while get_service_state returns its state. The commands get_service_status, get_multiple_service_status and get_dependent_service_status retrieve status information for one or more services. interrogate_service can be used to request a service to update its status with the service control manager (SCM).

Service configuration changes, including creation of new services and deletion of existing ones, can be done through the commands create_service, delete_service and set_service_configuration.

The commands start_service, stop_service, pause_service and continue_service control the run state of a service.

Writing services in Tcl

The command run_as_service allows an application to run as a Windows service. Services are implemented as callback handlers that are invoked in response to control signals received from the system. These signals include controls to stop the service, to pause and continue, or may be notifications of events such as session changes. The list of such signals and their handling is detailed in run_as_service.

While running as a service, applications need can update their status with the SCM, either asynchronously or in response to control signals. This can be done through update_service_status.

Standard Options

Most commands allow the following options to be specified:

-system SYSTEMNAME | Specifies the name of the system on which the command should be invoked. By default, this is the local system.
-database DATABASE | Specifies the service control database to be operated on. By default, this is the active service control database on the target system.

Commands

continue_service INTERNAL_SERVICE_NAME ?options?
This command resumes the specified service which must be in a paused state. INTERNAL_SERVICE_NAME must be the internal name of the service, not the display name. The command returns 1 if the service has resumed to a running state when the command completes and 0 otherwise. Note that a return value of 0 does not imply an error, just that the service had not completely resumed by the time the command returned.

The standard options described in Standard Options may be specified with this command. In addition, if the option "-wait MILLISECONDS" is specified the command will wait until the service is running or until MILLISECONDS milliseconds have expired.
create_service INTERNAL_SERVICE_NAME COMMAND ?options?
This command creates a new Windows service in the service control manager database.

INTERNAL_SERVICE_NAME is the internal name by which the service is identified by the service control manager.

COMMAND contains the system command to be executed to start the service. This includes the path to the executable as well as arguments to be passed to it. If the path contains spaces, it must be specifically quoted else the operating system will interpret all characters after the first space as arguments to be passed to the service. For example,

"\"C:\\Program Files\\MyService\\service.exe\" arg1 arg2"

In addition to the Standard Options, the following additional options may be specified which control various aspects of the service:

-displayname DISPLAYNAME | Specifies the user visible name for the service. This is the name that is shown in the net start command and the SCM control panel applet.
-servicetype SERVICETYPE Specifies the service type and may have one of the following values:

win32_own_process | Service that runs in its own process. This corresponds to the SERVICE_WIN32_OWN_PROCESS in the Windows SDK documentation. This is the default if the option is not specified.
win32_shared_process | Service that runs inside a process shared with other services. This corresponds to the SERVICE_WIN32_SHARED_PROCESS in the Windows SDK documentation.
file_system_driver | File system driver. This corresponds to the SERVICE_FILE_SYSTEM_DRIVER in the Windows SDK documentation.
kernel_driver | Kernel driver. This corresponds to the SERVICE_KERNEL_DRIVER in the Windows SDK documentation.

-interactive BOOLEAN | This option specifies whether the service should be allowed to interact with the desktop. This is only valid when -servicetype is specified to be win32_own_process or win32_shared_process. The -account option must not be used with this option since interactive services must run under the LocalSystem account.
-starttype STARTTYPE Specifies how the service is to be started. STARTTYPE should have one of the following values:

auto_start | The service should be automatically started by the service control manager during system startup. This is the default if the option is not specified.
boot_start | The service should be automatically started by the system loader during system boot. This is only valid when -servicetype is specified to be kernel_driver or file_system_driver.
demand_start | The service should be started by the system upon receiving an explicit program request.
disabled | The service is disabled and cannot be started even on program request.
system_start | The service is a driver that is started by the operating system IoInitSystem function during system initialization. This is only valid when -servicetype is specified to be kernel_driver or file_system_driver.

-errorcontrol ERRORCONTROLMODE This option specifies how errors during service start are to be handled. ERRORCONTROLMODE may have one of the following values:

ignore | An error message will be logged to the Windows event log. The system startup will continue.
normal | An error message will be logged to the Windows event log and a popup displayed to the user. The system startup will continue. This is the default.
severe | An error message will be logged to the Windows event log. The system startup will continue only if the last known good configuration is active. Otherwise, the system is restarted with the last known good configuration.
critical | An error message will be logged to the Windows event log if possible. If the last known good configuration is active, the system startup is aborted. Otherwise, the system is restarted with the last known good configuration.

-loadordergroup GROUPNAME | Specifies GROUPNAME to be the service load order group to which the service belongs. If the option is not specified, the service is assumed to not belong to any load order group.
-dependencies DEPENDENCYLIST | Specifies the services and service load order groups that are required by this service and that must start before this service. DEPENDENCYLIST is a list of service names and load order groups. A load order group name must be prefixed with a + character to indicate that it is a group name and not a service.
-account ACCOUNTNAME | Specifies ACCOUNTNAME to be the user account under which the service should run. ACCOUNTNAME takes the form domain\username. If the account is a local account, ACCOUNTNAME may be specified as .\username or username. If this option is not specified, the service will run under the LocalSystem account. When -servicetype is kernel or filesystem, ACCOUNTNAME should be the name of the driver object that the system uses to load the driver.
-password PASSWORD | Specifies the password corresponding to the user account specified in the -account option. This option is ignored if the -account option is not specified.
Example: Install a service

delete_service INTERNAL_SERVICE_NAME ?options?
This command deletes the specified service from the service control manager database. INTERNAL_SERVICE_NAME must be the internal name of the service, not the display name. The standard options described in Standard Options may be specified with this command.

Example: Uninstall a service
get_dependent_service_status INTERNAL_SERVICE_NAME ?options?
Retrieves the status of services that are dependent on INTERNAL_SERVICE_NAME and that match a specified service state. The standard options described in Standard Options may be specified with this command. In addition, the following options may be specified to only include services in a given state. If neither of these is specified, services in all states are included in the returned list.

-inactive | Specifying this option will result in inclusion of services that are in the stopped state.
-active | Specifying this option will result in inclusion of services that are not in the stopped state.
The command returns a list each element of which describes the status of a single service. The format of the sublist elements is identical to that returned by the get_multiple_service_status.

Example: Stop and restart a service

Example: Show the dependents of a service

get_multiple_service_status ?options?
Retrieves the status of multiple services matching the specified service type and/or state. The standard options described in Standard Options may be specified with this command. In addition, the options may be specified to only include services of a given type and in a given state.

One or more from the following service type options may be specified to limit the types of services that are included in the returned list: -kernel_driver, -file_system_driver, -win32_own_process, -win32_share_process, -adapter or -recognizer_driver. See the description of the -servicetype option in the create_service command for the semantics of these values. If no service type options are specified, all types of services are included in the returned list.

One of the following options may be specified to limit the returned services to those in a specific state. If neither of these is specified, services in all states are included in the returned list.

-inactive | Specifying this option will result in inclusion of services that are in the stopped state.
-active | Specifying this option will result in inclusion of services that are not in the stopped state.
The command returns a list each element of which describes the status of a single service. The format of the sublist is a list of the form field1 value1 ... with the following fields:

attrs | Contains a list of attributes. Currently, the only attribute that may appear in this list is systemprocess which indicates that the service runs in a system process that must alway be running.
checkpoint | Contains the last checkpoint value reported by the service during a lengthy operation.
controls_accepted | Contains a bitmask indicating the control commands accepted by the service. Refer to the Windows SDK documentation for ControlService for details.
displayname | Indicates the user visible name of the service
exitcode | The last exit code of the service. If this value is 1066, a service specific error code is returned in the service_code field.
interactive | Indicates whether the service is allowed to interact with the desktop (1) or not (0).
name | Indicates the internal name of the service
pid | The PID of the process in which the service is running. If the service is currently stopped, this will be 0. A value of -1 indicates that the process id of the service cannot be determined (NT 4.0).
service_code | In case the exitcode field contains 1066, this field contains a service specific code stored by the service.
servicetype | Indicates the type of the service, and is one of win32_own_process, win32_share_process, kernel_driver, file_system_driver, adapter, recognizer_driver or an integer denoting the type if not one of the above.
state | Contains the latest reported status of the service and may have one of the values stopped, start_pending, stop_pending, running, continue_pending, pause_pending, paused or an integer value indicating the status of the service if not one of the above.
wait_hint | Estimated time required to complete an start, stop, pause or continue operation as last reported by the service.
Example: Show currently running Windows services

Example: Show Windows services that start automatically

get_service_configuration INTERNAL_SERVICE_NAME ?options?
This command returns the current configuration data for the specified service. INTERNAL_SERVICE_NAME is the internal name by which the service is identified by the service control manager. The standard options described in Standard Options may be specified with this command.

The return value is a flat list of the form option1 value1 ... that can be directly passed to the set_service_configuration command. The returned values depend on which of the following options are specified:

-all | Returns all option values
-description | Returns description of the service if available, otherwise the empty string.
-displayname | Returns the user visible name of the service.
-errorcontrol | Returns an indication of how errors during service startup will be handled. See description of create_service for details.
-servicetype | Returns the service type. See description of create_service for details.
-interactive | Returns 1 if the service is allowed to interact with the desktop and 0 otherwise.
-loadordergroup | Returns the name of the service load order group to which the service belongs.
-dependencies | Returns a list of names of services and service load order groups that are required by this service and that must start before this service.
-account | Returns the user account under which the service runs.
-starttype | See description of create_service for details.
-command | Returns the command, including the executable name and parameters, that is invoked to run the Windows service.
Example: Show Windows services that start automatically

Example: Show the services that a specified service depends on

get_service_display_name SERVICE_NAME ?options?
This command returns the display name of the specified service. If SERVICE_NAME is the display name of a service, it is returned. If it is the internal name of a service, the corresponding display name is returned. Otherwise, an error is raised. The standard options described in Standard Options may be specified with this command.
get_service_internal_name SERVICE_NAME ?options?
This command returns the internal name of the specified service. If SERVICE_NAME is the internal name of a service, it is returned. If it is the display name of a service, the corresponding internal name is returned. Otherwise, an error is raised. The standard options described in Standard Options may be specified with this command.
get_service_state INTERNAL_SERVICE_NAME
Returns the last reported state of the service. See the description of the state field for the command get_service_status for possible values.
get_service_status INTERNAL_SERVICE_NAME ?options?
This command returns the latest status information sent by the given service to the service control manager. The standard options described in Standard Options may be specified with this command. The return value is a flat list of the form field1 value1 .... The following fields are returned:

attrs | Contains a list of attributes. Currently, the only attribute that may appear in this list is systemprocess which indicates that the service runs in a system process that must alway be running.
controls_accepted | Contains a bitmask indicating the control commands accepted by the service. Refer to the Windows SDK documentation for ControlService for details.
exitcode | The last exit code of the service. If this value is 1066, a service specific error code is returned in the service_code field.
interactive | Indicates whether the service is allowed to interact with the desktop (1) or not (0).
servicetype | Indicates the type of the service, and is one of win32_own_process, win32_share_process, kernel_driver, file_system_driver, adapter, recognizer_driver or an integer denoting the type if not one of the above.
state | Contains the latest reported status of the service and may have one of the values stopped, start_pending, stop_pending, running, continue_pending, pause_pending, paused or an integer value indicating the status of the service if not one of the above.
service_code | In case the exitcode field contains 1066, this field contains a service specific code stored by the service.
checkpoint | Contains the last checkpoint value reported by the service during a lengthy operation.
wait_hint | Estimated time required to complete an start, stop, pause or continue operation as last reported by the service.
pid | The PID of the process in which the service is running. If the service is currently stopped, this will be 0. A value of -1 indicates that the process id of the service cannot be determined (NT 4.0).

interrogate_service INTERNAL_SERVICE_NAME ?options?
This command asks the specified service to update the service control manager with its current status. INTERNAL_SERVICE_NAME must be the internal name of the service, not the display name. The standard options described in Standard Options may be specified with this command.
lock_scm_db ?options?
This command locks the service control manager database and returns a handle to the lock. The handle must later be released by passing it to unlock_scm_db. The standard options described in Standard Options may be specified with this command.
pause_service INTERNAL_SERVICE_NAME ?options?
This command pauses the specified service. INTERNAL_SERVICE_NAME is the internal name of the service, not the display name. The command returns 1 if the service is paused when the command completes and 0 otherwise. Note that a return value of 0 does not imply an error, just that the service had not completely changed to a paused state by the time the command returned. A Tcl error is generated if the service was not running.

The options described in Standard Options may be specified with this command. In addition, if the option "-wait MILLISECONDS" is specified the command will wait until the service is paused or until MILLISECONDS milliseconds have expired.
query_scm_db_lock_status v_lockinfo ?options?
This command returns the state of a service control manager database lock. It returns 1 if the database is locked and 0 otherwise. The user name of the lock holder and the number of seconds that the lock has been held is returned as a list in the variable referenced by v_lockinfo. The options described in Standard Options may be specified with this command.
run_as_service SERVICES ?-interactive BOOLEAN? ?-controls CONTROLLIST?
This command sets up the mechanisms that allow a Tcl application to act as a Windows service. It must be only called when the application is started by the Windows SCM as a Windows service, else it will fail silently. The command does not return until the service is ready to exit. Rather, it invokes the service handlers that implement each service in response to notifications received from the system as described below.

SERVICES is a list of SERVICENAME HANDLER pairs that describe the services that will run in the process. Note a single process may host multiple services. SERVICENAME is the internal name of a service. HANDLER is a script that will be invoked for that service in response to various system notifications as described below.

The option -interactive indicates whether the services running in the application will require interaction with the desktop.

The option -controls configures what controls messages from the system, signals and notifications, are understood by the services. The SCM will restrict itself to sending only these although for robustness it is recommended that all services gracefully handle all signals as described below. Note that it is not possible to specify different values for this on a per-service basis. By default, CONTROLLIST includes control signals stop and shutdown. Note the notification start is implicit and must be handled by every service.

When the application is started by the SCM, it should perform its basic application-wide initialization and then call run_as_service. The command will then set up the communication mechanisms with the SCM and register the specified services. The control signals sent by the SCM to the service are passed on to the HANDLER script registered for the service by the application.

The messages sent to a service fall into two categories - control signals and notifications. Control signals generally require the service to take some action, often a state change such as stopping or pausing the service. Notifications are generally of an informational nature to apprise the service of some system event such as session changes or power events.

There are five controls signals sent by the SCM to control the state of a service. These correspond to the tokens start, stop, shutdown, pause and continue. For each of these, HANDLER is invoked with four additional arguments. The first is control signal token itself. The second is the name of the service for which the control was sent and should match (ignoring case) the corresponding the SERVICENAME values passed to run_as_service. The third argument is a sequence number (more on this later). The fourth argument is a numeric value that is the actual value of the control signal sent by the SCM.

start | Sent to start the service.
stop | Sent to stop the service.
pause | Sent to pause the service without terminating it. This is only received if pause_continue has been specified as an element in the -controls option.
continue | Sent to contiue a service that was previously paused. This is only received if pause_continue has been specified as an element in the -controls option.
shutdown | Sent to indicate the system is shutting down. Should be treated similar to stop.
interrogate | Sent to enquire about the service status. TWAPI handles this internally and never actually sends this to the application.

In response to a control signal, the handler must take whatever action necessary and then notify the SCM by calling update_service_status, passing it new the process state. For example, in response to a pause control, the application may take whatever actions required to temporarily pause the service operation and then respond by passing the paused state to update_service_status. Alternatively, if the service cannot be paused for whatever reason, it may respond by passing the state running. Refer to update_service_status for details on valid responses. It is very important to correctly notify the service control manager of the state change.

The application must respond to every control notification with a corresponding call to update_service_status. There is no hard time limit during which this call must be made but it is a good idea not to delay the response too long. update_service_status can be either invoked from the handler itself or scheduled at some later point after the necessary actions have been taken by the application. During this time, TWAPI may internally send responses to the SCM essentially asking it to keep waiting for an answer without timing out.

Because multiple controls may be received from the SCM before previous controls have been fully processed, and to allow for asynchronous responses from the application, a sequence number is passed as the third argument to the callback. When the application responds using update_service_status, this sequence number should be passed to the call. When responses are made out-of-order, those with older sequence numbers will be ignored.

In addition to the above control signals that may be sent by the SCM, it may also send notifications to the service to inform it of system events. These are passed on to the appropriate service callback handler in the same fashion as the control signals. Unlike for control signals, the application need not, and generally should not, respond with a call to update status.

In addition to the four arguments described for control signals, some notifications may have additional arguments. The various notifiations are shown in the able below.

all_stopped | The all_stopped notification is sent to the last running service in the application when all other services in the process have been stopped. The application should normally clean up and exit when this control is received. The remaining arguments passed to the handler are either empty strings or 0 and should not be used. This notification is internally generated by TWAPI and not sent by the system.
hardwareprofilechange | Notifies the application that the system hardware profile has changed. This is only received if paramchange has been specified as an element in the -controls option.
paramchange | Notifies the application that one of its configuration parameters has changed and it should re-read its service information from the Windows registry. This is only received if paramchange has been specified as an element in the -controls option to indicate to the service manager that the service can read and change its configuration while running.
netbindadd | Refer to the Windows SDK. This is only received if netbindchange has been specified as an element in the -controls option.
netbinddisable | Refer to the Windows SDK. This is only received if netbindchange has been specified as an element in the -controls option.
netbindenable | Refer to the Windows SDK. This is only received if netbindchange has been specified as an element in the -controls option.
netbindremove | Refer to the Windows SDK. This is only received if netbindchange has been specified as an element in the -controls option.
powerevent | This notifies the application of a change in the power status of the system. This is only received if powerevent has been specified as an element in the -controls option. In addition to the standard arguments, an additional argument is appended detailing the nature of the change. This may be one of apmsuspend, apmstandby, apmresumecritical, apmresumesuspend, apmresumestandby, apmbatterylow, apmpowerstatuschange, apmoemevent, or apmresumeautomatic.
sessionchange Notifies that a session change event has occurred. This is only received if sessionchange has been specified as an element in the -controls option. In addition to the standard arguments, two additional arguments are appended. The first of these indicates the nature of the session change and is one of console_connect, console_disconnect, remote_connect, remote_disconnect, session_login, session_logoff, session_lock, session_unlock or session_remote_control.

The second additional argument is the session identifier for which the event is being reported.
user_defined | The userdefined control is strictly application-dependent and not used by the SCM. User defined controls can be sent to a service using command line utilities such as the Windows sc program. The standard four arguments are passed on except that the fourth argument, the numeric value of the control, will vary within the range 128-255 and can be used by the application to distinguish between different signals.

service_exists SERVICE_NAME ?options?
This command returns 1 or 0 depending on whether a service with the specified name exists or not. SERVICE_NAME may be either the internal name of the service or the display name. The options described in Standard Options may be specified with this command.
set_service_configuration INTERNAL_SERVICE_NAME ?options?
This command allows modification of configuration data for the service specified by INTERNAL_SERVICE_NAME. In addition to the options described in Standard Options, the following options may be specified to set configuration data. The values for any unspecified options will remain unchanged.

-displayname DISPLAYNAME | Specifies the user visible name for the service. This is the name that is shown in the net start command and the SCM control panel applet.
-command COMMAND | COMMAND contains the system command to be executed to start the service. See description of create_service for details.
-servicetype SERVICETYPE | Specifies the service type. See description of create_service for details.
-interactive BOOLEAN | This option specifies whether the service should be allowed to interact with the desktop. See description of this option in command create_service for details.
-starttype STARTTYPE | Specifies how the service is to be started. See description of this option in command create_service for valid values for STARTTYPE.
-errorcontrol ERRORCONTROLMODE | This option specifies how errors during service start are to be handled. See description of this option in command create_service for valid values for ERRORCONTROL.
-loadordergroup GROUPNAME | Specifies GROUPNAME to be the service load order group to which the service belongs. If the option is not specified, the service is assumed to not belong to any load order group.
-dependencies DEPENDENCYLIST | Specifies the services and service load order groups that are required by this service and that must start before this service. See description of this option in command create_service for details.
-account ACCOUNTNAME | Specifies ACCOUNTNAME to be the user account under which the service should run. See description of this option in command create_service for details.
-password PASSWORD | Specifies the password corresponding to the user account specified in the -account option. This option is ignored if the -account option is not specified.

Example: Change a Windows service account

start_service INTERNAL_SERVICE_NAME ?options?
This command starts the specified service if it is not already running. INTERNAL_SERVICE_NAME must be the internal name of the service, not the display name. The command returns 1 if the service is up and running when the command completes and 0 otherwise. Note that a return value of 0 does not imply an error, just that the service had not completely started by the time the command returned.

The options described in Standard Options may be specified with this command. In addition, if the option "-wait MILLISECONDS" is specified the command will wait until the service is running or until MILLISECONDS milliseconds have expired.

Example: Stop and restart a service
stop_service INTERNAL_SERVICE_NAME ?options?
This command stops the specified service if it is currently running. INTERNAL_SERVICE_NAME must be the internal name of the service, not the display name. The command returns 1 if the service has stopped by the time the command completes and 0 otherwise. Note that a return value of 0 does not imply an error, just that the service had not completely stopped by the time the command returned.

The options described in Standard Options may be specified with this command. In addition, if the option "-wait MILLISECONDS" is specified the command will wait until the service is stopped or until MILLISECONDS milliseconds have expired.

Example: Stop and restart a service
unlock_scm_db SCM_LOCK_HANDLE
This command releases a lock previously obtained through lock_scm_db.
update_service_status SERVICENAME SEQNO STATE ?options?
This command should be called by applications, running as a Windows service, to update their status information with the Windows service control manager (SCM). The command may be called asynchronously at any time, but is most often called in response to a control notification from the SCM requesting a state change. See run_as_service for more detail.

SERVICENAME is the name of the service whose status is being updated.

SEQ is the sequence number of the control notification to which this is the response. See the discussion in the run_as_service documentation. If the call is not in response to a control notification, SEQ should be set to 0.

STATE is the of the application and should be one of the values stopped, running or paused. Note that an application can stop at any time, but should not generally change state to running or paused on its own without a control notification from the SCM. Doing so will in all likelihood confuse the SCM manager sufficiently to make the service unmanageable.

If the service state being specified is stopped, the application may also indicate a standard Windows exit code and a service-specific exit code by specifying their values through the options -exitcode and -servicecode respectively.

COPYRIGHT

Copyright © 2003-2008 Ashok P. Nadkarni


Network configuration - Network related commands

Network configuration

Commands related to network configuration

SYNOPSIS

package require twapi

address_to_hostname IPADDRESS ?-async SCRIPT? ?-flushcache?
flush_arp_table INTERFACEINDEX
get_arp_table ?options?
get_ip_addresses
get_netif_count
get_netif_indices
get_netif_info NETWORKINTERFACE ?options?
get_network_info ?options?
get_outgoing_interface DESTADDR
get_route ?options?
get_routing_table ?-sort?
get_tcp_connections ?options?
get_udp_connections ?options?
hostname_to_address HOSTNAME ?-async SCRIPT? ?-flushcache?
hwaddr_to_ipaddr HWADDR ?VARNAME?
ipaddr_to_hwaddr IPADDR ?VARNAME?
port_to_service PORTNUMBER
service_to_port SERVICENAME
terminate_tcp_connections ?options?

DESCRIPTION

This module provides procedures to retrieve network information

Overview

This module provides commands to retrieve various network-related data for the local system including DNS and DHCP information, type and configuration of network interfaces, traffic statistics and various other information. The module also provides some client side name resolution lookup functions including nonblocking name and address lookups. Many of these commands and some options are not available on all platforms as noted in each command description.

Commands

address_to_hostname IPADDRESS ?-async SCRIPT? ?-flushcache?
Attempts to map the specified Internet address IPADDRESS to its fully qualified DNS name (FQDN).

If the -async option is not specified, the command returns the FQDN if available and the empty string otherwise. Note that this is a blocking call and the Tcl event loop will not be run until the command returns.

If the -async option is specified, the command returns right away. The address resolution is done in the background and when completed, SCRIPT is called at the global scope. Three additional arguments are appended to the script before it is executed - IPADDRESS, status success or fail and either the FQDN (when the status is success) or the Winsock error code (when the status is fail). The Winsock error code may be translated to an error string using the map_windows_error command. If no names are found, the status is success but the third argument will be an empty string.

Internally, the command maintains a cache of address to hostname mappings so as to avoid unnecessary lookups. The result is normally returned from here if available. However, if the -flushcache option is specified, the cache entry is deleted and an explicit lookup up is done.
flush_arp_table INTERFACEINDEX
Flushes the ARP table associated with the specified network interface.
get_arp_table ?options?
Returns the entries in the system's ARP table. Each entry is a sublist consisting of four elements - the interface index, the hardware address, the IP address and the type. The type is one of dynamic, static, other or invalid.

The following options control the returned data:

-ifindex INTERFACEINDEX | Limits the returned entries to those in the ARP table for the specified network interface with index INTERFACEINDEX.
-sort | Returns the entries sorted by IP address.
-validonly | Skips entries that are marked invalid.

get_ip_addresses
Returns a list of IP addresses for the system.
get_netif_count
Returns the number of network interfaces in the system.
get_netif_indices
Network interfaces in the system are identified by integer indices. This command retrieves the list of network interfaces in the system.

Example: Show network interface information
get_netif_info NETWORKINTERFACE ?options?
Returns various information about the configuration of a network interface. NETWORKINTERFACE must be the index of a network interface or a name identifying the interface.

The information returned depends on the options specified and is in the form of a flat list of the form "option1 value1 ...". The following options may be specified:

-adapterdescription | Returns a description of the adapter associated with the interface. This option is supported on Windows 2000 and higher.
-adapterindex | Returns the index of the adapter associated with the interface. This option is supported on Windows 2000 and higher.
-adaptername | Returns the name of the adapter associated with the interface. This option is supported on Windows 2000 and higher.
-adminstatus | Returns 1 or 0 depending on whether the interface has been administratively enabled or not.
-all | Returns all option values.
-autoconfigactive | Returns 1 if the interface has been autoconfigured with an address, and 0 otherwise. This option is supported on Windows 2000 and higher.
-autoconfigenabled | Returns 1 if autoconfiguration is enabled on the interface if a DHCP server cannot be found, and 0 otherwise. This option is supported on Windows 2000 and higher.
-defaultgateway | Returns the address of the default gateway on the interface. This option is supported on Windows 2000 and higher.
-description | Returns a description of the interface.
-dhcpenabled | Returns 1 if DHCP is enabled on the interface, else 0. This option is supported on Windows 2000 and higher.
-dhcpleaseend | Returns the time, in seconds since Jan 1, 1970, that the DHCP lease will expire. This option is supported on Windows 2000 and higher.
-dhcpleasestart | Returns the time, in seconds since Jan 1, 1970, that the DHCP lease was obtained. This option is supported on Windows 2000 and higher.
-dhcpserver | Returns the address of the DHCP server on the network interface. This option is supported on Windows 2000 and higher.
-dnsservers | Returns a list of DNS servers on that interface. This option is supported on Windows 2000 and higher.
-havewins | Returns 1 if the interface uses WINS, else 0. This option is supported on Windows 2000 and higher.
-ifindex | Returns the interface index. This is the same as INTERFACEINDEX unless the latter is specified as a name.
-ifname | Returns the name of the network interface.
-inbytes | Returns the number of bytes received through this interface.
-indiscards | Returns the number of incoming packets on this interface that were discarded even though they had no errors.
-inerrors | Returns the number of incoming packets on this interface that were discarded because of errors.
-innonunicastpkts | Returns the number of broadcast or multicast packets received through this interface.
-inunicastpkts | Returns the number of unicast packets received through this interface.
-inunknownprotocols | Returns the number of incoming packets on this interface that were discarded because of the protocol was unknown.
-laststatuschange | Returns the last time the operational status changed.
-ipaddresses | Returns a list sublists containing the IP addresses and masks for the interface.
-mtu | Returns the maximum transmission unit of the interface.
-operstatus | Returns the operational status of the interface. This is one of the values nonoperational, wanunreachable, disconnected, wanconnecting, wanconnected, operational.
-outbytes | Returns the number of bytes transmitted through this interface.
-outdiscards | Returns the number of outgoing packets on this interface that were discarded even though they had no errors.
-outerrors | Returns the number of outgoing packets on this interface that were discarded because of errors.
-outnonunicastpkts | Returns the number of broadcast or multicast packets transmitted through this interface.
-outqlen | Returns the output queue length on this interface.
-outunicastpkts | Returns the number of unicast packets transmitted through this interface.
-physicaladdress | Returns the physical address of the network interface.
-primarywins | Returns the address of the primary WINS server, if any.
-reassemblysize | Returns the maximum size of a reassembled packet that is supported by the interface.
-secondarywins | Returns the address of the secondary WINS server, if any.
-speed | Returns the speed of the network interface in bits per second.
-type | Returns the network interface type. This is one of ethernet, tokenring, fddi, ppp, loopback, slip or other.

Example: Show network interface information

Example: Show network statistics

get_network_info ?options?
Returns various information about network configuration. The information returned depends on the options specified and is in the form of a flat list of the form "option1 value1 ...". The following options may be specified:

-all | Returns all values.
-arpproxyenabled | Returns 1 if ARP proxying is enabled and 0 otherwise.
-dhcpscopeid | Returns the DHCP scope id.
-dnsenabled | Returns 1 if DNS name resolution is enabled on the system and 0 otherwise.
-dnsservers | Returns a list of DNS server addresses used for name resolution.
-domain | Returns the system domain.
-hostname | Returns the host name of the system.
-routingenabled | Returns 1 if routing is enabled on the system and 0 otherwise.

get_outgoing_interface DESTADDR
Returns the index of the network interface that will be used to send a packet to the IP address specified by DESTADDR
get_route ?options?
Returns the best route to a specified destination. The following options may be specified:

-dest DESTADDR | Specifies the destination address for which the route is to be returned. If unspecified, defaults to 0.0.0.0 which corresponds to the default route.
-source SRCADDR | Specifies the source address to be used. This can affect the route selected. Defaults to 0.0.0.0 which indicates the source address should not affect which route is selected.
The returned information is a keyed list with the following fields:

-addr | The destination address that together with the -mask field specifies the address range to which the route applies.
-age | The age of the route in seconds. This is valid only if the Routing and Remote Access service is running and the protocol is netmgmt.
-ifindex | The interface index for this route.
-mask | The network mask that together with -dest specifies the address range to which the route applies.
-metric1 | A routing protocol specific metric value.
-metric2 | A routing protocol specific metric value.
-metric3 | A routing protocol specific metric value.
-metric4 | A routing protocol specific metric value.
-metric5 | A routing protocol specific metric value.
-nexthop | The IP address of next hop in the route to the destination.
-nexthopas | The autonomous system number of the next hop.
-policy | Multi-path route selector condition, typically in IP TOS format as defined in RFC 1354.
-protocol | Protocol that generated the route.
-type | The type of the route. This is one of local, remote, other or invalid.

get_routing_table ?-sort?
Returns the network routing table as a list of routes. Each element of the route is in the format described in the get_route command description.
get_tcp_connections ?options?
Retrieves information about currently active TCP connections similar to the Windows netstat command. The return value is a list of sublists, each corresponding to a single connection.

The information returned for each connection is a flat list of the form "option1 value1 ...". The information returned for each connection is controlled through the following options:

-all | Returns all fields for a connection. This option is assumed if no other field option is specified.
-bindtime | Returns the time at which the last bind operation was done on the socket, or 0 if no bind has been done. On some platforms, this may not be available in which case, an empty string is returned for the value.
-localaddr | Returns the local address being used for the connection.
-localport | Returns the local port number being used for the connection.
-modulename | Returns the name of the process module that owns the socket. On some platforms, this may not be available in which case, an empty string is returned for the value.
-modulepath | Returns the path to the process module that owns the socket. On some platforms, this may not be available in which case, an empty string is returned for the value.
-pid | Returns the PID of the process communicating on the port. On some platforms, this may not be available in which case, an empty string is returned for the value.
-remoteaddr | Returns the address of the remote end of the connection.
-remoteport | Returns the port number of the remote end of the connection.
-state | Returns the connection state. This is one of closed, listen, syn_sent, syn_rcvd, estab, fin_wait1, fin_wait2, close_wait, closing, last_ack, time_wait or delete_tcb.
In addition, the connections for which information is returned may be filtered through the following options. Only those connections that match the specified criteria are returned.

-matchlocaladdr HOSTLIST | Only returns those connections whose local address is one of those specified in HOSTLIST. Each element of HOSTLIST may be either an IP address or a host name.
-matchlocalport PORTNUMBER | Only returns those connections whose local port is the specified number.
-matchpid PID | Only returns those connections owned by the process with the specified PID. On platforms where the PID is not available, specifying this option will generate an error.
-matchremoteaddr HOSTLIST | Only returns those connections whose remote address is one of those specified in HOSTLIST. Each element of HOSTLIST may be either an IP address or a host name.
-matchremoteport PORTNUMBER | Only returns those connections whose remote port is PORTNUMBER.
matchstate STATELIST | Only returns those connections whose state is one those specified in STATELIST which should be a list of connection state values (see above).

get_udp_connections ?options?
Retrieves information about currently active UDP sockets similar to the Windows netstat command. The return value is a list of sublists, each corresponding to a single open socket.

The information returned for each connection is a flat list of the form "option1 value1 ...". The fields returned for each connection is controlled through the following options:

-all | Returns all fields for a connection. This option is assumed if no other field option is specified.
-bindtime | Returns the time at which the last bind operation was done on the socket, or 0 if no bind has been done. On some platforms, this may not be available in which case, an empty string is returned for the value.
-localaddr | Returns the local address being used for the connection.
-localport | Returns the local port number being used for the connection.
-modulename | Returns the name of the process module that owns the socket. On some platforms, this may not be available in which case, an empty string is returned for the value.
-modulepath | Returns the path to the process module that owns the socket. On some platforms, this may not be available in which case, an empty string is returned for the value.
-pid | Returns the PID of the process communicating on the port. On some platforms, this may not be available in which case, an empty string is returned for the value.
In addition, the connections for which information is returned may be filtered through the following options. Only those connections that match the specified criteria are returned.

-matchlocaladdr HOSTLIST | Only returns those connections whose local address is one of those specified in HOSTLIST. Each element of HOSTLIST may be either an IP address or a host name.
-matchlocalport PORTNUMBER | Only returns those connections whose local port is the specified number.
-matchpid PID | Only returns those connections owned by the process with the specified PID. On platforms where the PID is not available, specifying this option will generate an error.

hostname_to_address HOSTNAME ?-async SCRIPT? ?-flushcache?
Attempts to map the specified host name to its IP addresses. Note there may be more than one address associated with a host name.

If the -async option is not specified, the command returns the list of IP addresses corresponding to the host if available and an empty list otherwise. Note that this is a blocking call and the Tcl event loop will not be run until the command returns.

If the -async option is specified, the command returns right away. The name resolution is done in the background and when completed, SCRIPT is called at the global scope. Three additional arguments are appended to the script before it is executed - HOSTNAME, status success or fail and either the list of IP addresses (when the status is success) or the Winsock error code (when the status is fail). The Winsock error code may be translated to an error string using the map_windows_error command. If no addresses are found, the status is success but the third argument will be an empty list.

Internally, the command maintains a cache of address to hostname mappings so as to avoid unnecessary lookups. The result is normally returned from here if available. However, if the -flushcache option is specified, the cache entry is deleted and an explicit lookup up is done.
hwaddr_to_ipaddr HWADDR ?VARNAME?
Returns the IP address corresponding to the given hardware address. If VARNAME is specified, the command stores the result in a variable of that name in the caller's context if a mapping can be found and returns 1. Otherwise the command returns 0 without affecting the variable. If VARNAME is not specified, the command returns the IP address if a mapping is found and generates a Tcl exception otherwise.
ipaddr_to_hwaddr IPADDR ?VARNAME?
Returns the hardware address corresponding to the given IP address. If VARNAME is specified, the command stores the result in a variable of that name in the caller's context if a mapping can be found and returns 1. Otherwise the command returns 0 without affecting the variable. If VARNAME is not specified, the command returns the hardware address if a mapping is found and generates a Tcl exception otherwise.

Example: Map an IP address to a physical address

port_to_service PORTNUMBER
Returns the service name (e.g. http) corresponding to the specified port number. If no corresponding service name exists, an empty string is returned.
service_to_port SERVICENAME
Returns the port number corresponding to the specified service name (e.g. http). If the service name is not defined, an empty string is returned. If SERVICENAME is a port number, it is returned.
terminate_tcp_connections ?options?
Terminates all connections that match all the options specified. Any options that are not specified are assumed to match. The valid matching options are:

-matchlocaladdr IPADDR | Only matches those connections whose local address is bound to IPADDR.
-matchlocalport PORTNUMBER | Only matches those connections whose local port is the specified number.
-matchpid PID | Only matches those connections owned by the process with the specified PID. On platforms where the PID is not available, specifying this option will generate an error.
-matchremoteaddr IPADDR | Only matches those connections whose remote address is bound to IPADDR.
-matchremoteport PORTNUMBER | Only matches those connections whose remote port is PORTNUMBER.
matchstate STATELIST | Only matches those connections whose state is one those specified in STATELIST which should be a list of connection state values. See get_tcp_connections for a list of valid values.

COPYRIGHT

Copyright © 2004-2009, Ashok P. Nadkarni


Files, Disks and Volumes - Disk information

Files, Disks and Volumes

Commands related to files, disks and volumes

SYNOPSIS

package require twapi

begin_filesystem_monitor PATH SCRIPT ?options?
cancel_filesystem_monitor MONITORID
find_logical_drives ?-type DRIVETYPELIST?
find_physical_disks
file_properties_dialog FILEPATH ?options?
find_volumes
find_volume_mount_points VOLNAME
get_drive_info DRIVE ?options?
get_drive_type DRIVE
get_file_times FILE ?options?
get_file_version_resource PATH ?options? ?STRINGNAME...?
get_mounted_volume_name MOUNTPOINT
get_physical_disk_info DISK ?options?
get_volume_info DRIVE ?options?
get_volume_mount_point_for_path PATH
map_drive_local DRIVE PATH ?options?
mount_volume MOUNTPOINTPATH VOLNAME
set_drive_label DRIVE NAME
set_file_times FILE ?options?
unmap_drive_local DRIVE ?options?
unmount_volume MOUNTPOINTPATH
user_drive_space_available drive space
volume_properties_dialog VOLUME ?options?

DESCRIPTION

This package provides procedures related to file, disk and volume information in Windows operating systems.

Physical disks

The find_physical_disks command returns the list of physical disks installed in the system. The get_physical_disk_info command can then be used to retrieve detailed information about the physical disk.

Volumes

The command find_volumes returns a list of volumes on the system. The command get_volume_info returns various information about a volume (logical drive) including size and space utilization, file system characteristics and device.

The command find_volume_mount_points returns the list of volume mount points on a particular volume. Commands mount_volume and unmount_volume can be used to set and remove volumes from volume mount points. The command get_mounted_volume_name will return the name of the volume mounted on a drive letter or volume mount point.

The command volume_properties_dialog displays the shell property sheet dialog for a volume.

Logical drives

For all drive related commands, the drive parameter may be specified as a single drive letter, a drive letter followed by a :, or as the root path of the drive (eg. C:\)

The command find_logical_drives returns a list of drives in the system of a specified type. get_drive_type returns the type (fixed, remote, etc.) of the logical drive.

The command user_drive_space_available can be used to check if sufficient free space is available on a drive.

The command set_drive_label may be used to set the volume name (drive label).

The command map_drive_local and unmap_drive_local may be used to assign and unassign a drive letter to a local path.

File system

The commands begin_filesystem_monitor and cancel_filesystem_monitor can be used for monitoring changes to the file system.

The get_file_version_resource returns various information stored within the version resource of a file.

The command file_properties_dialog displays the shell property sheet dialog for a file.

The commands get_file_times and set_file_times and allow retrieval and setting of the times associated with a file.

Commands

begin_filesystem_monitor PATH SCRIPT ?options?
Registers SCRIPT to be invoked when the specified types of changes occur in the directory of subtree matching PATH.

The command returns an identifier corresponding to the monitoring callback. When no longer interested in the specified changes, the returned identifier should be passed to cancel_filesystem_monitor to end the monitoring.

The following options specify the type of changes to be monitored:

-access BOOLEAN | If true, changes to the last access time are monitored.
-attr BOOLEAN | If true, attribute changes, are monitored.
-create BOOLEAN | If true, changes to the creation times are monitored.
-dirname BOOLEAN | If true, directory name changes, including creation and renaming, are monitored.
-filename BOOLEAN | If true, file name changes, including file creation, renaming and deletion, are monitored.
-patterns PATTERNLIST | If specified, notification callbacks are invoked only on those files and directories that match one of the patterns in PATTERNLIST. See below for more detail.
-secd BOOLEAN | If true, changes to security descriptors in the specified directories are monitored.
-size BOOLEAN | If true, size changes in the specified directories are monitored.
-subtree BOOLEAN | If true, all subdirectories under the specified directory PATH are monitored in addition to PATH itself. If false (default), only the directory indicated by PATH is monitored.
-write BOOLEAN | If true, changes to the last write time of files in the specified directories are monitored.
By default, all options are false if unspecified. However, if no options related to the type changes to be monitored are present (either true or false), the command will monitor all types of changes.

When a file system change is detected, the SCRIPT is invoked after being appended with a list each element of which is a pair consisting the notification type and the file or directory name (except when the type is error). The type is one of the following values:

added | The file or directory was added.
removed | The file or directory was deleted.
modified | The file or directory was modified. This includes changes to attributes or timestamps.
renameold | The file or directory was renamed. The associated name is the old name.
renamenew | The file or directory was renamed. The associated name is the new name.
error | There was an error in the operation. In this case the second element is the identifier of the callback for which the error occurred and the third element an error message. On receiving an error notification, the monitoring should generally be canceled by calling cancel_filesystem_monitor.
Note that the file names being reported may be either in longname or shortname (8.3) format. Moreover, depending on the buffering and caching by the operating system, a single write may result in one or more notifications.

If the -patterns option is specified, then the value associated with the option is a pattern filter that is used to match against the name component being reported. SCRIPT will be invoked only if the pattern filter matches.

Each element of the pattern list is a string beginning with either + or - followed by a pattern that is used for matching using the same rules as for the Tcl string match -nocase command. Note that \ path separator need to be escaped with another \ just as in the string match case. Alternatively, you can use / as the path separator in the pattern.

The name component being reported is matched against each element of the pattern list. When a match occurs, further elements of the pattern list are not matched. If the matching element is prefixed with a +, then SCRIPT is invoked. If the matching element is prefixed with a -, then the pattern filter is deemed to have not matched and SCRIPT is not invoked for the notification. Even in this case, no further matching is attempted against the remaining patterns. Pattern elements that do not begin with +, or - are treated as having an implicit + prefix.

If a non-empty pattern filter is specified but no element matches, the pattern filter is treated as having not matched, and SCRIPT is not invoked. Thus a pattern filter that only has - type elements will never match anything. Note a pattern list where no element matches is different from the case where -patterns is not specified or PATTERNLIST is empty in which case the pattern filter is treated as matched.

Note that the pattern matching is done only against the name component being reported, not against the full path.

Some examples of pattern matching are below (assume callback is your SCRIPT procedure):

begin_filesystem_monitor c:/temp callback -patterns {*.exe}

will only monitor files in c:\temp with .exe extensions.

begin_filesystem_monitor c:/temp callback -patterns {-*.foo +*.fo*}

will monitor files in c:\temp with an extension beginning with .fo except if the extension is .foo.

begin_filesystem_monitor c:/temp callback -patterns {+*.fo -*.foo}

will monitor files in c:\temp with an extension beginning with .fo including those with extension .foo. The second pattern -*.foo has no effect as the matching stops as soon as a match is found.
cancel_filesystem_monitor MONITORID
Cancels monitoring of the file system corresponding to MONITORID which must be an identifier returned by begin_filesystem_monitor.
find_logical_drives ?-type DRIVETYPELIST?
Returns a list of the logical drives in the system. If option -type not specified, all drives in the system are returned. Otherwise, only drives whose type is in DRIVETYPELIST are returned. DRIVETYPELIST must be a subset of the values returned by the get_drive_type command.

Example: List all drives on a system

Example: List the remote drives on a system
find_physical_disks
Returns the list of physical disks in the system. The returned paths can be passed to CreateFile or create_file to get a handle to the raw physical disk.
file_properties_dialog FILEPATH ?options?
Displays the shell property dialog for the specified file. The following options may be specified:

-hwin HWIN | If specified, HWIN is the handle to the window to be used as the parent for the dialog.
-page PAGENAME | Specifies the name of the property sheet page to be displayed. If unspecified, the default page is displayed.

find_volumes
Returns the list of volumes in the system. Each entry in the list includes a trailing slash.
find_volume_mount_points VOLNAME
Returns the list of volume mount points on the volume whose name is VOLNAME.
get_drive_info DRIVE ?options?
Synonym for get_volume_info.
get_drive_type DRIVE
Returns the type of the drive - unknown, removable, fixed, remote, cdrom or ramdisk or invalid.
get_file_times FILE ?options?
Retrieves the creation, access and modification timestamps for a file. The latter two are available through the Tcl file command which however does not provide the creation time for a file. FILE may either be the path to the file, an open Tcl channel to the open file or a Win32 handle to an open file. In the latter two cases, the file must have been opened for read access.

The information returned is a flat list of option value pairs. options, which may contain one or more of the following values, controls the information returned.

-all | Returns all fields.
-atime | Returns the time of last access for the file.
-ctime | Returns the creation time for the file.
-mtime | Returns the time of last modification for the file.
All times are returned in the same format as get_system_time.

get_file_version_resource PATH ?options? ?STRINGNAME...?
Returns the information stored within the version resource of a file. The command will generate a Tcl error if the file specified by PATH does not contain a version resource.

The version resource consists of two parts. The information in the first part is in a fixed format and can be retrieved by specifying appropriate options in options. The second part is a string table, the entries in which can be retrieved by specifying the key as a STRINGNAME argument.

The following options may be used with the command:

-all | Returns all information in the fixed part.
-datetime | Returns the date and time the file was created (as stored in the version resource) as a 64 bit number. Refer to large_system_time_to_timelist or large_system_time_to_secs_since_1970.
-fileversion | Returns the file version as indicated in the version resource. This is returned in the format MAJOR.MINOR.BUILD.PRIVATE. Note this is not necessarily identical to the value specified for the FileVersion entry in the string table.
-fileos | Returns a value specifying the platform for which the file was designed. This may be one of dos (MS-DOS), os216 (16-bit OS/2), os232 (16-bit OS/2), nt (Windows NT), wince (Windows CE), windows16 (16-bit Windows), pm16 (16-bit Presentation Manager), pm32 (32-bit Presentation Manager), windows32 (32-bit Windows), dos_windows32 (32-bit Windows on MS-DOS), os216_pm16 (16-bit Presentation Manager on 16-bit OS/2), os232_pm32 (32-bit Presentation Manager on 32-bit OS/2) or nt_windows32 (32-bit Windows on Windows NT).
-filetype | Returns the file type which may be one of the following: application, dll, driver.printer, driver.keyboard, driver.language, driver.display, driver.mouse, driver.network, driver.system, driver.installable, driver.sound, driver.comm, driver.inputmethod, driver.versionedprinter, driver.DRIVERSUBTYPENUMBER, font.raster, font.vector, font.truetype, font.FONTSUBTYPENUMBER, vxd.VIRTUALDEVICEID, staticlib or FILETYPENUMBER.FILESUBTYPENUMBER. (Note in cases where the file type or subtype is not recognized, the actual numeric value is returned.)
-flags | Returns a list of symbols corresponding to flags set in the version resource. The list may contain symbols from the following: debug, prerelease, patched, privatebuild, infoinferred and specialbuild. In addition, the list may also contain a numeric value corresponding to bits that are set but are not recognized as one of the above.
-foundcodepage | Returns the code page of the matched string table (see below).
-foundlangid | Returns the language of the matched string table (see below). The returned value is a list of two elements containing the numeric language identifier and a description string for the corresponding language.
-langid LANGID | Specifies LANGID as the language identifier to be used for string table lookup (see below). By default, the language identifier returned by get_user_ui_langid is used.
-codepage CODEPAGE | Specifies CODEPAGE as the code page to be used for string table lookup (see below).
-productversion | Returns the product version as indicated in the version resource. This is returned in the format MAJOR.MINOR.BUILD.PRIVATE. Note this is not necessarily identical to the value specified for the ProductVersion entry in the string table.
-signature | Contains a longword that is a signature for the fixed part of the version resource. Not particularly useful for the application.
-structversion | Returns the version of the version resource format.
In addition to the options that retrieve fixed portions of the version resource, the caller may also specify string names corresponding to language-specific string tables in the version resource. Each such STRINGNAME is looked up in the string table and returned as a STRINGNAME VALUE pair. If a particular string name does not exist in the string table, an empty string is returned as its value. The following string names are commonly defined in version resources: Comments, InternalName, ProductName, CompanyName, LegalCopyright, ProductVersion, FileDescription, LegalTrademarks, PrivateBuild, FileVersion, OriginalFilename, SpecialBuild.

The version resource may contain multiple string tables for different languages and code pages. The caller can control the string table used through the -langid and -codepage options. The command uses the following algorithm in selecting the string table that is looked up.

  • If a string table exactly matches the language id and code page, it is used.
  • Otherwise, if a string table exactly matches the language id, it is used irrespective of the code page.
  • Otherwise, a string table matching the primary language portion of the language id and the code page is used.
  • Otherwise, a string table matching the primary language portion of the language id is used regardless of the code page.
  • Otherwise, a string table specified as language neutral is used.
  • Otherwise, a string table specified as English is used.
  • Finally, the string table corresponding to the first language and code page specified in the resource is used.
The language identifier and code page corresponding to the actual string table that was looked up may be optionally be retrieved by passing the -foundlangid and -foundcodepage to the command.
get_mounted_volume_name MOUNTPOINT
Returns the name of a mounted volume. The returned name has a trailing backslash appended. MOUNTPOINT must specify a root directory of a local drive or path to a volume mount point. Specifying remote file shares will generate an error.
get_physical_disk_info DISK ?options?
Returns information about a physical disk. DISK is a device path to the physical disk in the format returned by find_physical_disks. The command returns a keyed list with fields depending on the passed options:

-all | Returns all fields.
-geometry | Returns the geometry of the disk. The value is itself a keyed list with the fields -cylinders, -mediatype, -trackspercylinder, -sectorspertrack and -bytespersector.
-layout | Returns the layout of the disk in terms of how it is partitioned. The returned value is a keyed list with the fields depending on how the disk is partitioned. See below for a discussion.

The partitioning of a disk can take several forms and the information returned by the -layout differs in each case. The following is a brief summary that assumes familiarity with disk formats. See the Windows DDK documentation for details.

On Windows 2000, the -layout field value is a keyed list with the fields -partitioncount, -signature and -partitions containing the number of partitions of the disk, the disk signature, and a list of partitions. Each element of the partition list is itself a keyed list with the fields -startingoffset, -partitionlength, -hiddensectors, -partitionnumber, -partitiontype, -bootindicator, -recognizedpartition and -rewritepartition.

On Windows XP and newer operating systems, the -layout field value is a keyed list with the fields, -partitioncount, -partitionstyle and -partitions. The value of the -partitionstyle field is one of the values mbr, gpt, raw or unknown. The -partitions field is a list each element of which is itself a keyed list containing information about each partition. Note that the number of elements of the -partitions list may not match the value of the -partitioncount field in case information for some partitions cannot be retrieved. Every element of the -partitions field will have the fields -partitionstyle, -startingoffset, -partitionlength, -partitionnumber and -rewritepartition. In addition, if -partitionstyle is mbr, the element will also have the fields -hiddensectors, -partitiontype, -bootindicator and -recognizedpartition. If -partitionstyle is gpt, it will have the fields -partitiontype, -partitionif, -attributes and -name. Partition styles raw and unknown have no additional fields.

get_volume_info DRIVE ?options?
Returns attributes and properties of the specified volume as a list of the form "option1 value1 ...". DRIVE may be either a DOS drive, file share or a volume. Note certain options are not valid except when DRIVE specifies a drive letter (see below).

The values returned depend on which of the following options are specified:

-all | Returns all fields except -type and -device which have to be explicitly specified since they are not valid for volumes.
-attr | Returns a list containing one or more of the values case_preserved_names, unicode_on_disk, persistent_acls, file_compression, volume_quotas, supports_sparse_files, supports_reparse_points, supports_remote_storage, volume_is_compressed, supports_object_ids, supports_encryption, named_streams, or read_only_volume. These indicate the features supported by the drive's file system. Refer to the documentation for GetVolumeInformation function in the Windows SDK for details on these.
-device | Returns a list the first element of which is the device name mapping for the drive. Remaining elements containing prior undeleted mappings for the drive. Only valid if DRIVE is a drive letter. For UNC paths, an empty string will be returned.
-extents | Returns a list of disk extents describing the physical location of the volume. Each disk extent is a keyed list containing 3 fields: -disknumber identifying the physical disk, -startingoffset containing the byte offset in the physical disk that the extent starts at, and -extentlength containing the size of the extent. An empty list is returned for extents if they cannot be determined (for example, for remote drives).
-freespace | Returns the total size of the unused space on the drive in bytes.
-fstype | Returns the type of the file system on the volume (eg. NTFS).
-label | Returns the label of the drive.
-maxcomponentlen | Returns the maximum length allowed for a single component in a file path.
-serialnum | Returns the serial number of the drive in hexadecimal format.
-size | Returns the size of the drive in bytes.
-type | Returns the type of the drive. Only valid if DRIVE is a drive letter. This may have one of the values unknown, removable, fixed, remote, cdrom or ramdisk. In case the drive path is invalid, the value invalid is returned in this field.
-used | Returns the total size of the used space on the drive in bytes.
-useravail | Returns the total size of the unused space on the drive that is available for the caller. This may be less than the freespace field if quotas are in effect.
Example: List drives that are almost full

Example: Check if the given drive supports unicode filenames

get_volume_mount_point_for_path PATH
Returns the volume mount point below which the file specified by PATH resides. Refer to documentation for GetVolumePathName in the Windows SDK for more details.
map_drive_local DRIVE PATH ?options?
Maps the fully qualified path PATH to the specified drive letter. The mapping established by this command is not persistent across reboots. It may also be removed using the unmap_drive_local command.

The following options may be specified with the command:

-raw Specifies that PATH is a raw path specification that includes the device name as opposed to a drive letter.

mount_volume MOUNTPOINTPATH VOLNAME
Mounts the volume specified by VOLNAME at the mount point specified by MOUNTPOINTPATH. The directory MOUNTPOINTPATH must be empty. VOLNAME must be of the form \\?\VOLUME{GUID}\. If any volume is already mounted at MOUNTPOINTPATH, it will be silently unmounted before the new mount is performed.
set_drive_label DRIVE NAME
Sets the volume name for the specified drive. NAME may be an empty string in which case the drive label is removed.

Example: Change the label of a drive
set_file_times FILE ?options?
Sets the creation, access or modification timestamps for a file. FILE may either be the path to the file, an open Tcl channel to the open file or a Win32 handle to an open file. In the latter two cases, the file must have been opened for write access.

The timestamps modified depend on the options specified:

-atime LARGETIMESTAMP | Sets the time of last access for the file.
-ctime LARGETIMESTAMP | Sets the creation time for the file.
-mtime LARGETIMESTAMP | Sets the time of last modification for the file.
-preserveatime | Indicates that the time of last access for an open file should be preserved and not updated when the file is closed. This option can only be specified if FILE is either an open Tcl channel or Win32 handle and not if it is a file path. Also, the option cannot be used together with -atime.
All time values must be specified in the same format as get_system_time. You can use secs_since_1970_to_large_system_time to convert the format used by Tcl's clock command to this format.

unmap_drive_local DRIVE ?options?
Unmaps the drive specified by DRIVE. This must reference a local drive. The following options may be specified with the command:

-path PATH | Specifies that the drive should be unmapped only if it refers to the location specified by PATH. This is useful to ensure drive letters are not unmapped when they have been redefined to point elsewhere.
-raw | Specifies that PATH argument specified with the -path option is a raw path specification that includes the device name as opposed to a drive letter.

unmount_volume MOUNTPOINTPATH
Unmounts the volume at the mount point specified by MOUNTPOINTPATH. If MOUNTPOINTPATH is a root directory of a drive, the corresponding DOS drive letter mapping is removed.
user_drive_space_available drive space
Returns 1 if the given drive has at least space bytes free, and 0 otherwise. Note that space is compared to the free bytes available to the caller as opposed to total free bytes on the drive. The former may be smaller if disk quotas are being enforced on the drive.

Example: Check available disk space

volume_properties_dialog VOLUME ?options?
Displays the shell property dialog for the specified volume. The following options may be specified:

-hwin HWIN | If specified, HWIN is the handle to the window to be used as the parent for the dialog.
-page PAGENAME | Specifies the name of the property sheet page to be displayed. If unspecified, the default page is displayed.

COPYRIGHT

Copyright © 2003-2009 Ashok P. Nadkarni


Network shares and Lan Manager - Network share and Lan Manager session management

Network shares and Lan Manager

Commands related to management of network shares and Lan Manager sessions

SYNOPSIS

package require twapi

close_lm_open_file FILEID ?-system SYSTEMNAME?
connect_share SERVERSHARE ?options?
delete_share SHARENAME ?-system SYSTEMNAME?
disconnect_share SHARE ?options?
end_lm_sessions ?options?
find_lm_connections ?options?
find_lm_open_files ?options?
find_lm_sessions ?options?
get_client_share_info SHAREPATH ?options?
get_client_shares
get_mapped_share_info SHAREPATH ?options?
get_share_info SHARENAME ?options?
get_shares ?options?
get_lm_open_file_info FILEID ?options?
get_lm_session_info CLIENTSYSTEM USER ?options?
new_share SHARENAME RESOURCE ?options?
set_share_info SHARENAME ?options?

DESCRIPTION

This module provides commands related to management of Windows network shares and the Lan Manager sessions over which they are implemented.

Lan Manager sessions

A Lan Manager (LM) session is a logical connection between the client and server over which all communications related to shares takes place. LM sessions are created and terminated on the fly by the client as and when needed.

Lan Manager sessions on a server can be enumerated through the find_lm_sessions command. Information about individual sessions can be obtained through the get_lm_session_info command. Existing sessions can be deleted using end_lm_sessions.

The files and resource opened within a Lan Manager session can be enumerated through the find_lm_open_files command. Information about individual open files can be obtained through get_lm_open_file_info and closed using close_lm_open_file.

Information about the connections to a shared resource on a system can be obtained through find_lm_connections.

Network Shares - Server

These commands work with all types of Windows network shares exported from a server including files and disks, printers, devices and IPC.

The command new_share creates a new share of the specified type. The command delete_share removes an existing share.

The commands get_shares and get_share_info allow enumeration and retrieval of detailed information about a share. The command set_share_info allows attributes of an existing share to be modified.

Network Shares - Client

The following commands deal with client side of network share connections.

The commands connect_share and disconnect_share are used to establish and remove client side connections to network shares. The command get_client_shares lists all current connections to any network share. Details about a particular connected share can be obtained through the get_client_share_info command.

When a local device (for example, a printer port or a drive letter) is mapped to a network drive, information about the mapping may be obtained through the get_mapped_share_info command.

Share Types

The type of a network share is indicated by a token that indicates the basic type, such as file or print queue, followed by one or more tokens that indicate additional attributes such as whether it is a temporary share. The basic share type token is one of file, print, ipc or device corresponding to a file, print queue, interprocess communication, and a communication device respectively. Additional type information may contain the tokens temporary, which indicates a temporary share, and special, which indicates a administrative share.

Commands

close_lm_open_file FILEID ?-system SYSTEMNAME?
Closed the file or resource associated with FILEID. The file ids open within a Lan Manager session may be obtained through the find_lm_open_files command. Option -system may be specified to indicate the system on which the command is to be executed. By default, this is the local system.
connect_share SERVERSHARE ?options?
Establishes a new connection to a network share, optionally mapping it to a local device. SERVERSHARE is of the form \\SERVERNAME\SHARE and is the name of the share to connect to. The following options may be specified to control the connection characterisics:

-type | Specifies the type of network share. This must be one of any (default), file for file and disk shares or printer for print shares.
-localdevice DEVICENAME By default, the command establishes a connection to SERVERSHARE but does not map it to a local device. Specifying this option maps the network share connection to a local device, for example a drive letter or printer port.

Note that if this option is specified, the -type option must also be specified with a value of disk or printer.
-provider PROVIDERNAME | This option allows specification of a network provider to be used for the connection. Generally, this option should not be specified allowing Windows to select the appropriate network provider based on SERVERSHARE.
-user USERNAME | Specifies the user account to use to connect to the network share. By default, this is the current user account.
-password PASSWORD | Specifies the password to be used for connecting to the network share. This option is ignored if either -defaultpassword or -nopassword is specified.
-defaultpassword | Specifies that the password for the current user account is to be used for connecting. This option cannot be used with the -nopassword option.
-nopassword | Specifies that no password is to be used for connecting. This option cannot be used with the -defaultpassword option.
-interactive | Specifies that a user name and password dialog should be displayed to the user if the network share login fails. The connection is retried using the values entered by the user.
-prompt | Displays a dialog allowing the user to change the user name and password before the connection attempt is made. This option has no effect if -interactive is not specified.
-commandline | If this option is specified, the operating system will prompt the user for the password on the command line rather than showing the password dialog. This option has no effect if -interactive is not specified. This option is not supported on Windows 2000. An error will be generated if this option is specified on those platforms.
-window HWIN | Specifies that the window identified by HWIN is to be used as the owner window for any password dialogs that are displayed.
-updateprofile | If this option is specified, the user's profile is updated so that the network share connection will be reestablished every time the user logs in.
Example: Map a drive to a network share

delete_share SHARENAME ?-system SYSTEMNAME?
Deletes a share. By default the share is assumed to be on the local system unless the -system option is specified.
disconnect_share SHARE ?options?
Disconnects the network share SHARE. The following options may be specified:

-force | Forces the network share connection to be closed even if there are open files or print jobs on the connection.
-updateprofile | If this option is specified, the user's profile is updated so that the network share connection will not be reestablished every time the user logs in.

end_lm_sessions ?options?
Terminates all Lan Manager sessions matching the specified options. options may include the following matching criteria:

-system SYSTEMNAME | Specifies the name of the system on which the command is to be executed. By default, this is the local system.
-client SYSTEMNAME | Specifies the name of the client system whose sessions are to be terminated.
-user USERNAME | Specifies the name of the user whose sessions are to be terminated.
Note that at least one of the options -user or -client must be specified.

find_lm_connections ?options?
Returns information about the connections to a share on a server or established from a particular client system. The return value is a list of sublists containing information about each connection. The actual data included depends on the options specified.

-activeseconds | Returns the number of seconds the connection has been established.
-all | Returns all data fields for each connection.
-client CLIENTNAME | Specifies that only connections from client CLIENTNAME should be included in the returned list. This option and option -share are mutually exclusive.
-clientname | Returns the name of the client computer for the connection.
-id | Returns the connection id.
-opencount | Returns number of resources currently opened through the connection.
-share SHARENAME | Specifies that only connections to the share identified by SHARENAME should be included in the returned list. This option and option -client are mutually exclusive.
-sharename | Returns the name of the share to which the connection is attached.
-system SYSTEMNAME | Specifies the name of the system on which the command is to be executed. By default, this is the local system.
-type | Returns the share type of the resource to which the connection is made (see Share Types).
-usercount | Returns number of users currently using the connection.
-username | Returns name of the user that made the connection.

find_lm_open_files ?options?
Returns a list of sublists containing information about files and devices opened through a Lan Manager session. The actual data included depends on the options specified.

The following options specify matching criteria that control which sessions are returned:

-system SYSTEMNAME | Specifies the name of the system on which the command is to be executed. By default, this is the local system.
-basepath PATHPREFIX | Specifies that all returned files should have begin with PATHPREFIX. If PATHPREFIX is an empty string (default), all open files are included.
Additional options control the data returned for each open file. Refer to get_lm_open_file_info for a list of these options.

find_lm_sessions ?options?
Returns a list of Lan Manager sessions matching the specified options. The list contains sublists containing data for each session. The actual data included depends on the options specified.

The following options specify matching criteria that control which sessions are returned:

-system SYSTEMNAME | Specifies the name of the system on which the command is to be executed. By default, this is the local system.
-client SYSTEMNAME | Specifies the name of the client system whose sessions are to be included. If SYSTEMNAME is an empty string (default), all client systems are included.
-user USERNAME | Specifies the name of the user whose sessions are to be included. If USERNAME is an empty string (default), all users are included.
Additional options control the data returned for each session. Refer to get_lm_session_info for a list of these options.

get_client_share_info SHAREPATH ?options?
Returns information about the connected network share identified by SHAREPATH. SHAREPATH may be either a UNC format share or a locally mapped device.

The information returned depends on the specified options and is in the form of a flat list of "option value" pairs.

-all | Returns all configuration data for the connected share.
-comment | Returns the comment describing the connected share, if any
-domain | Returns the domain name of the connected share.
-localdevice | Returns the local device to which the share is mapped and an empty string otherwise.
-opencount | Returns the number of open handles that are open to resources on the remote share.
-provider | Returns the name of the network service provider that owns the share.
-remoteshare | Returns the name of the remote share.
-status | Returns the status of the share. This may be one of connected, paused, lostsession, disconnected, networkerror, connecting, reconnecting or unknown.
-type | Returns the type of the network share. This may be one of file, printer, char, ipc or unknown.
-usecount | Returns the number of references to the remote share. Note the remote share may be connected multiple times with and without local device mappings.
-user | The name of the user who initiated the connection.

get_client_shares
Returns a list of currently connected network shares. The returned list consists of sublists corresponding to each connected network share. The first element of each sublist is the local device (for example X:). This may be an empty string if the connection has not been mapped to a local device. The second element of the sublist is the name of the server share for the connection.

Example: List connected shares
get_mapped_share_info SHAREPATH ?options?
This command is now deprecated. Use get_client_share_info instead.

Retrieves various information about a network share. SHAREPATH can be any path under a network share but the path must begin with the local device name, for example C:, if it was mapped to a local device and the share name, for example, \\SERVERNAME\SHARENAME, if no local device was mapped to it.

The information returned depends on the specified options and is in the form of a flat list of "option value" pairs.

-all | Returns all configuration data for the share connection.
-user | Returns the user account name under which the connection was established.
-uncpath | Returns the UNC format path corresponding to SHAREPATH
-uncvolume | Returns the UNC format name of the server share
-relative_path | Returns the relative path component of SHAREPATH under the server share.
For example, assume \\myfileserver\userdata is mapped to drive X:. Then the command

twapi::get_mapped_share_info X:\dir\file -uncpath -uncvolume -relativepath

will return

-uncpath \\myfileserver\userdata\dir\file -uncvolume \\myfileserver\userdata -relativepath \dir\file

Example: Show mapped drive information
get_share_info SHARENAME ?options?
Retrieves information pertaining to the specified share. By default, the share is assumed to be on the local system. The -system may be used to specify the name of a remote system.

The information returned depends on the specified options and is in the form of a flat list of "option value" pairs.

-all | Returns all configuration data for the share.
-name | Returns the name of the share as configured. This is generally SHARENAME but may differ in the character case.
-type | Returns the type of the share. See Share Types for details.
-path | Returns the path or name of the resource being shared.
-comment | Returns the comment associated with the share.
-max_conn | Returns the maximum number of connections that are permitted for the share. A value of -1 indicates that there is no limit.
-current_conn | Returns the current number of connections to the share.
-secd | Returns the security descriptor attached to the share.
Example: List shares exported from a system

get_shares ?options?
This command enumerates all the shares exported on a system. The following options control the shares that are enumerated.

-system SYSTEMNAME | Specifies the name of the system whose shares are to be enumerated. By default, this is the local system.
-type SHARETYPE | Specifies the type of the share to include in the enumeration. SHARETYPE must be one of base share types listed in Share Types. By default, all share types are enumerated.
-excludespecial | Specifying this option causes special shares (see Share Types) not to be included in the enumeration.
Example: List shares exported from a system

get_lm_open_file_info FILEID ?options?
Returns a list of field values pairs containing data for a file or resource opened in a Lan Manager session. The file is identified by FILEID. find_lm_open_files returns a list of all such ids. The command will generate an error there is no file open with the specified id.

The actual data returned depends on the options specified. The following options may be specified:

-system SYSTEMNAME | Specifies the name of the system on which the command is to be executed. By default, this is the local system.
-all | Returns all data fields.
-id | Returns the file id of the open resource.
-lockcount | Returns the number of locks on the open resource.
-path | Returns the path of the open resource.
-permissions | Returns a list of zero or more from among read, write and create corresponding to the access permissions for the opening application.
-username | Returns the name of the user that opened the resource.

get_lm_session_info CLIENTSYSTEM USER ?options?
Returns a list of field values pairs containing data for a Lan Manager session. The Lan Manager session is identified by CLIENTSYSTEM which identifies a client system and USER which identifies the user that authenticated the session. The actual data returned depends on the options specified. The command will generate an error if no matching connection is found.

The following options may be specified:

-system SYSTEMNAME | Specifies the name of the system on which the command is to be executed. By default, this is the local system.
-all | Returns all data fields.
-activeseconds | Returns the number of seconds session has been active.
-attrs | Returns a list of tokens describing the session attributes. The tokens may include guest, indicating the session was established using a guest account, and noencryption, indicating the session was established without using password encryption.
-clientname | Returns the UNC name of the client system.
-clienttype | Returns a string identifying the type of client system.
-idleseconds | Returns the number of seconds the session has been idle.
-opencount | Returns the number of open files, devices and pipes opened in the session.
-transport | Returns the name of the underlying transport over which the session runs.
-username | Returns the name of the user account under which the session was established.

new_share SHARENAME RESOURCE ?options?
Creates a new share with name SHARENAME that exports the specified resource RESOURCE. Unless specified through the -type option, the share is assumed to be a file share and RESOURCE is assumed to be the directory path.

The following options control the various attributes of the share:

-system SYSTEMNAME | Specifies the name of the system on which the share is to be created. By default, this is the local system.
-comment COMMENT | Specifies a comment to be associated with the share. This is displayed to users connecting to the share. If unspecified or empty, this defaults to the share name.
-max_conn MAX_NUM_CONNECTION | Specifies the maximum number of connections to be allowed. If this is not specified, or is specified as -1, there is no limit to the number of connections allowed to the share.
-secd SECURITY_DESCRIPTOR | Specifies the security descriptor to be attached to the share. If unspecified, it defaults to allowing group Everyone (well-known SID S-1-1-0) read access similar to default permissions when creating a share from Windows Explorer.
-type SHARETYPE | Specifies the type of the share. See Share Types for details. This defaults to a file share.
Example: Export a network share

set_share_info SHARENAME ?options?
Changes the configuration of the specified share. By default, the share is assumed to be on the local system. The -system may be used to specify the name of a remote system.

The configuration data that is to be modified is specified through the following options:

-comment STRING | Sets the comment associated with the share.
-max_conn INTEGER | Sets the maximum number of connections that are permitted for the share. A value of -1 indicates that there is not limit.
-secd SECD | Sets the security descriptor attached to the share.

COPYRIGHT

Copyright © 2003-2009 Ashok P. Nadkarni


Users and Groups - User and group account management commands

Users and Groups

Commands related to user and group accounts

SYNOPSIS

package require twapi

add_account_rights ACCOUNTNAME RIGHTS ?-system SYSTEMNAME?
add_user_to_global_group GROUPNAME USERNAME ?-system SYSTEMNAME?
add_member_to_local_group GROUPNAME ACCOUNTNAME ?-system SYSTEMNAME?
delete_global_group GROUPNAME ?-system SYSTEMNAME?
delete_local_group GROUPNAME ?-system SYSTEMNAME?
delete_user USERNAME ?-system SYSTEMNAME?
disable_user USERNAME ?-system SYSTEMNAME?
enable_user USERNAME ?-system SYSTEMNAME?
find_accounts_with_right RIGHT ?-system SYSTEMNAME? ?-name?
get_account_rights ACCOUNTNAME ?-system SYSTEMNAME?
get_global_group_info GROUPNAME ?options?
get_global_group_members GROUPNAME ?-system SYSTEMNAME?
get_global_groups ?-system SYSTEMNAME?
get_local_group_info GROUPNAME ?options?
get_local_group_members GROUPNAME ?-system SYSTEMNAME?
get_local_groups ?-system SYSTEMNAME?
get_user_account_info ACCOUNT ?-system SYSTEMNAME? ?options?
get_user_local_groups_recursive ACCOUNT ?-system SYSTEMNAME?
get_users ?-system SYSTEMNAME?
lookup_account_name name ?options?
lookup_account_sid sid ?options?
map_account_to_name ACCOUNT ?-system SYSTEMNAME?
map_account_to_sid ACCOUNT ?-system SYSTEMNAME?
new_global_group GROUPNAME ?-system SYSTEMNAME? ?-comment COMMENT?
new_local_group GROUPNAME ?-system SYSTEMNAME? ?-comment COMMENT?
new_user USERNAME ?options?
remove_member_from_local_group GROUPNAME ACCOUNTNAME ?-system SYSTEMNAME?
remove_account_rights ACCOUNTNAME RIGHTS ?-system SYSTEMNAME?
remove_user_from_global_group GROUPNAME USERNAME ?-system SYSTEMNAME?
set_user_account_info account ?-system SYSTEMNAME? ?options?
set_user_comment USERNAME STRING ?-system SYSTEMNAME?
set_user_country_code USERNAME INTEGER ?-system SYSTEMNAME?
set_user_expiration USERNAME DATETIME ?-system SYSTEMNAME?
set_user_full_name USERNAME STRING ?-system SYSTEMNAME?
set_user_home_dir USERNAME PATH ?-system SYSTEMNAME?
set_user_home_dir_drive USERNAME DRIVEPATH ?-system SYSTEMNAME?
set_user_name USERNAME NEWNAME ?-system SYSTEMNAME?
set_user_password USERNAME PASSWORD ?-system SYSTEMNAME?
set_user_priv_level USERNAME PRIVLEVEL ?-system SYSTEMNAME?
set_user_profile USERNAME PATH ?-system SYSTEMNAME?
set_user_script_path USERNAME PATH ?-system SYSTEMNAME?
unlock_user USERNAME ?-system SYSTEMNAME?

DESCRIPTION

This module provides procedures related to management of user and group accounts on Windows operating systems.

Standard Options

Most commands allow the following options to be specified:

-system SYSTEMNAME Several commands, for example, looking up account names or adding users, may be carried out on a target system other than the local system. The -system option allows specification of the target system. This option defaults to the local system if unspecified.

User and Group Accounts

The command lookup_account_name, map_account_to_name, lookup_account_sid and map_account_to_sid translate between user and group account names and their SID's. The command is_valid_sid_syntax validates the syntax of an SID.

The commands get_users, get_global_groups and get_local_groups may be used to enumerate users and groups on a system.

The commands new_user and delete_user allow addition and deletion of user accounts. The commands enable_user, disable_user and unlock_user may be used to change the state of a user account. The command get_user_account_info returns various attributes and properties of a user account. These may be modified through the set_user_account_info function or alternatively, modified individually through the following set of functions: set_user_name, set_user_password, set_user_home_dir, set_user_comment, set_user_script_path, set_user_full_name, set_user_country_code, set_user_profile, set_user_home_dir_drive, set_user_priv_level, set_user_expiration.

Information about global and local groups may be retrieved through the get_global_group_info and get_local_group_info commands. New global groups may be created and deleted through the new_global_group and delete_global_group commands. The equivalent commands for local groups are new_local_group and delete_local_group. Users may be added and removed using the commands add_user_to_global_group, add_member_to_local_group, remove_user_from_global and remove_member_from_local_group. The commands get_local_group_members and get_global_group_members allow enumeration of the members of a group. get_user_local_groups_recursive returns information about the local groups in which the user account has direct or indirect membership.

The rights and privileges associated with accounts can be managed through the get_account_rights, find_accounts_with_right, add_account_rights and remove_account_rights commands.

Commands

add_account_rights ACCOUNTNAME RIGHTS ?-system SYSTEMNAME?
Adds the privileges and account rights listed in RIGHTS to the account specified by ACCOUNTNAME. The option -system may be used to specify a system as described in Standard Options.

RIGHTS is a list of privileges and account rights. Refer to Authorization constants in the Windows SDK for valid values. Note: you must use the string form of the privilege or right, for example, SeBatchLogon, not SE_BATCH_LOGON_NAME.
add_user_to_global_group GROUPNAME USERNAME ?-system SYSTEMNAME?
Adds the user account specified by USERNAME to the global group GROUPNAME. The option -system may be used to specify a system as described in Standard Options.
add_member_to_local_group GROUPNAME ACCOUNTNAME ?-system SYSTEMNAME?
Adds the account specified by ACCOUNTNAME to the local group GROUPNAME. ACCOUNTNAME may be either a user name or a global group and may include a domain in the form domainname\username.

The option -system may be used to specify a system as described in Standard Options.

Example: Add a user to a local group
delete_global_group GROUPNAME ?-system SYSTEMNAME?
Deletes a global group GROUPNAME. Also, deletes any rights associated with the account in the LSA rights database. The option -system may be used to specify a system as described in Standard Options.
delete_local_group GROUPNAME ?-system SYSTEMNAME?
Deletes a local group GROUPNAME. Also, deletes any rights associated with the account in the LSA rights database. The option -system may be used to specify a system as described in Standard Options.

Example: Delete a local group
delete_user USERNAME ?-system SYSTEMNAME?
Delete the specified user account. Also, deletes any rights associated with the account in the LSA rights database. The option -system may be used to specify a system as described in Standard Options.

Example: Delete a user account
disable_user USERNAME ?-system SYSTEMNAME?
Disables a user account. The option -system may be used to specify a system as described in Standard Options.
enable_user USERNAME ?-system SYSTEMNAME?
Enables a user account. The option -system may be used to specify a system as described in Standard Options.
find_accounts_with_right RIGHT ?-system SYSTEMNAME? ?-name?
Returns a list of all accounts (user and group) that hold the right or privilege specified by RIGHT. The returned list contains the SID's of the account unless the -name option is specified in which case the account names are returned instead.

Refer to Authorization constants in the Windows SDK for valid values for RIGHT. Note: you must use the string form of the privilege or right, for example, SeBatchLogon, not SE_BATCH_LOGON_NAME.

The option -system may be used to specify a system as described in Standard Options.
get_account_rights ACCOUNTNAME ?-system SYSTEMNAME?
Returns the list of rights and privileges for the user or group specified by ACCOUNTNAME. This only includes those directly belonging to the account, and does not include the ones inherited from membership in groups.

The option -system may be used to specify a system as described in Standard Options.
get_global_group_info GROUPNAME ?options?
Retrieves information about the specified global group. The actual information returned depends on the specified options and is returned as a list of the form "option value...". The following options may be specified:

-all | Returns all data items.
-comment | Returns the comment associated with the group account.
-name | Returns the name of the group.
-sid | Returns the SID for the group.
-members | Returns the members of the group.

get_global_group_members GROUPNAME ?-system SYSTEMNAME?
Returns a list of user accounts that are members of the global group GROUPNAME. The option -system may be used to specify a system as described in Standard Options.
get_global_groups ?-system SYSTEMNAME?
Returns the list of global groups on the system. See Standard Options for description of the -system option.

Example: List the users in a group
get_local_group_info GROUPNAME ?options?
Retrieves information about the specified local group. The actual information returned depends on the specified options and is returned as a list of the form "option value...". The following options may be specified:

-all | Returns all data items.
-comment | Returns the comment associated with the group account.
-name | Returns the name of the group.
-sid | Returns the SID for the group.
-members | Returns the members of the group.

get_local_group_members GROUPNAME ?-system SYSTEMNAME?
Returns a list of user accounts that are members of the local group GROUPNAME. The option -system may be used to specify a system as described in Standard Options.

Example: List the users in a group
get_local_groups ?-system SYSTEMNAME?
Returns the list of local groups on the system. See Standard Options for description of the -system option.
get_user_account_info ACCOUNT ?-system SYSTEMNAME? ?options?
Returns attributes and properties of a user account as a list of the form "option1 value1 ...". ACCOUNT specifies the user account for which the information is to be retrieved. The option -system may be used to specify the system from whose context the account lookup should be performed.

The data returned depends on which of the following options are specified:

-all | Returns all data items.
-comment | Returns the comment associated with the user account.
-password_expired | Returns a value of 1 if the account password has expired, and 0 otherwise.
-full_name | Returns the full name of the user.
-parms | Returns an application specific string.
-sid | Returns the SID of the user.
-units_per_week | Returns an integer indicating the number of equal time units into which a week is divided (see -logon_hours).
-primary_group_id | Returns the the RID (relative id component of a SID) of the primary global group for the account.
-global_groups | Returns the global groups of which the account is a member.
-local_groups | Returns the local groups of which the account is a member. This includes only groups of which the account is directly a member and does not include indirect membership through a global group which is itself a member of a local group. See get_user_local_groups_recursive for a command that will recursively include groups.
-status | Returns one of the values disabled, enabled or locked.
-logon_server | Returns the name of the server to which logon requests are sent.
-country_code | Returns an integer country/region value for the user's preferred language.
-home_dir | Returns the full path to the user's home directory.
-password_age | Returns the number of seconds since the password was last changed for the account.
-home_dir_drive | Returns the drive letter assigned to the user's home directory.
-num_logons | Returns the number of times the user has logged on. In an environment with backup domain controllers, each domain controller maintains this value independently and must be queried (using the -system option) separately. A value of -1 indicates the number is unknown.
-acct_expires | Returns the time in GMT when the account is set to expire. This value may also be never or unknown.
-last_logon | Returns the time in GMT when the user last logged in. This value may also be never or unknown. In an environment with backup domain controllers, each domain controller maintains this value independently and must be queried separately (using the -system option).
-last_logoff | Returns the time in GMT when the user last logged off. This value may also be never or unknown. In an environment with backup domain controllers, each domain controller maintains this value independently and must be queried separately (using the -system option).
-user_id | Returns RID component of the user's SID.
-usr_comment | Returns the user comment for the account.
-bad_pw_count | Returns the number of login attempts for that account that failed because of a bad password. In an environment with backup domain controllers, each domain controller maintains this value independently and must be queried separately (using the -system option).
-code_page | Returns an integer corresponding to the code page for the user's preferred language.
-logon_hours | Returns a bit string of 1's and 0's corresponding to each hour in the week that the user is allowed to log on. Note the week starts based on GMT time, not local time.
-workstations | Returns a comma-separated list of upto eight workstations from which the user can log in.
-name | Returns the name of the account.
-script_path | Returns the full path to the user's logon script.
-priv | Returns one of the values admin, user or guest corresponding to the privilege level for the account.
-profile | Returns the full path to the user's profile.
-max_storage | Returns the maximum amount of disk space the user is allowed to use.
Example: List the group membership for a user

Example: Show user account settings

get_user_local_groups_recursive ACCOUNT ?-system SYSTEMNAME?
Returns the local groups in which the given user account is a member either directly or indirectly by belonging to a global group which is a member of a local group. This differs from the -local_groups option of the get_user_account_info command.

The option -system may be used to specify a system as described in Standard Options.
get_users ?-system SYSTEMNAME?
Returns the list of user accounts on the system. Note the returned list includes only accounts defined on the system, not all accounts that are known to the system. See Standard Options for description of the -system option.

Example: List the user accounts on a system
lookup_account_name name ?options?
name specifies the name of the account and may be fully qualified in the form domain\name.

If no options are specified, this command returns the SID for the account. If one or more options are specified, returns a flat list of the form "option1 value1 ...". The following options may be specified:

-all | Returns all values.
-sid | Returns the SID for the account.
-domain | Returns the domain in which the account was found.
-system | Specifies the name of the system on which the account is to be looked up. If unspecified, the local system is used.
-type | Returns the account type. This may be one of user, group (domain group), domain, alias (system local group), logonid, wellknowngroup, deletedaccount, invalid, unknown, or computer. The logonid type is returned for SID's that identify a logon session.

lookup_account_sid sid ?options?
Argument sid specifies the SID of the account. If no options are specified, this command returns the name for the account. If one or more options are specified, the command returns a flat list of the form "option1 value1 ...". The following options may be specified:

-all | Returns all values.
-name | Returns the name for the account.
-domain | Returns the domain in which the account was found.
-system | Specifies the name of the system on which the account is to be looked up. If unspecified, the local system is used.
-type | Returns the account type. This may be one of user, group (domain group), domain, alias (system local group), wellknowngroup, deletedaccount, invalid, unknown, or computer.

map_account_to_name ACCOUNT ?-system SYSTEMNAME?
Returns the name for an account. If ACCOUNT is a valid account name, it is returned as is. Otherwise, it is assumed to be a SID and the corresponding account name is returned. An exception is raised if neither of these is true. The option -system may be used to specify a system as described in Standard Options.
map_account_to_sid ACCOUNT ?-system SYSTEMNAME?
Returns the SID corresponding to an account. If ACCOUNT is a SID, it is returned as is. Otherwise, it is assumed to be an account name and the corresponding SID is returned. An exception is raised if neither of these is true. The option -system may be used to specify a system as described in Standard Options.
new_global_group GROUPNAME ?-system SYSTEMNAME? ?-comment COMMENT?
Creates a global group GROUPNAME. The option -comment allows a comment to be associated with the group. The option -system may be used to specify a system as described in Standard Options.
new_local_group GROUPNAME ?-system SYSTEMNAME? ?-comment COMMENT?
Creates a local group GROUPNAME. The option -comment allows a comment to be associated with the group. The option -system may be used to specify a system as described in Standard Options.

Example: Create a local group
new_user USERNAME ?options?
Creates a new user account. The following options may be specified to set the account properties:

-system SYSTEMNAME | Indicates the system on which to create the account.
-comment STRING | Sets the comment associated with the account.
-home_dir PATH | Sets the account's home directory path.
-script_path PATH | Sets the path to the logon script for the account.
-priv PRIVLEVEL | Sets the privilege level for the account. PRIVLEVEL should be one of the values admin, user or guest. If unspecified, this defaults to user.
-password STRING | Sets the password for the account.
Example: Create a new user account

remove_member_from_local_group GROUPNAME ACCOUNTNAME ?-system SYSTEMNAME?
Removes the user account or global group specified by ACCOUNTNAME from the local group GROUPNAME. ACCOUNTNAME may be a domain account in the form domainname\username.

The option -system may be used to specify a system as described in Standard Options.

Example: Remove a user from a local group
remove_account_rights ACCOUNTNAME RIGHTS ?-system SYSTEMNAME?
Removes the privileges and account rights listed in RIGHTS from the account specified by ACCOUNTNAME. The option -system may be used to specify a system as described in Standard Options.

RIGHTS is a list of privileges and account rights. Refer to Authorization constants in the Windows SDK for valid values. Note: you must use the string form of the privilege, for example, SeBatchLogon, not SE_BATCH_LOGON_NAME.
remove_user_from_global_group GROUPNAME USERNAME ?-system SYSTEMNAME?
Removes the user account specified by USERNAME from the global group GROUPNAME. The option -system may be used to specify a system as described in Standard Options.
set_user_account_info account ?-system SYSTEMNAME? ?options?
Sets attributes and properties of a user account. account specifies the user account for which the information is to be retrieved. The option -system may be used to specify the system from whose context the account lookup should be performed. The following options may be specified to set various properties of the account:

-comment STRING | Sets the comment associated with the account.
-full_name STRING | Sets the full name of the user.
-country_code INTEGER | Sets the country code associated with the user account.
-home_dir PATH | Sets the account's home directory path.
-home_dir_drive | Sets the account's home directory drive.
-acct_expires DATETIME | Sets the time at which the account will expire. DATETIME may be specified in any format accepted by the clock scan command, or may be the string never to indicate that the account should never expire.
-name STRING | Sets the name field containing the name of the account.
-script_path PATH | Sets the path to the logon script for the account.
-priv PRIVLEVEL | Sets the privilege level for the account. PRIVLEVEL should be one of the values admin, user or guest.
-profile PATH | Sets the path to the account's profile.

set_user_comment USERNAME STRING ?-system SYSTEMNAME?
Sets the comment associated with the specified user account to STRING The option -system may be used to specify a system as described in Standard Options.
set_user_country_code USERNAME INTEGER ?-system SYSTEMNAME?
Sets the country code for the specified user account. The option -system may be used to specify a system as described in Standard Options.
set_user_expiration USERNAME DATETIME ?-system SYSTEMNAME?
Sets the time at which the specified user account expires. DATETIME may be specified in any format accepted by the clock scan command, or may be the string never to indicate that the account should never expire. The option -system may be used to specify a system as described in Standard Options.
set_user_full_name USERNAME STRING ?-system SYSTEMNAME?
Sets the full name for the specified user to STRING. The option -system may be used to specify a system as described in Standard Options.
set_user_home_dir USERNAME PATH ?-system SYSTEMNAME?
Sets the home directory for the specified user account to PATH. The option -system may be used to specify a system as described in Standard Options.
set_user_home_dir_drive USERNAME DRIVEPATH ?-system SYSTEMNAME?
Sets the home directory drive for the specified user account. The option -system may be used to specify a system as described in Standard Options.
set_user_name USERNAME NEWNAME ?-system SYSTEMNAME?
Modifies the name of the specified user account to NEWNAME. The option -system may be used to specify a system as described in Standard Options.
set_user_password USERNAME PASSWORD ?-system SYSTEMNAME?
Sets the password of the specified user account to PASSWORD. The option -system may be used to specify a system as described in Standard Options.
set_user_priv_level USERNAME PRIVLEVEL ?-system SYSTEMNAME?
Sets the privilege level of the specified user account to PRIVLEVEL. PRIVLEVEL should be one of the values admin, user or guest. The option -system may be used to specify a system as described in Standard Options.
set_user_profile USERNAME PATH ?-system SYSTEMNAME?
Sets the location of the profile of the specified user account to PATH. The option -system may be used to specify a system as described in Standard Options.
set_user_script_path USERNAME PATH ?-system SYSTEMNAME?
Sets the path to the login script for the specified user account. The option -system may be used to specify a system as described in Standard Options.
unlock_user USERNAME ?-system SYSTEMNAME?
Unlocks a user account that has been locked out. The option -system may be used to specify a system as described in Standard Options.

COPYRIGHT

Copyright © 2004-2009, Ashok P. Nadkarni


Security and access control - Security commands

Security and access control

Commands related to authentication and access control

SYNOPSIS

package require twapi

append_acl_aces ACL ACELIST
check_enabled_privileges PRIVILEGES ?-any?
close_token token
disable_all_token_privileges token
disable_privileges PRIVLIST
disable_token_privileges token PRIVLIST
enable_privileges PRIVLIST
enable_token_privileges token PRIVLIST
eval_with_privileges SCRIPT PRIVLIST
find_logon_sessions ?options?
get_ace_inheritance ACE
get_ace_rights ACE ?-type RESOURCETYPE? ?-raw?
get_ace_sid ACE
get_ace_text ACE ?-resourcetype RESOURCETYPE?
get_ace_type ACE
get_acl_aces ACL
get_acl_rev ACL
get_current_user ?FORMATOPTION?
get_logon_session_info SESSIONLUID ?options?
get_privilege_description PRIVILEGE
get_resource_security_descriptor RESTYPE NAME ?options?
get_security_descriptor_control SECD
get_security_descriptor_dacl SECD
get_security_descriptor_group SECD
get_security_descriptor_owner SECD
get_security_descriptor_sacl SECD
get_security_descriptor_text SECD ?-resourcetype RESOURCETYPE?
get_token_groups token ?-name?
get_token_groups_and_attrs token
get_token_impersonation_level token
get_token_owner token ?-name?
get_token_primary_group token ?-name?
get_token_privileges token ?-all?
get_token_privileges_and_attrs token
get_token_source token
get_token_statistics token
get_token_type token
get_token_user token ?-name?
impersonate_self IMPERSONATIONLEVEL
impersonate_token TOKEN
impersonate_user USERNAME PASSWORD ?options?
is_valid_luid_syntax LUID
is_valid_sid_syntax sid
map_luid_to_privilege LUID ?-system SYSTEMNAME? ?-mapunknown?
map_privilege_to_luid PRIVILEGE ?-system SYSTEMNAME? ?-mapunknown?
new_ace ACETYPE ACCOUNT ACCESSRIGHTS ?options?
new_acl ?ACELIST?
new_luid
new_security_descriptor ?options?
new_uuid ?-localok?
nil_uuid
open_process_token ?-pid PID? ?-access DESIREDACCESS?
open_thread_token ?-tid TID? ?-access DESIREDACCESS? ?-self BOOLEAN?
open_user_token USERNAME PASSWORD ?options?
prepend_acl_aces ACL ACELIST
reset_thread_token
revert_to_self
set_ace_inheritance ACE ?options?
set_ace_rights ACE ACCESSRIGHTS
set_ace_sid ACE ACCOUNT
set_ace_type ACE ACETYPE
set_acl_aces ACL ACELIST
set_resource_security_descriptor RESTYPE NAME SECD ?options?
set_security_descriptor_dacl SECD ACL
set_security_descriptor_group SECD ACCOUNT
set_security_descriptor_owner SECD ACCOUNT
set_security_descriptor_sacl SECD ACL
set_thread_token TOKEN
sort_aces ACELIST
sort_acl_aces ACL

DESCRIPTION

This module provides procedures related to access control in Windows operating systems.

Unique Identifiers

A Locally Unique Identifier (LUID) is a string generated by the command new_luid that is guaranteed to be unique on that system for that boot session.

A Universally Unique Identifier (UUID) is a string generated by the command new_uuid that is guaranteed to be unique on any system at any time.

In both instances, unique means it will not be generated by some other call to that command.

Access Tokens and Privileges

An access token is associated with a process or a thread and contains various elements that determine the security context for the process or thread.

The commands open_process_token and open_thread_token retrieve the access tokens associated with a process and thread respectively. An access token for a specific user account may be obtained using open_user_token. The returned tokens can be passed to other functions to retrieve or set information for the process or thread's privileges and other security related information. When no longer required, the tokens must be passed to close_token in order to release resources.

The commands get_token_user, get_token_groups, get_token_primary_group, get_token_owner and get_token_group_sids_and_attrs retrieve information related to the user and group accounts associated with a token.

The commands get_token_privileges, check_enabled_token_privileges and get_token_privileges_and_attrs retrieve information related to the privileges associated with a token. The commands enable_token_privileges, disable_token_privileges and disable_all_token_privileges allow manipulation of the same. Similarly, enable_privileges and disable_privileges can be used to enable and disable privileges for the current process. eval_with_privileges evaluates a script after enabling specified privileges.

The command get_privilege_description returns a description of a privilege.

The commands get_token_type and get_token_impersonation_level return information related to impersonation.

get_token_source returns the source of a token. get_token_statistics returns various other pieces of information, such as expiration, memory usage etc.

The commands map_luid_to_privilege and map_privilge_to_luid map LUID's to privilege names. The command is_valid_luid_syntax can be used to check the syntactic validity of a LUID.

Impersonation

Windows allows a thread or process to impersonate a user different from the account in which it was started (given the proper privileges). The functions for impersonation and reverting back are impersonate_token, impersonate_user, impersonate_self, set_thread_token and revert_to_self.

The command get_current_user returns the user account for the thread taking into consideration any ongoing impersonation.

Impersonation may be done at several levels. These levels control the degree to which the impersonator takes on the identity of the impersonated client. The following constants define the different levels:

anonymous | The impersonating process cannot obtain identification information about the client or impersonate it.
identification | The impersonating process cannot impersonate the client (ie. access resources using the client's credentials) but can obtain identity and privilege information about the client. This can be used for controlling access to its own objects (as opposed to operating system resources).
impersonation | The impersonating process can impersonate the client only on the local system. The client credentials cannot be used to access other resources on the network.
delegation | The impersonating process can use the client's credentials for accessing network resources.

Access Rights

Access rights in the Windows API take the form of a bit mask with each bit signifying a specific desired or granted right. Access rights may be specified to TWAPI functions in the form of a single element or list of elements, each of which is an integer or a symbolic constant. The access rights bit mask passed to the underlying function is formed by OR'ing together the individual elements in the list. In the case of a symbolic constant, the access right is mapped to the appropriate bits before being OR'ed with the other elements.

The following symbolic constants define generic access rights that are mapped by each object type into its own specific rights: generic_read, generic_write, generic_execute and generic_all.

The following symbolic constants define access rights that are common to all securable object types: delete, read_control, write_dac, write_owner, synchronize, standard_rights_read, standard_rights_write, standard_rights_execute, standard_rights_required and standard_rights_all. Refer to the Windows SDK for a definition of these access rights.

In addition to the standard rights, specific object types may have other access rights associated with them as described in the following table.

Desktops | desktop_readobjects, desktop_createwindow, desktop_createmenu, desktop_hookcontrol, desktop_journalrecord, desktop_journalplayback, desktop_enumerate, desktop_writeobjects, desktop_switchdesktop.
Events | event_all_access, event_modify_state.
Files | file_all_access, file_generic_read, file_generic_write, file_generic_execute, file_read_data, file_write_data, file_append_data, file_read_ea, file_write_ea, file_execute, file_delete_child, file_read_attributes, file_write_attributes
Mutexes | mutex_all_access, mutex_modify_state
Named pipes | file_all_access, file_read_data, file_write_data, file_create_pipe_instance, file_read_attributes, file_write_attributes
Processes | process_all_access, process_terminate, process_create_thread, process_set_sessionid, process_vm_operation, process_vm_read, process_vm_write, process_dup_handle, process_create_process, process_set_quota, process_set_information, process_query_information, process_suspend_resume
Registry | key_all_access, key_read, key_write, key_execute, key_query_value, key_set_value, key_create_sub_key, key_enumerate_sub_keys, key_notify, key_create_link, key_wow64_32key, key_wow64_64key, key_wow64_res
Semaphores | semaphore_all_access, semaphore_modify_state
Services | service_all_access, service_query_config, service_change_config, service_query_status, service_enumerate_dependents, service_start, service_stop, service_pause_continue, service_interrogate, service_user_defined_control
Threads | thread_all_access, thread_terminate, thread_suspend_resume, thread_get_context, thread_set_context, thread_set_information, thread_query_information, thread_set_thread_token, thread_impersonate, thread_direct_impersonation
Timers | timer_all_access, timer_query_state, timer_modify_state.
Tokens | token_all_access, token_assign_primary, token_duplicate, token_impersonate, token_query, token_query_source, token_adjust_privileges, token_adjust_groups, token_adjust_default, token_adjust_sessionid.
Window stations | winsta_enumdesktops, winsta_readattributes, winsta_accessclipboard, winsta_createdesktop, winsta_writeattributes, winsta_accessglobalatoms, winsta_exitwindows, winsta_enumerate, winsta_readscreen, winsta_all.

Note that some of the symbolic access rights are a combination of other access rights. For example, file_all_access includes all other rights associated with a file object. When an access rights list is returned from a command, it includes both the individual symbolic rights as well as all valid symbols for combined rights.

Access Control Entries

Several functions deal with access control entries (ACE) either directly or as part of the more complex structures. A new ACE may be created through the new_ace command. The structure of an ACE should be treated as opaque and the fields should be manipulated only through the access control entry functions. An access control entry contains the fields described below.

The type of an ACE may be one of the following values: allow, deny, audit, alarm, allow_compound, allow_object, deny_object, audit_object, alarm_object, allow_callback, deny_callback, allow_callback_object, deny_callback_object, audit_callback, alarm_callback, audit_callback_object, alarm_callback_object. Currently, only the allow, deny and audit type ACE's are supported. The type of an ACE may be manipulated through the get_ace_type and set_ace_type commands.

Each ACE has an SID associated with it that indicates the user or group that the ACE applies to. This may be retrieved or set using the get_ace_sid and set_ace_sid functions.

The access rights granted or restricted by an ACE can be manipulated through the get_ace_rights and set_ace_rights functions.

An ACE may be recursively applied to objects within a container. This is controlled through the get_ace_inheritance and set_ace_inheritance commands.

The command sort_aces may be used to sort a list of ACE elements into the order recommended by Windows.

The command get_ace_text returns a textual description of an ACE.

Access Control List

An access control list (ACL) is an ordered list of access control entries that is applied to a resource. The command new_acl creates a new ACL with an optional set of ACE elements.

The commands get_acl_aces and set_acl_aces may be used to retrieve or set the access control entries in the ACL. Alternatively, the commands prepend_acl_aces and append_acl_aces may be used to place additional ACEs in front of or after, respectively, of the current entries in an ACL.

Access control lists are of two types - a discretionary access control list (DACL) controls the operations that may be invoked on a resource based on the identity of the accessor, while a system access control list (SACL) controls the audit events that are generated when the resource is accessed. A SACL should contain only ACE elements of types prefixed with audit while a DACL should only contain ACE elements of other types.

The list of ACE elements in an ACL may be resorted to conform to the Windows recommended order through the sort_acl_aces command.

Security Descriptors

A security descriptor is associated with a resource and ties together various information that controls access to the resource including the SID of the owner of the resource, the SID of the primary group, a discretionary access control list (DACL) and a system access control list (SACL).

A new security descriptor may be created through the command new_security_descriptor.

The commands get_security_descriptor_owner, get_security_descriptor_group, set_security_descriptor_owner and set_security_descriptor_group retrieve and set the owner and group attributes of a security descriptor.

The commands get_security_descriptor_dacl, get_security_descriptor_sacl, set_security_descriptor_dacl and set_security_descriptor_sacl retrieve and set the DACL and SACL fields of a security descriptor. It is important to distinguish between the absence of a DACL (or SACL) in a security descriptor and an empty DACL (or SACL). The former results in everyone being allowed to access the object whereas the latter results in no one being allowed to access the object. When modifying or creating a security descriptor, pass the literal string null to indicate that the security descriptor has no DACL (or SACL). An empty DACL (or SACL) on the other hand is indicated simply by passing an ACL that does not contain any ACEs.

The command get_security_descriptor_control returns the control flags associated with the security descriptor.

Note that not all fields in a security descriptor need to be initialized. For example, to change the owner of a resource, you only need to create a descriptor with the owner field initialized either at creation time or through a subsequent call to set_security_descriptor_owner. Then this can be passed to the appropriate function to set a resource's security with an option indicating that only the owner field should be changed.

The security information associated with each resource type can be retrieved and modified through functions get_resource_security_descriptor and set_resource_security_descriptor.

The command get_security_descriptor_text returns a textual description of a security descriptor.

Logon sessions

A logon session is identified by an LUID and provides the context for a particular instance of an authenticated security principal where the principal may be a user, a computer, a service etc. A single principal, for example a user, may have multiple logon sessions concurrently present at any time. The command find_logon_sessions allows enumeration of logon sessions. The details associated with each can be obtained through the get_logon_session_info command.

Commands

append_acl_aces ACL ACELIST
Appends the list of ACEs in ACELIST to the entries in the given ACL. Returns the modified ACL.
check_enabled_privileges PRIVILEGES ?-any?
Without the -any option, the command returns 1 if the given list of privileges is enabled in the token, and 0 otherwise. If the option -any is specified, the command returns 1 if at least one of the privileges is enabled, and 0 otherwise. PRIVLIST is a list of privilege names or LUIDs.
close_token token
Frees resources associated with an access token.
disable_all_token_privileges token
This command disables all privileges in the token. An error will be raised if the privilege does not exist or cannot be disabled because of lack of rights to the token handle.

The command returns a list of privileges that were modified by the command because they were not previously disabled. This list can be passed to enable_token_privileges to undo the privilege modifications made by this call.
disable_privileges PRIVLIST
This command disables one or more privileges in the current process. PRIVLIST is a list of privileges each of which may be either a symbolic privilege such as SeLoadDriverPrivilege or a LUID corresponding to a privilege.

An error will be raised if the privilege does not exist or cannot be disabled because of lack of rights to the token handle.

The command returns a list of privileges that were modified by the command because they were not previously disabled. This list can be passed to enable_privileges to undo the privilege modifications made by this call.
disable_token_privileges token PRIVLIST
This command disables one or more privileges in the token. PRIVLIST is a list of privileges each of which may be either a symbolic privilege such as SeLoadDriverPrivilege or a LUID corresponding to a privilege.

An error will be raised if the privilege does not exist or cannot be disabled because of lack of rights to the token handle.

The command returns a list of privileges that were modified by the command because they were not previously disabled. This list can be passed to enable_token_privileges to restore the token privileges to their original value.
enable_privileges PRIVLIST
This command enables one or more privileges in the current process. PRIVLIST is a list of privileges each of which may be either a symbolic privilege such as SeLoadDriverPrivilege or a LUID corresponding to a privilege.

An error will be raised if a privilege does not exist or cannot be enabled because of lack of rights to the token handle.

The command returns a list of privileges that were modified by the command because they were not previously enabled. This list can be passed to disable_privileges to undo the privilege modifications made by this call.
enable_token_privileges token PRIVLIST
This command enables one or more privileges in the token. PRIVLIST is a list of privileges each of which may be either a symbolic privilege such as SeLoadDriverPrivilege or a LUID corresponding to a privilege.

An error will be raised if a privilege does not exist or cannot be enabled because of lack of rights to the token handle.

The command returns a list of privileges that were modified by the command because they were not previously enabled. This list can be passed to disable_token_privileges to undo the privilege modifications made by this call.
eval_with_privileges SCRIPT PRIVLIST
The command enables the privileges specified in PRIVLIST, if they were not already enabled, and then evaluates SCRIPT in the caller's context. The command returns the result of SCRIPT after restoring the privileges in effect when the command was called.
find_logon_sessions ?options?
Returns a list of LUID values that identify the logon sessions on the system. By default, all logon sessions are returned. One or more of the following options may be specified to restrict the set of logon sessions that are returned.

-user ACCOUNT | Only returns logon sessions for the specified user. ACCOUNT may be either the account name or the SID for the user.
-type SESSIONTYPELIST | Only returns logon sessions that match one of the specified types. SESSIONTYPELIST is a list of integer logon session types defined in the Windows SDK or the following equivalent tokens: interactive, network, batch, service, proxy, unlockworkstation, networkclear, newcredentials, remoteinteractive, cachedinteractive, cachedremoteinteractive or cachedunlockworkstation.
-tssession TSSESSION | Only returns those logon sessions belonging to the terminal services session identified by TSSESSION.

get_ace_inheritance ACE
Returns a flat list of "option value" pairs that indicate the inheritance characteristics of the ACE. The option elements are -self, -recursecontainers, -recurseobjects and -recurseonelevelonly as described in the documentation for new_ace. In addition, the read-only option -inherited indicates whether the ACE has been inherited from an ancestor or not.
get_ace_rights ACE ?-type RESOURCETYPE? ?-raw?
Returns a list of access rights contained within an ACE. This is a list of symbolic constants and bit masks as described in Access Rights. The option -type may be used to map the access rights to symbolic constants for a specific type of resource. RESOURCETYPE must be one of file, pipe, service, registry, process, thread or token.

If the -raw option is specified, the access rights are returned as a single hex bitmask.
get_ace_sid ACE
Returns the SID of the given ACE.
get_ace_text ACE ?-resourcetype RESOURCETYPE?
Returns a textual description of the specified ACE. The option -resourcetype may be specified to indicate that the ACE is for a particular resource type. RESOURCETYPE must be one of the resource type values defined for the get_ace_rights command. This command is primarily useful for debugging and troubleshooting purposes.
get_ace_type ACE
Returns the type of the given ACE. See Access Control Entries for the possible types.
get_acl_aces ACL
Returns the ordered list of ACE elements in the given ACL.
get_acl_rev ACL
Returns the revision level of an ACL. Note that this is controlled by the ACEs in the ACL and cannot be set directly.
get_current_user ?FORMATOPTION?
Returns the user account for the current thread. If the thread is impersonating, this command returns the account being impersonated. Note this is not the same as the $::env(USERNAME) variable as the latter does not take impersonation into account. By default, the command returns the name of the user account in NT 4.0 SAM-compatible format. One of the following options may be specified to return the name in a different format:

-fullyqualifieddn | Fully qualified Active Directory distinguished name.
-samcompatible | NT 4.0 SAM account name (default).
-display | Active Directory human-friendly display name.
-uniqueid | Active Directory GUID format name. This is NOT the same as the SID.
-canonical | Active Directory canonical format.
-userprincipal | User principal format.
-canonicalex | Active Directory canonical format except that the rightmost / is replaced by a newline.
-serviceprincipal | Generalized service principal name.
-dnsdomain | DNS domain followed by the SAM user name.
-sid | User SID instead of name.

Note that all options except -samcompatible and -sid require that the system be part of a Active Directory domain, else an error is raised that no mapping to that format exists.

get_logon_session_info SESSIONLUID ?options?
Returns details for the logon session identified by SESSIONLUID. The information is returned as a flat list of option value pairs and depends on the specified options:

-all | Returns the values for all options.
-authpackage | Returns the name of the package that authenticated the session.
-dnsdomain | Returns the DNS name for the owner of the logon session. This is always empty on Windows 2000.
-logondomain | Returns the name of the domain used to authenticate the session.
-logonid | Returns the LUID for the session (same as SESSIONLUID).
-logonserver | Returns the name of the server used to authenticate the session. This is always an empty string on Windows 2000.
-logontime | Returns the time session owner logged on.
-type | Returns the logon session type (see find_logon_sessions).
-sid | Returns the SID for the session owner.
-tssession | Returns the terminal session identifier for the logon session.
-user | Returns the user name for the session owner.
-userprincipal | Returns the user principal name for the session owner. This is always an empty string on Windows 2000.

get_privilege_description PRIVILEGE
Returns a string description of the specified privilege.
get_resource_security_descriptor RESTYPE NAME ?options?
Retrieves the security descriptor attached to a operating system resource. RESTYPE specifies the resource type and if option -handle is not specified, must be one of file, service (Windows service), printer, registry, share (Network shares) or kernelobj (kernel objects such as mutexes, semaphores and events). If option -handle is specified, then RESTYPE may also be one of windowstation, directoryservice, directoryserviceall, providerdefined, wmiguid or registrywow6432key.

NAME specifies the name of the resource, for example, the path of a file unless option -handle is specified in which case it is the handle to the resource.

Without any options being specified, the returned security descriptor will contain only the owner, group and DACL fields. The SACL field will not contain valid data. The following options may be specified to control which fields are returned in the security descriptor:

-all | Includes all fields in the security descriptor. This requires the caller to have the SeSecurityPrivilege privilege enabled.
-dacl | Includes the DACL in the returned security descriptor.
-group | Includes the group information in the returned security descriptor.
-owner | Includes the owner information in the returned security descriptor.
-sacl | Includes the SACL in the returned security descriptor. This requires the caller to have the SeSecurityPrivilege privilege enabled.

get_security_descriptor_control SECD
Returns the control flags contained in the given security descriptor SECD. The flags are returned as a list of zero or more tokens from the following: owner_defaulted, group_defaulted, dacl_present, dacl_defaulted, sacl_present, sacl_defaulted, dacl_auto_inherit_req, sacl_auto_inherit_req, dacl_auto_inherited, sacl_auto_inherited, dacl_protected, sacl_protected, rm_control_valid, self_relative. Refer to the Windows Platform SDK for details.
get_security_descriptor_dacl SECD
Returns the DACL contained in the given security descriptor SECD.
get_security_descriptor_group SECD
Returns the group SID for the given security descriptor SECD.
get_security_descriptor_owner SECD
Returns the owner SID for the given security descriptor SECD.
get_security_descriptor_sacl SECD
Returns the SACL contained in the given security descriptor SECD.
get_security_descriptor_text SECD ?-resourcetype RESOURCETYPE?
Returns a textual description of the specified security descriptor SECD. The option -resourcetype may be specified to indicate that the security descriptor is for a particular resource type. RESOURCETYPE must be one of the resource type values defined for the get_ace_rights command. This command is primarily useful for debugging and troubleshooting purposes.
get_token_groups token ?-name?
Returns the list of group SID's for the token. If -name is specified, returns the group names instead of the SID's.
get_token_groups_and_attrs token
Returns the list of group SID's for the token together with the attributes for each group. The returned list is of the form SID ATTRIBUTELIST SID ATTRIBUTELIST... where ATTRIBUTELIST is a list of zero or more of the following attributes: enabled, enabled_by_default, logon_id, mandatory, owner, resource, and use_for_deny_only. Refer to the Windows Platform SDK for details.
get_token_impersonation_level token
Gets the current impersonation level for the token. This may have one of the following values: anonymous, identification, impersonation, or delegation. See Impersonation for details.
get_token_owner token ?-name?
Returns the SID of the entity (user, group, etc.) that will be used as the owner for objects created using this token. If -name is specified, the name of the entity is returned instead of the SID.
get_token_primary_group token ?-name?
Returns the SID of the group that will be used as the primary group for objects created using this token. If -name is specified, the name of the group is returned instead of the SID.
get_token_privileges token ?-all?
Returns the list of enabled privileges in the token. If the option -all is specified, returns a list of two sublists. The first containing the enabled privileges and the second the disabled privileges.
get_token_privileges_and_attrs token
Returns the list of privileges in the token together with the attributes for each. The returned list is of the form PRIVILEGE ATTRIBUTELIST PRIVILEGE ATTRIBUTELIST... where ATTRIBUTELIST is a list of zero or more of the following attributes: enabled, enabled_by_default and used_for_access.
get_token_source token
Returns the source of an access token.
get_token_statistics token
Returns various token statistics as a list of field value pairs. The following fields are returned:

authluid | The LUID for the session represented by the token.
expiration | Expiration time for the token. Windows does not currently support expiration for access tokens.
dynamicavailable | Number of free bytes available for storing default protection and primary group identifier for the token.
dynamiccharged | Number of bytes allocated for storing default protection and primary group identifier for the token.
groupcount | Number of group SID's included in the token.
impersonationlevel | The impersonation level of the token. This value is only valid if the field type has the value impersonation.
luid | An LUID that identifies the instance of the token.
modificationluid | An LUID that changes every time the token is modified.
privilegecount | The number of privileges (including disabled ones) that are included in the token.
type | The type of the token - primary or impersonation.

get_token_type token
Returns the type of the token: either primary, or impersonation.
get_token_user token ?-name?
Returns the SID of the user account associated with the token. If -name is specified, returns the name of the account instead of its SID. Example: Show the user account for each process
impersonate_self IMPERSONATIONLEVEL
Assigns an impersonation token to the current thread based on the security context of the process. The security characteristics of the thread can then be changed (for example by modifying the privileges of its token) without impacting the security context of the remaining threads in the process.

IMPERSONATIONLEVEL may have any of the values allowed for impersonation levels (see Impersonation).
impersonate_token TOKEN
Changes the security context of the calling thread to that of the user account associated with the specified token. TOKEN is a token returned from a command such as open_user_token, open_process_token or open_thread_token.

The caller must be careful that exceptions raised by this command are handled correctly. It should not continue with normal processing as though the security context was changed to that of the token.
impersonate_user USERNAME PASSWORD ?options?
Changes the security context of the calling thread to that of the specified user account. This is essentially a wrapper around open_user_token and impersonate_token. Refer to the documentation of open_user_token for a description of the arguments.

The caller must be careful that exceptions raised by this command are handled correctly. It should not continue with normal processing as though the security context was changed to that of the user account.
is_valid_luid_syntax LUID
Returns if LUID is a syntactically valid LUID, else 0.
is_valid_sid_syntax sid
Returns true or false depending on whether sid is a valid SID or not. Note this only checks the syntax of the SID, not whether it corresponds to a real account.
map_luid_to_privilege LUID ?-system SYSTEMNAME? ?-mapunknown?
Returns the privilege name corresponding to the given LUID. If LUID does not correspond to a system defined privilege, an exception is raised unless the -mapunknown option is specified. In this case, the command will return a string of the form Privilege-LUID. As a special case, if LUID is a privilege name (and not a LUID), returns it as is. The option -system may be used to specify a system as described in Standard Options.
map_privilege_to_luid PRIVILEGE ?-system SYSTEMNAME? ?-mapunknown?
Returns the LUID corresponding to the given privilege name. If PRIVILEGE does not correspond to a system defined privilege name or a constructed privilege name of the form Privilege-LUID, an exception is raised. As a special case, if PRIVILEGE is itself a LUID, it is returned. The option -system may be used to specify a system as described in Standard Options.
new_ace ACETYPE ACCOUNT ACCESSRIGHTS ?options?
Creates and returns a new ACE. ACETYPE is the type of the ACE and should be one of supported values described in Access Control Entries. The user or group that the ACE pertains to is given by ACCOUNT which may be either a name or a SID. ACCESSRIGHTS determines the rights to be granted or denied by the ACE and should be a list of one or more constants described in Access Rights.

The following options may be specified when creating an ACE:

-self BOOLEAN | If the specified value is 1 (default), the ACE applies to the object to which it is attached. If the specified value is 0, then the created ACE does not apply to the object with which it is attached. In this case, it only applies to the descendents of that object as indicated by the other options.
-recursecontainers BOOLEAN | If the specified value is 1, the ACE is also applied to all descendents of the object to which the ACE is attached that are themselves containers. For example, in the case of a file ACE, this would indicate that the ACE also apply to all subdirectories. If 0 (default), the ACE does not apply to descendents that are containers.
-recurseobjects BOOLEAN | If the specified value is 1, the ACE is also applied to all descendents of the object to which the ACE is attached that are not themselves containers. For example, in the case of a file ACE, this would indicate that the ACE also apply to all files under all subdirectories below a directory but not to the subdirectories themselves. If 0 (default), the ACE does not apply to descendents that are not containers.
-recurseonelevelonly BOOLEAN | If the specified value is 0 (default), the -recursecontainers and -recurseobjects options have effect at all levels below the container object to which the ACE is applied. If the value is 1, the ACE is only applied to the immediate children of the container object. This option has no effect if neither -recurseobjects nor -recursecontainers is specified.

new_acl ?ACELIST?
Returns a new ACL initialized. ACELIST may be optionally specified to prepopulate the ACL with a list of ACE elements.
new_luid
Returns a LUID.
new_security_descriptor ?options?
Returns a new security descriptor. The following options may be specified to initialize various fields of the security descriptor:

-owner ACCOUNT | The owner field of the security descriptor is set to the SID for the specified account. ACCOUNT may be the SID itself or the name of the user or group account.
-group ACCOUNT | The primary group field of the security descriptor is set to the SID for the specified account. ACCOUNT may be the SID itself or the name of the group.
-dacl ACL | The DACL field of the security descriptor is set to ACL. If ACL is the string "null", no DACL will be present in the security descriptor.
-sacl ACL | The SACL field of the security descriptor is set to ACL. If ACL is the string "null", no SACL will be present in the security descriptor.

new_uuid ?-localok?
Returns a UUID. If the system does not contain a network card, the operating system may return an error as it cannot guarantee uniqueness across systems. Specifying the -localok option causes this to be ignored and a identifier value to be returned anyways.
nil_uuid
Returns a nil UUID.
open_process_token ?-pid PID? ?-access DESIREDACCESS?
Returns a process token that can passed to other functions for querying and modifying security related data for a process. By default, the current process is assumed. The -pid option may be used to retrieve the token for another process.

By -access option may be used to specify a list of desired access rights. If this option is not specified, access rights default to token_query. See Access Rights for a description of the format of this list and for a description of standard access rights.

In addition, the following symbols may be specified in the list: token_adjust_default, token_adjust_groups, token_adjust_privileges, token_adjust_sessionid, token_assign_primary, token_duplicate, token_execute, token_impersonate, token_query, token_query_source, token_read, token_write and token_all_access. See the documentation of OpenProcessToken in the Windows SDK for a description of each of these.

When no longer required, this token must be passed to close_token.

Example: Show the user account for each process
open_thread_token ?-tid TID? ?-access DESIREDACCESS? ?-self BOOLEAN?
Returns a thread access token that can passed to other functions for querying and modifying security related data for a thread. By default, the current process is assumed. The -pid option may be used to retrieve the token for another process. Note that the command will generate an error if the thread does not have a token. In this case, ::errorCode facility and code are set to WINDOWS and 1008 respectively. The caller can retrieve the process token instead.

The -access option specifies the desired access mode. See open_process_token for more details.

The -self option controls whether the access check is to be made against the security context of the thread or against the security context of the process. If specified as false, the security context of the thread is used, else that of the process.

When no longer required, this token must be passed to close_token.
open_user_token USERNAME PASSWORD ?options?
Returns a token corresponding to a logon session for the USERNAME account. This token may be used for impersonation or starting processes under a different account. When no longer required, this token must be passed to close_token.

USERNAME is the name of the account and may be specified either as just the account name, or in UPN format as user@DNS_domain_name.

The following options may be specified:

-domain DOMAIN | Specifies the domain for the user. This option must not be specified if USERNAME is in UPN format user@DNS_domain_name which includes a domain name. If USERNAME is not in UPN format and -domain is not specified, the account validation is done only using the local account database.
-type LOGONTYPE | Indicates the logon type. LOGONTYPE must be one of batch, interactive, network, network_cleartext, new_credentials, service or unlock. Refer to the Windows SDK documentation of LogonUser for details.
-provider PROVIDER | Selects a logon provider. PROVIDER must be one of winnt50, winnt40 or winnt35. If this option is not specified, the operating system picks the standard (version dependent) logon provider for the system. Specify winnt40 to select the NTLM provider and winnt50 (only valid for Windows 2000 and up) for the negotiate logon provider.

prepend_acl_aces ACL ACELIST
Prepends the list of ACEs in ACELIST to the entries in the given ACL. Returns the modified ACL.
reset_thread_token
Ends the current thread's impersonation state.
revert_to_self
Calling this function will restore the original security context for the process thereby ending any impersonation initiated by prior impersonation commands such as impersonate_user.

Any exceptions raised by this command will result in the process continuing to run in the impersonation context. This is dangerous from a security perspective and the caller should normally immediately exit.
set_ace_inheritance ACE ?options?
Returns a new ACE constructed from ACE with inheritance attributes defined by options. These may be one or more of -self, -recursecontainers, -recurseobjects and -recurseonelevelonly as described in the documentation for new_ace.
set_ace_rights ACE ACCESSRIGHTS
Returns a new ACE containing the access rights specified in ACCESSRIGHTS. This should be a list of symbolic constants and bit masks as described in Access Rights.
set_ace_sid ACE ACCOUNT
Returns a new ACE constructed from ACE but with its SID field set to be the SID for account ACCOUNT. ACCOUNT may be either the name or the SID of a user or group account.
set_ace_type ACE ACETYPE
Returns a new ACE constructed from ACE but with the type ACETYPE. See Access Control Entries for valid values of ACETYPE.
set_acl_aces ACL ACELIST
Sets the list of ACEs within an ACL to those given in ACELIST. Returns the modified ACL.
set_resource_security_descriptor RESTYPE NAME SECD ?options?
Modifies the security descriptor attached to a operating system resource. RESTYPE specifies the resource type and if option -handle is not specified, must be one of file, service (Windows service), printer, registry, share (Network shares) or kernelobj (kernel objects such as mutexes, semaphores and events). If option -handle is specified, then RESTYPE may also be one of windowstation, directoryservice, directoryserviceall, providerdefined, wmiguid or registrywow6432key.

NAME specifies the name of the resource, for example, the path of a file unless option -handle is specified in which case it is the handle to the resource.

The fields of the resource's security descriptor are modified based on the contents of SECD. The specific fields modified depend on the options specified:

-all | All fields in the security descriptor are modified. This requires the caller to have the SeSecurityPrivilege privilege enabled.
-owner | The resource's owner is modified.
-group | The resource's group is modified.
-dacl | Changes the DACL attached to the resource.
-sacl | Changes the SACL attached to the resource. This requires the caller to have the SeSecurityPrivilege privilege enabled.
-protect_dacl | If this option is specified, the resource will not inherit any DACL's from its parent. Otherwise, the parent's DACL's flow down to the resource. This option only has effect if the -dacl option is specified. This option cannot be specified with -unprotect_dacl. If neither is specified, the current DACL inherit settings are preserved.
-protect_sacl | If this option is specified, the resource will not inherit any SACL's from its parent. Otherwise, the parent's SACL's flow down to the resource. This option only has effect if the -sacl option is specified. This option cannot be specified with -unprotect_sacl. If neither is specified, the current SACL inherit settings are preserved.
-unprotect_dacl | If this option is specified, the resource will inherit any DACL's from its parent. This option only has effect if the -dacl option is specified. This option cannot be specified with -protect_dacl. If neither is specified, the current DACL inherit settings are preserved.
-unprotect_sacl | If this option is specified, the resource will inherit any SACL's from its parent. This option only has effect if the -sacl option is specified. This option cannot be specified with -protect_sacl. If neither is specified, the current SACL inherit settings are preserved.

set_security_descriptor_dacl SECD ACL
Returns a security descriptor identical to SECD except for the DACL field which is set to ACL. If ACL is the string "null", the security descriptor is set to have no DACL. If ACL is an empty list, the security descriptor has an empty DACL, which is not the same not having a DACL.
set_security_descriptor_group SECD ACCOUNT
Returns a security descriptor identical to SECD except for the group field which is set to the SID for account ACCOUNT. ACCOUNT may be the SID itself or the name of the group.
set_security_descriptor_owner SECD ACCOUNT
Returns a security descriptor identical to SECD except for the owner field which is set to the SID for account ACCOUNT. ACCOUNT may be the SID itself or the name of the user or group.
set_security_descriptor_sacl SECD ACL
Returns a security descriptor identical to SECD except for the SACL field which is set to ACL. If ACL is the string "null", the security descriptor is set to have no SACL.
set_thread_token TOKEN
Changes the security context of the current thread by associating it with the given token. This is generally used in combination with open_thread_token to implement an impersonation stack.
sort_aces ACELIST
Although not enforced by the operating system, Windows has a recommended order in which multiple ACEs should be applied. The sort_aces command takes a list of ACE elements and returns a list that has been sorted as per the Windows recommendation. This sort order places all inherited ACEs after all non-inherited ACEs. Within each group, deny ACEs are placed before allow ACEs.
sort_acl_aces ACL
Rearranges the ACEs in the given ACL to conform to the Windows recommended order. Returns the modified ACL.

COPYRIGHT

Copyright © 2003-2009, Ashok P. Nadkarni


Cryptographic API - Cryptographic API

Cryptographic API

Commands related to cryptographical operations

SYNOPSIS

package require twapi

sspi_client_new_context CREDENTIALS ?options?
sspi_close_security_context CONTEXT
sspi_decrypt CONTEXT DATA SIGNATURE PADDING ?options?
sspi_encrypt CONTEXT DATA ?options?
sspi_enumerate_packages
sspi_generate_signature CONTEXT DATA ?options?
sspi_get_security_context_features CONTEXT
sspi_get_security_context_sizes CONTEXT
sspi_get_security_context_username CONTEXT
sspi_free_credentials arg CREDENTIALS
sspi_new_credentials ?options?
sspi_security_context_next CONTEXT ?RESPONSE?
sspi_server_new_context CREDENTIALS CLIENTDATA ?options?
sspi_verify_signature CONTEXT DATA SIGNATURE ?options?

DESCRIPTION

This module is still experimental and liable to change.

This package provides procedures related to cryptographic services provided by the Windows platforms.

SSPI overview

The Security Support Provider Interface (SSPI) is a standard interface to various security protocols that provide for security functions such as authentication, encryption and integrity. The SSPI interface allows establishment of a security context that can be used for signing and encrypting data passed between a client and a server.

SSPI security context establishment

On the client side, the application program starts off by retrieving the credentials to be used to authenticate itself to the server by calling sspi_new_credentials with the -outbound option. It then creates a new client security context by calling sspi_client_new_context specifying appropriate desired security characteristics. The application then exchanges messages with the server to complete the authentication.

Depending on the security protocol in use, the authentication between the client and the server may require multiple message exchanges between the client and the server. Once it obtains its security context, the client calls sspi_security_context_next passing it the security context. This command returns an indication of whether the authentication is complete, or more exchanges with the server are required. In the latter case, data returned by the command is sent to the server and the server response is passed back to the command. This sequence is repeated until the command indicates the authentication is complete or generates a Tcl exception indicating authentication failure. The security context generated in this manner can then be used to sign and encrypt messages between the client and the server.

On the server side, the application program starts off by retrieving its own credentials by calling sspi_new_credentials with the -inbound. It then creates a new server security context by calling sspi_server_new_context passing it the authentication data sent by the client. The server then enters the authentication loop described below. From this point on, the server follows the authentication loop calling sspi_security_context_next in the same manner as described above for the client.

Once a security context is established, either on the client or the server, its characteristics, including the negotiated parameters, security principal name etc. can be retrieved through commands sspi_get_security_context_flags, sspi_get_security_context_username and sspi_get_security_context_sizes.

When no longer required, both the server and client ends should free resources associated with their credentials by calling sspi_free_credentials. Similarly, the security context should be released when no longer needed by calling sspi_close_security_context.

SSPI message signing and encryption

Once a security context has been completely created as above, it can then be used to generate and verify messages signatures using sspi_generate_signature and sspi_verify_signature respectively.

Similarly, the security context can be used to encrypt and decrypt messages using sspi_encrypt and sspi_decrypt.

Commands

sspi_client_new_context CREDENTIALS ?options?
Initiates the building of a new client-side, security context from based on the specified credentials. CREDENTIALS is a handle to credentials returned by sspi_new_credentials. The returned value, which is a handle to a security context, should be treated as opaque by the caller and used as described in SSPI security context establishment.

The options below specify the requirements for the context. Note that not all security providers support all options or combinations of options. Refer to the Windows SDK for more information about these options.

-confidentiality BOOL | If specified as true, messages are to be encrypted.
-connection BOOL | If specified as true, the security context will not handle formatting of messages.
-datarep DATAREP | Specifies the data representation on the target. DATAREP must be either network (default) or native.
-delegate BOOL | If specified as true, the server can use the context to other servers as the client. Requires -mutualauth to also be specified as true.
-extendederror BOOL | When true, the remote end is notified of errors.
-integrity BOOL | If specified as true, messages are to be signed.
-mutualauth BOOL | If specified as true, both the client and server are to be authenticated.
-replaydetect BOOL | If specified as true, detection of replayed messages is desired.
-sequencedetect BOOL | If specified as true, detection of out-of-sequence messages is desired.
-stream BOOL | If specified as true, indicates a stream oriented connection.
-target TARGET | Specifies the target of the security context. The format depends on the security service provider.
-usesessionkey BOOL | If specified as true, a new session key must be negotiated.

When a security context is no longer required, it should be released by calling sspi_close_security_context.

sspi_close_security_context CONTEXT
Closes a security context constructed through sspi_client_new_context or sspi_server_new_context or and frees any associated resources.
sspi_decrypt CONTEXT DATA SIGNATURE PADDING ?options?
TBD
sspi_encrypt CONTEXT DATA ?options?
TBD
sspi_enumerate_packages
Returns a list of the names of the security provider packages available on the system.
sspi_generate_signature CONTEXT DATA ?options?
TBD
sspi_get_security_context_features CONTEXT
After a security context is established, this command may be used to retrieve information about what security features were negotiated. The command returns a keyed list with boolean values for the following fields.

-confidentiality | If true, encryption is supported.
-connection | If true, the security context will not handle formatting of messages.
-delegate | If true, the server can use the context to other servers as the client.
-extendederror | If true, the remote end is notified of errors.
-integrity | If true, messages signing is supported.
-mutualauth | If true, both the client and server are authenticated.
-replaydetect | If true, detection of replayed messages is enabled.
-sequencedetect | If true, detection of out-of-sequence messages is enabled.
-stream | If true, indicates a stream oriented connection.

sspi_get_security_context_sizes CONTEXT
Returns a keyed list with the following fields:

-maxtoken | Maximum size of token used in the authentication exchange.
-maxsig | Maximum size of signature.
-blocksize | Messages should preferably be a multiple of this value.
-trailersize | Size of security trailer to be appended to messages.

sspi_get_security_context_username CONTEXT
TBD
sspi_free_credentials arg CREDENTIALS
Frees resources associated with credentials returned by sspi_new_credentials.
sspi_new_credentials ?options?
Returns credentials that can be used to negotiate and establish a security context. The command returns a handle to the credentials unless the -getexpiration option is specified in which case it returns a keyed list with two fields: -handle which is the handle to the credentials, and -expiration which returns the time (as number of 100ns intervals since January 1, 1601) at which the credentials expire.

The following options may be specified with the command:

-domain DOMAIN | Specifies the domain to which the user account belongs. Not all security providers support this. By default, the user account for the current process is used.
-getexpiration | If specified, the expiration time for the returned credentials is also returned. See description of command return value above.
-package SECURITYPACKAGE | Specifies the security package with which the credentials are to be used. By default, this is NTLM. The list of available security packages on a system can be obtained through sspi_enumerate_packages.
-password PASSWORD | Specifies the password for retrieving credentials to the user account specified by the -user option.
-principal.arg PRINCIPAL | Specifies the name of the principal whose credentials are to be referenced. By default, this is the user account under which the process is running.
-usage DIRECTION | Indicates how the credentials will be used, based on DIRECTION - inbound, outbound or both (default).
-user USERNAME | Specifies the name of the user account. Not all security providers support this. By default, the user account for the current process is used.

The returned credentials must be freed by calling sspi_free_credentials when no longer needed.

sspi_security_context_next CONTEXT ?RESPONSE?
Depending on the security provider in use, building a security context may require negotiation with multiple message exchanges between the client and server. This command indicates to the caller whether the negotiation is complete or additional exchange is required. See SSPI security context establishment for an overview of this process.

CONTEXT contains the security context being built. This is the return value from sspi_client_new_context, sspi_server_new_context or from a previous call to sspi_security_context_next.

The command returns a list containing three elements. The first element is either done, indicating that building of the security context was successfully completed, or continue, indicating that additional negotiation is required. In both cases, if the second element of the returned list is not an empty string, it contains data to be sent to the remote end to either complete or continue the negotiation. The application should keep calling sspi_security_context_next until it returns done as the first element of the returned list. Finally, the third element of the returned list contains the updated context. Callers should pass this in as CONTEXT in the next call to the command.

The command will raise a Tcl exception if the security context negotiation fails for any reason, including authentication failures.
sspi_server_new_context CREDENTIALS CLIENTDATA ?options?
Initiates the building of a new server-side, security context from based on the specified credentials and security data received from the client. CREDENTIALS is a handle to credentials returned by sspi_new_credentials. The returned value, which is a handle to a security context, should be treated as opaque by the caller and used as described in SSPI security context establishment.

The options below specify the requirements for the context. Note that not all security providers support all options or combinations of options. Refer to the Windows SDK for more information about these options.

-confidentiality BOOL | If specified as true, messages are to be encrypted.
-connection BOOL | If specified as true, the security context will not handle formatting of messages.
-datarep DATAREP | Specifies the data representation on the target. DATAREP must be either network (default) or native.
-delegate BOOL | If specified as true, the server can use the context to other servers as the client. Requires -mutualauth to also be specified as true.
-extendederror BOOL | When true, the remote end is notified of errors.
-integrity BOOL | If specified as true, messages are to be signed.
-mutualauth BOOL | If specified as true, both the client and server are to be authenticated.
-replaydetect BOOL | If specified as true, detection of replayed messages is desired.
-sequencedetect BOOL | If specified as true, detection of out-of-sequence messages is desired.
-stream BOOL | If specified as true, indicates a stream oriented connection.

When a security context is no longer required, it should be released by calling sspi_close_security_context.

sspi_verify_signature CONTEXT DATA SIGNATURE ?options?
TBD

COPYRIGHT

Copyright © 2007-2009 Ashok P. Nadkarni


Event log - Event Log

Event log

Commands relating to reading and writing the Windows event log

SYNOPSIS

package require twapi

eventlog_backup EVENTLOGHANDLE FILENAME
eventlog_clear EVENTLOGHANDLE ?-backup FILENAME?
eventlog_close EVENTLOGHANDLE
eventlog_count EVENTLOGHANDLE
eventlog_format_category EVENT_RECORD ?options?
eventlog_format_message EVENT_RECORD ?options?
eventlog_is_full EVENTLOGHANDLE
eventlog_log MESSAGE ?options?
eventlog_oldest EVENTLOGHANDLE
eventlog_open ?options?
eventlog_read EVENTLOGHANDLE ?options?
eventlog_write EVENTLOGHANDLE EVENTID ?options?

DESCRIPTION

This module provides commands for reading and writing the Windows event log.

Overview

Most access to the event log requires a handle returned by the eventlog_open command. A handle allows either read or write access, but never both. Events can be written using the eventlog_write command. The eventlog_log command provides an alternate, simpler but less flexible, interface for writing events. Events can be read from an event log through the eventlog_read command. The returned event record can be formatted using eventlog_format_message and eventlog_format_category.

Event logs can be backed up using eventlog_backup or as a side effect of clearing the log through eventlog_clear. The backup file can be read using the standard eventlog_open and eventlog_read commands.

The command eventlog_count returns the number of records in the event log. eventlog_oldest returns the record number of the oldest record. The command eventlog_is_full indicates whether the event log is full.

Commands

eventlog_backup EVENTLOGHANDLE FILENAME
Backs up the specified event log to the file FILENAME. The file may be opened for reading using the eventlog_open command. EVENTLOGHANDLE must be a read handle.
eventlog_clear EVENTLOGHANDLE ?-backup FILENAME?
Clears the specified event log. If the -backup option is specified, the event log is first backed to the file FILENAME. EVENTLOGHANDLE must be a read handle (even though the command actually modifies the event log).
eventlog_close EVENTLOGHANDLE
Closes a handle previously returned by eventlog_open and frees any associated resources.
eventlog_count EVENTLOGHANDLE
Returns the number of records in the specified event log. EVENTLOGHANDLE must be a read handle.
eventlog_format_category EVENT_RECORD ?options?
Returns the text corresponding to the numeric category field in EVENT_RECORD by looking up the appropriate resources. EVENT_RECORD must be an element of the event record list returned from the eventlog_read command.

The following options may be specified with the command:

-langid LANGID | Passed to the format_message command for formatting. See the description of that function for details.
-width MAXLINEWIDTH | Passed to the format_message command for formatting. See the description of that function for details.

eventlog_format_message EVENT_RECORD ?options?
Returns the text corresponding to the message in EVENT_RECORD by looking up the appropriate resources. EVENT_RECORD must be an element of the event record list returned from the eventlog_read command.

The following options may be specified with the command:

-langid LANGID | Passed to the format_message command for formatting. See the description of that function for details.
-width MAXLINEWIDTH | Passed to the format_message command for formatting. See the description of that function for details.

eventlog_is_full EVENTLOGHANDLE
Returns 1 if the specified event log is full, and 0 otherwise. EVENTLOGHANDLE may be either a read or a write handle.
eventlog_log MESSAGE ?options?
Writes a record into the specified event log. This is a wrapper around eventlog_open, eventlog_write, eventlog_close for simple logging needs and should be used for applications that do not have a message file.

The following options may be specified to control the values of the various fields in the event log record:

-system SYSTEMNAME | Specifies the system on which the event log resides. By default, this is the local system.
-source SOURCENAME | Specifies a event log source. The returned handle will refer to the event log to which events from SOURCENAME are logged. This defaults to the filename portion (without the path or extension) of the executable file.
-type EVENTTYPE | Indicates the type or severity of the event. EVENTTYPE should be one of success, error, warning, information (default), auditsuccess or auditfailure.
-category CATEGORY | This should be a integer corresponding to a category id in the event source's category or message file. This value defaults to 1.

eventlog_oldest EVENTLOGHANDLE
Returns the record number of the oldest record in the specified event log. EVENTLOGHANDLE must be a read handle.
eventlog_open ?options?
Returns a handle to the specified event log. When no longer required, it should be closed by passing it to eventlog_close. Various options specify the event log to be opened and the read-write mode.

-system SYSTEMNAME | Specifies the system on which the event log resides. By default, this is the local system.
-source SOURCENAME | Specifies a event log source. The returned handle will refer to the event log to which events from SOURCENAME are logged. This defaults to the filename portion (without the path or extension) of the executable file. This option may not be used with the -file option.
-file EVENTLOGBACKUPFILE | Specifies the name of a backed up event log file. This option may not be used with the -source or -file options.
-write | Returns a handle used for writing to the event log. By default, a read handle is returned. Note that event log handles are never read-write. Applications wishing to do both need to open two separate handles. This option may not be used with the -file option as event log backup files cannot be written to.

eventlog_read EVENTLOGHANDLE ?options?
Returns a list of event records read from the specified event log. EVENTLOGHANDLE must be a read handle. The number of records returned may vary depending on the number of records in the event log as well as internal buffering limits. Returns an empty list when no more records can be read. Each eventlog_read command moves the event log read pointer.

The following options may be specified to control the read operation:

-seek RECORDNUMBER | Normally the command returns event log records starting from current read pointer. If this option is specified, the command will return records starting with the one with record number RECORDNUMBER.
-direction backward|forward | Controls the direction in which the read pointer moves. By default, the commands will return records reading forwards from the current read pointer.
Each element in the returned list corresponds to an event log record and is a list of the form field value .... The following fields are returned in each event record:

-category | This is an integer corresponding to a category id in the event source's category or message file.
-data | Raw binary data stored as part of the event record.
-eventid | The event id that identifies the event type. See eventlog_write for how this may be used.
-params | A list of strings corresponding to the positional %N format specifiers in the format string for the event in the message file.
-sid | The SID of the user account of the thread that logged the event. This may be a null string if this information was not included in the record.
-recordnum | The record number for this record. This may be used with the -seek option to locate a record.
-source | The event source that logged the event.
-system | The name of the system on which the event was generated.
-timegenerated | Contains the time that the event was generated (UTC) expressed as an offset in seconds since 00:00:00 Jan 1, 1970. This can be passed to the clock format command to convert to an absolute time.
-timewritten | Contains the time (UTC) that the event was written into the event log expressed as an offset in seconds since 00:00:00 Jan 1, 1970. This can be passed to the clock format command to convert to an absolute time.
-type | Indicates the type or severity of the event. The value is one of success, error, warning, information, auditsuccess or auditfailure.

eventlog_write EVENTLOGHANDLE EVENTID ?options?
Writes a record into the specified event log. EVENTLOGHANDLE must be a write handle for an event log. EVENTID is a integer that identifies the specific event. If the event source is configured in the registry, this is the message id for the event in the message file for the source. If no message file has been configured, this event id is irrelevant.

The following options may be specified to control the values of the various fields in the event log record:

-type EVENTTYPE | Indicates the type or severity of the event. EVENTTYPE should be one of success, error, warning, information (default), auditsuccess or auditfailure. Note that the last two may only be used when writing to the Security event log.
-category CATEGORY | This should be a integer corresponding to a category id in the event source's category or message file. This value defaults to 1.
-loguser | Specifying this will cause the SID of the user account for this thread to be included in the event record.
-params PARAMLIST | Specifies a list of strings corresponding to the positional %N format specifiers in the format string for the event in the message file. If the source has not been configured with a message file in the registry, event viewers will generally display this as a list of strings.
-data DATA | Raw binary data that should be stored as part of the event record.

COPYRIGHT

Copyright © 2004, Ashok P. Nadkarni


Windows INI file - Windows INI files

Windows INI file

Commands for accessing Windows INI files

SYNOPSIS

package require twapi

delete_inifile_key SECTION KEY ?-inifile FILENAME?
delete_inifile_section SECTION ?-inifile FILENAME?
read_inifile_key SECTION KEY ?options?
read_inifile_section SECTION ?-inifile FILENAME?
read_inifile_section_names ?-inifile FILENAME?
write_inifile_key SECTION KEY VALUE ?-inifile FILENAME?

DESCRIPTION

This module provides commands to access Windows INI files

Overview

These commands are wrappers to the Windows functions that provide access to INI files such as GetPrivateProfileString.

The commands read_inifile_key, write_inifile_key and delete_inifile_key can be used for manipulating individual entries.

The commands read_inifile_section_names, read_inifile_section and delete_inifile_section may be used for manipulating entire sections of INI files.

Note these commands take into account INI file mappings set up in the HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\IniFileMapping registry key.

A cross-platform package that provides similar functionality is available in the available in the tcllib standard library. However, that does not take into account the registry mappings on Windows platforms.

Commands

delete_inifile_key SECTION KEY ?-inifile FILENAME?
Deletes the key KEY from the INI file section SECTION. By default, the command writes to the win.ini file in the system directory. The -inifile option may be used to specify different INI file.
delete_inifile_section SECTION ?-inifile FILENAME?
Deletes the entire section SECTION from an INI file. By default, the command writes to the win.ini file in the system directory. The -inifile option may be used to specify a different INI file.
read_inifile_key SECTION KEY ?options?
Returns the value of the key KEY in the INI file section SECTION. If the key is not found, an empty string is returned unless the -default option is specified. The following options may be specified:

-default DEFAULTVALUE | If the key is not found in the section, the command returns DEFAULTVALUE instead of an empty string.
-inifile FILENAME | By default, the command looks up the win.ini file in the system directory. This option may be used to look up a different INI file instead.

read_inifile_section SECTION ?-inifile FILENAME?
Returns all the entries in section SECTION of an INI file as a list of key value pairs. By default, the command reads the win.ini file in the system directory. The -inifile option may be used to specify a different INI file.
read_inifile_section_names ?-inifile FILENAME?
Returns the names of all sections in an INI file. By default, the command reads the win.ini file in the system directory. The -inifile option may be used to specify a different INI file.
write_inifile_key SECTION KEY VALUE ?-inifile FILENAME?
Writes VALUE as the value of the key KEY in the INI file section SECTION. The section and key are created if they did not already exist. By default, the command writes to the win.ini file in the system directory. The -inifile option may be used to look up a different INI file instead.

COPYRIGHT

Copyright © 2004, Ashok P. Nadkarni


Console - Windows console mode

Console

Commands related to Windows consoles

SYNOPSIS

package require twapi

allocate_console
clear_console CONOUTH ?-fillchar CHARACTER? ?-windowonly BOOL?
console_read CONINH ?options?
create_console_screen_buffer ?options?
fill_console CONOUTH ?options?
flush_console_input CONINH
free_console
generate_console_control_event EVENT ?PROCESSGROUP?
get_console_handle TYPE
get_console_input_codepage
get_console_input_mode ?CONINH?
get_console_output_mode ?CONOUTH?
get_console_pending_input_count CONINH
get_console_screen_buffer_info CONH ?options?
get_console_title
get_console_window
get_console_window_maxsize
get_standard_handle TYPE
modify_console_input_mode CONINH MODEOPTIONS...
modify_console_output_mode CONOUTH MODEOPTIONS...
num_console_mouse_buttons
set_console_active_screen_buffer CONOUTH
set_console_control_handler SCRIPT
set_console_cursor_position CONOUTH X Y
set_console_default_attr CONOUTH ?options?
set_console_input_codepage CODEPAGE
set_console_input_mode CONINH MODEOPTIONS...
set_console_output_codepage CODEPAGE
set_console_output_mode CONOUTH MODEOPTIONS...
set_console_screen_buffer_size CONOUTH SCRSIZE
set_console_title TEXT
set_console_window_location CONOUTH RECT ?-absolute BOOL?
set_standard_handle TYPE HANDLE
write_console CONOUTH STRING ?options?

DESCRIPTION

This module provides commands for manipulating console windows.

Consoles

A console may have multiple processes attached to it. However, a process may be attached to at most one console. Character mode applications are generally started with a console attached. GUI mode processes however do not have a console attached. The command allocate_console may be used to allocate and attach to a console. An allocated console may be released with the free_console command.

Console Handles

The input and screen buffers for a console are identified by handles that can be retrieved through the get_console_handle call. Alternately, the the strings stdin, stdout and stderr may be passed to the various console commands to identify the input, output and error handles. The standard input, output and error handles may be retrieved through the get_standard_handle calls. These may not refer to the console if standard input/output has been redirected.

Console Input

A console is associated with an input buffer that contains input events such as keyboard and mouse inputs. The console can be read through the console_read command. The number of events in the input buffer can be obtained through get_console_pending_input_count and any pending events can be flushed through flush_console_input.

Console input is associated with a specific code page that can be retrieved and set through the get_console_input_codepage and set_console_input_codepage commands.

A console control event may be generated with the generate_console_control_event command. Console control event handlers may be set up with the set_console_control_handler command.

The number of mouse buttons available through the console interface is returned by the num_console_mouse_buttons command.

Console Output

A console may have one or more screen buffers only one of which is active and visible at a time. A screen buffer is a two dimensional array of cells with each cell containing a character and an attribute that controls how the character is displayed. Screen buffers can be written to with the write_console command. The code page used for output can be retrieved and set through the get_console_output_codepage and set_console_output_codepage commands.

Screen buffers can be allocated through create_console_screen_buffer and made to be the active buffer by calling set_console_active_screen_buffer. The size of the buffer can be controlled through the set_console_screen_buffer_size command.

The console window is the portion of the screen buffer that is actually visible on the display. The command set_console_window_location can be used to control the location of this window into the screen buffer. The window handle of the console window can be obtained through the get_console_window command. The maximum possible size of the window that can fit on the display given the font can be obtained through get_console_window_maxsize. The title associated with a console window may be retrieved and set through the get_console_title and set_console_title respectively.

The command clear_console clears the screen buffer or a portion of it and can optionally fill it with a specific character.

Characteristics of the screen buffer such as buffer size, cursor position, window coordinates can be obtained through get_console_screen_buffer_info.

Console Modes

A console's input and output modes control how characters are handled when when entered and displayed.

Characters typed into a console window may be handled differently based on the input mode of the console. The commands get_console_input_mode, set_console_input_mode and modify_console_input_mode allow retrieval and setting of the input mode. The various mode settings are specified as arguments to these functions and may contain zero or more of the following elements:

-autoposition BOOL | If true, position of console windows is determined by the operating system when the windows are opened.
-echoinput BOOL | If true, characters are echoed as they are read in. This is only valid if the -lineinput mode is true.
-extendedmode BOOL | Must be set if -quickeditmode or -insertmode are specified.
-insertmode BOOL | If true, characters are inserted as they entered and do not overwrite the characters at the current cursor position.
-lineinput BOOL | If true, calls to read input only return when a carriage return character is read.
-mouseinput BOOL | If true, mouse events are placed in the input queue when the console window has focus and the mouse is within the window coordinates.
-processedinput BOOL | If true, control characters are handled by the system and not placed in the input queue. If -lineinput is also true, carriage returns, line feeds and tabs are also handled by the system.
-quickeditmode BOOL | If true, allows the user to use the mouse to select and edit text.
-windowinput BOOL | If true, changes in the console window coordinates are reported through the input queue.
In a similar fashion, the characters written to a screen buffer may be displayed differently depending on the output mode of the console. The commands get_console_output_mode, set_console_output_mode and modify_console_output_mode allow retrieval and setting of the input mode. The various mode settings are specified as arguments to these functions and may contain zero or more of the following elements:

-processedoutput BOOL | If true, characters written to the screen buffer are processed for ASCII control characters - backspace, tab, bell, carriage return, linefeed - and appropriate action taken.
-wrapoutput BOOL | If true, characters written to the screen buffer will wrap around to the next row when the end of row is reached. Otherwise, the last character in the row will be overwritten with characters that extend beyond the width of the row.

Text Attributes

Each cell in a screen buffer has attributes that control the display characteristics of that cell. The default attribute used for writing to the screen buffer can be set through set_console_default_attr.

Text attributes are retrieved and controlled through the following options:

-bgCOLOR BOOL | If true, adds COLOR to the background text color. COLOR may be one of blue, green, red, purple, yellow, gray, or white.
-fgCOLOR BOOL | If true, adds COLOR to the foreground text color. COLOR may be one of blue, green, red, purple, yellow, gray, or white.
-fgbright BOOL | If true, intensifies the foreground color.
-bgbright BOOL | If true, intensifies the background color.
The command fill_console can be used to change the attribute of portions of the screen buffer.

Commands

allocate_console
Allocates a console for the process. If the process already has a console, an error exception is generated.
clear_console CONOUTH ?-fillchar CHARACTER? ?-windowonly BOOL?
If no option are specified, sets the contents of the entire screen buffer to spaces. The -fillchar option may be used to specify a different character to use. If -windowonly is specified as true, only the portion of screen buffer that is visible is cleared.
console_read CONINH ?options?
Reads input from the console. Note that the input is from the console even if standard input has been redirected. options specify the input mode to use and are passed to modify_console_input_mode before input is read. The original mode is restored before returning.
create_console_screen_buffer ?options?
Creates a new console screen buffer and returns a handle to it. The following options may be specified:

-inherit BOOL | If true, the returned handle is inheritable by child processes.
-mode read|write|readwrite | Specifies whether the buffer access is read, write or both.
-secd SECURITY_DESCRIPTOR | Specifies a security descriptor to be attached to the screen buffer.
-share none|read|write|readwrite | Specifies whether the buffer is not shared or can be shared for read, write or both (default).
The allocated screen buffer handle should be closed by calling close_handles when no longer needed.

fill_console CONOUTH ?options?
Sets the text attribute of cells in specified area of the screen buffer. The text attributes are specified with one or more of the options described in Text Attributes. The following additional options may also be specified:

-fillchar CHARACTER | Normally, the command does not change the text contents in the specified region. If this option is specified, in addition to changing the attributes in the specified region, the contents of each cell are set to CHARACTER.
-mode line|column | If specified as column (default), the fill region in the second line starts at the same column as the first line. If specified as line, the fill region starts at the first column in the second and subsequent lines.
-numcols INTEGER | Width of the region to be filled. By default, the fill region extends to the rightmost column of the screen buffer.
-numlines INTEGER | Number of rows to be filled. By default, the fill region extends to the rightmost column of the screen buffer.
-position POSITION | Location of the top left corner of the fill region. POSITION is specified as a list of two integers corresponding to the column and row.
-window BOOL | If specified as true, the fill region is the visible window portion of the screen buffer. This option cannot be used with the -position, -numlines and -numrows options.

flush_console_input CONINH
Removes any pending input events from the buffer of the specified input console.
free_console
Frees the console attached to the process.
generate_console_control_event EVENT ?PROCESSGROUP?
Sends a control event to a process group. EVENT should be one of ctrl-c or ctrl-break. PROCESSGROUP indicates the console process group to which the event should be sent. By default, the event is sent to all processes sharing the console of the caller.
get_console_handle TYPE
Returns a handle to console input, output or error. Note if input and output have been redirected, the handle may not be the same as returned by get_standard_handle. TYPE must be stdin or stdout.
get_console_input_codepage
Returns the input code page of the console.
get_console_input_mode ?CONINH?
Returns the input mode of the console. CONINH is a handle to console input and defaults to stdin. The returned value is a list describing the current mode. See Console Modes for the possible values.
get_console_output_mode ?CONOUTH?
Returns the output mode of the console. CONOUTH is a handle to console output and defaults to stdout. The returned value is a list describing the current mode. See Console Modes for the possible values.
get_console_pending_input_count CONINH
Returns the number of pending input events for the specified console.
get_console_screen_buffer_info CONH ?options?
Retrieves various information about a screen buffer as a flat list of option VALUE pairs. The following options determine what information is returned:

-all | Equivalent to specifying all other options.
-cursorpos | Returns the cursor position in the screen buffer.
-maxwindowsize | Returns the maximum possible size of a window in the screen buffer as a pair of integer corresponding to the width and height. This takes into account the screen buffer size, the display size and the font being used.
-size | Returns a list of two integers containing the number of columns and rows in the screen buffer.
-textattr | Returns the default text attributes used when writing into the screen buffer.
-windowpos | Returns a list of two integers corresponding to the column and row of the top left cell of the window.
-windowsize | Returns a list of two integers containing the number of columns and rows in the window.

get_console_title
Returns the title of the window of the currently attached console.
get_console_window
Returns the handle to the window displaying the currently attached console.
get_console_window_maxsize
Returns the maximum size of a console window given the current display size and font as a list of two integers corresponding to the width and height. This command does not take into account the size of the screen buffer itself. The -maxwindowsize option of get_console_screen_buffer_info does take into account the screen buffer size.
get_standard_handle TYPE
Returns a handle to standard input, output or error. This may correspond to the console or some other device if the standard devices have been redirected. If the process does not have associated standard handles, an exception is generated with errorCode set to WINDOWS 2 ERRORMESSAGE. If the returned handle corresponds to a console device, it can be passed to the other console commands. TYPE is one of stdin, stdout, stderr.

Note this command returns a handle to standard input, output and error, which may not be the console if they have been redirected. To retrieve handles to the console, use the get_console_handle function.
modify_console_input_mode CONINH MODEOPTIONS...
Modifies the input modes for the console identified by CONINH according to the mode options specified. MODEOPTIONS must correspond to the input mode options described in Console Modes. Any options not specified are unchanged. The command returns the previous input modes of the console.

Also see set_console_input_mode.
modify_console_output_mode CONOUTH MODEOPTIONS...
Modifies the output modes for the console identified by CONOUTH according to the mode options specified. MODEOPTIONS must correspond to the output mode options described in Console Modes. Any options not specified are unchanged. The command returns the previous output modes of the console.

Also see set_console_output_mode.
num_console_mouse_buttons
Returns the number of console mouse buttons.
set_console_active_screen_buffer CONOUTH
Sets the active screen buffer of the currently attached console to CONOUTH.
set_console_control_handler SCRIPT
Registers SCRIPT to be invoked when a console application receives one of the control events in the table below. The appropriate event name is appended to SCRIPT before it is invoked. The script should return a non-zero integer value if it has handled the event itself. Any other value returned from the script will result in the event being passed on to other handlers including the operating system default handler.

Calling the command a second time will result in the previous callback script being replaced. So if multiple scripts are to be invoked, the application has to do the chaining itself.

If SCRIPT is empty, the callback handler is unregistered.

In order for the callback scripts to be invoked, the Tcl event loop must be running (through vwait, update etc.). Note that this function should be used only in console applications, not Win32 GUI applications.

The following event names are passed to SCRIPT.

ctrl-c | A Ctrl-C signal was received.
ctrl-break | A Ctrl-Break signal was received.
close | The user requested the console window to be closed.
logoff | The user is logging off.
shutdown | The system is being shut down.

set_console_cursor_position CONOUTH X Y
Sets the cursor position in a screen buffer. CONOUTH is the handle to the buffer and X Y is a list of two integers specifying the column and row that the cursor is to be positioned at.
set_console_default_attr CONOUTH ?options?
Sets the default attribute to be used when writing to the specified screen buffer. See Text Attributes for a list of valid options.
set_console_input_codepage CODEPAGE
Sets the input code page of the console.
set_console_input_mode CONINH MODEOPTIONS...
Sets the input mode for the console identified by CONINH according to the mode options specified. MODEOPTIONS must correspond to the input mode options described in Console Modes. Any options not specified are assumed to be false. To change the input mode for specific options without affecting others, use modify_console_input_mode. For example,

    set_console_input_mode stdin -echoinput 0 -lineinput 1

will set the console input to only have mode -lineinput set. -echoinput as well as unspecified modes will be reset. On the other hand,

    modify_console_input_mode stdin -echoinput 0 -lineinput 1

will turn off -echoinput mode, turn on -lineinput mode but will leave others unchanged.
set_console_output_codepage CODEPAGE
Sets the output code page of the console.
set_console_output_mode CONOUTH MODEOPTIONS...
Sets the output modes for the console identified by CONOUTH according to the modes specified. MODEOPTIONS must correspond to the output modes described in Console Modes. Any modes not specified are reset. To change the output modes for specific options without affecting others, use modify_console_output_mode. For example,

    set_console_output_mode stdout -processedoutput 0

will set the console output to only have mode -processedoutput set. On the other hand,

    modify_console_output_mode stdout -processedoutput 0

will turn off -processedoutput mode but leave others unchanged.
set_console_screen_buffer_size CONOUTH SCRSIZE
Sets the size of the specified console screen buffer. SCRSIZE should be a list of two integers containing the width and height of the screen buffer in characters.
set_console_title TEXT
Sets the title of the window of the currently attached console to TEXT.
set_console_window_location CONOUTH RECT ?-absolute BOOL?
Sets the position and size of the visible window within the specified screen buffer. RECT is a list of four integers containing the left column position, the top row position, the right column position and the bottom row position. If option -absolute is true (default), the coordinates are absolute coordinates in the screen buffer. Otherwise, they are relative to the current window coordinates.
set_standard_handle TYPE HANDLE
Redirects standard input, output or error to the specified HANDLE. TYPE is one of stdin, stdout, stderr. HANDLE may be any handle to a device.
write_console CONOUTH STRING ?options?
Writes the sequence of characters in STRING to the screen buffer identified by CONOUTH. The characters are always written to the screen buffer in raw mode, i.e. as if the -processedoutput mode (see Console Modes) was off. The original mode setting is restored after the write is completed. Note however, that newline characters are treated specially.

In addition, the following options may be specified to alter the behavour of the write.

-newlinemode line|column | If the -newlinemode is set to column (default), a newline character in STRING causes further characters to be written at the original starting column position on the next line. If the option is specified as line, characters after the newline character are written starting at the first column on the next line.
-position COORD | By default, the characters are written starting at the current cursor position. This option may be specified to change the location at which the characters are written. COORD is a list of two integers containing the column and row coordinates of the starting location.
-restoreposition BOOL

COPYRIGHT

Copyright © 2004-2009 Ashok P. Nadkarni


Task Scheduler - Windows task scheduler

Task Scheduler

Commands related to the Windows task scheduler

SYNOPSIS

package require twapi

itask_configure ITASK_HANDLE ?options?
itask_delete_itasktrigger ITASK_HANDLE INDEX
itask_edit_dialog ITASK_HANDLE
itask_end ITASK_HANDLE
itask_get_info ITASK_HANDLE ?options?
itask_get_itasktrigger ITASK_HANDLE INDEX
itask_get_itasktrigger_count ITASK_HANDLE
itask_get_itasktrigger_string ITASK_HANDLE INDEX
itask_get_runtimes_within_interval ITASK_HANDLE ?options?
itask_new_itasktrigger ITASK_HANDLE
itask_release ITASK_HANDLE
itask_run ITASK_HANDLE
itask_save ITASK_HANDLE
itaskscheduler_delete_task ITASKSCHEDULER_HANDLE TASKNAME
itaskscheduler_get_itask ITASKSCHEDULER_HANDLE TASKNAME
itaskscheduler_get_target_system ITASKSCHEDULER_HANDLE
itaskscheduler_get_tasks ITASKSCHEDULER_HANDLE
itaskscheduler_new ?-system SYSTEMNAME?
itaskscheduler_new_itask ITASKSCHEDULER_HANDLE TASKNAME
itaskscheduler_release ITASKSCHEDULER_HANDLE
itaskscheduler_set_target_system ITASKSCHEDULER_HANDLE SYSTEMNAME
itaskscheduler_task_exists ITASKSCHEDULER_HANDLE TASKNAME
itasktrigger_configure ITASKTRIGGER_HANDLE ?options?
itasktrigger_get_info ITASKTRIGGER_HANDLE
itasktrigger_release ITASKTRIGGER_HANDLE
mstask_create TASKNAME ?options?
mstask_delete TASKNAME ?options?

DESCRIPTION

This module provides commands for scheduling and running jobs through the Windows task scheduler.

Overview

The Windows task scheduler allows programs to be automatically started at certain times or when certain conditions are met. Tasks may be scheduled on either local or remote computers.

The simplest way to create and delete tasks is through the mstask_create and mstask_delete commands. These take care of acquiring and releasing the low lever interface handles and deal with the common case where a single task trigger is associated with a task.

More flexible and complete task scheduler functionality is available through commands that expose the interface handles to the different types of task scheduler objects. Working with the task scheduler involves three types of objects:

  • The task scheduler service which manages tasks
  • A task which is a unit of work scheduled by the task scheduler and is identified by a name unique to a system.
  • A task trigger which defines the conditions under which a task will be run. A task may have multiple associated task triggers.
An interface to the local or a remote task scheduler is obtained through the itaskscheduler_new command. The returned interface handle can be used to manage tasks on that computer. The commands itaskscheduler_get_target_system and itaskscheduler_set_target_system allow retrieving and changing the system associated with the task scheduler handle at any time.

Once a task scheduler interface handle is obtained, it can be used to access task definitions for that scheduler. The commands itaskscheduler_new_itask and itaskscheduler_get_itask will return interfaces to new and existing tasks which can be manipulated as described below. Tasks can also be deleted through the itaskscheduler_delete_task command and enumerated using itaskscheduler_get_tasks. Existence of a task definition can be verified using the itaskscheduler_task_exists command. (Note: as a general rule, commands related to tasks that require a task interface handle use itask in the command name while commands that require a task name use task.)

Once an interface handle to a task is obtained, its settings can be accessed and modified through the itask_get_info and itask_configure commands. Any changes made must be saved by then calling the itask_save command. Alternately, itask_edit_dialog may be used to display a dialog that allows the user to configure a task.

In addition to scheduling through the task scheduler, task execution can also be directly controlled. itask_run will immediately run a task while itask_end will terminate a task that is currently executing. Future times when a task will be run can be obtained using the itask_get_runtimes_within_interval call.

Each task is associated with zero or more task triggers that determine when and under what conditions the task is executed. The commands itask_new_itasktrigger and itask_get_itasktrigger return interface handles to new or existing task triggers. When not required triggers can be deleted through itask_delete_itasktrigger. The number of triggers associated with a task can be obtained through the itask_get_itasktrigger_count command. itask_get_itasktrigger_string returns a string describing the trigger.

Once a handle to a trigger is obtained, its settings can be retrieved and modified through the itasktrigger_get_info and itasktrigger_configure commands respectively.

Commands

itask_configure ITASK_HANDLE ?options?
Modifies the settings for the task associated with the handle ITASK_HANDLE. Note that the command itask_save must be called to save the changes.

The following options may be specified to change the settings for the task:

-account USERNAME | Sets USERNAME as the account under which the task will be run. If USERNAME is specified as the empty string, the task will be run under the system account. If any user other than the system account is specified, the -password option must also be specified.
-application PATH | Sets the application to be executed to PATH.
-comment COMMENT | Sets the comment for the task.
-creator NAME | Sets the task's creator name.
-data BINDATA | Stores BINDATA as the application-defined data for the task. BINDATA is treated as binary data.
-deletewhendone BOOLEAN | If specified as true, the task will be automatically deleted from the task scheduler when it has no more scheduled run times. Default is false.
-disabled BOOLEAN | If specified as true, the task is disabled and will not be run at its scheduled times. Default is false.
-dontstartonbatteries BOOLEAN | If specified as true, the task is not started at the scheduled time if the system is running on batteries. Default is false.
-hidden BOOLEAN | If specified as true, the task is hidden. Default is false.
-idlewait MINUTES | Sets the number of minutes that the system must be idle before the task runs.
-idlewaitdeadline MINUTES | Sets the maximum number of minutes that the task scheduler will wait for the system to become idle.
-killifonbatteries BOOLEAN | If specified as true, the task is not terminated if if the system is switches to batteries while the task is running. Default is false.
-killonidleend BOOLEAN | If specified as true, the task is terminated, if running, when the computer switches to a non-idle state (i.e. receives user input). Default is false.
-maxruntime MILLISECONDS | Sets the maximum time (in milliseconds) the application can run before it is terminated. If MILLISECONDS is specified as -1, there is no limit on the run time.
-params PARAMSTRING | Sets PARAMSTRING as the parameters to be passed to the application when the task is run.
-password PASSWORD | Specifies PASSWORD as the password associated with the user account specified with the -account option.
-priority PRIORITY | Sets the priority for the process executing the task. PRIORITY must be one of normal, abovenormal, belownormal, high, realtime, or idle.
-resumesystem BOOLEAN | If specified as true, the system will be awakened from a suspended state, if necessary, at the task's scheduled time. Default is false.
-restartonidleresume BOOLEAN | If specified as true, the task is restarted when the system goes into an idle state and the task had been previously terminated when the system went into a non-idle state. Default is false.
-runonlyifloggedon BOOLEAN | If specified as true, the task is only run if the user specified through the -account option is logged on. Default is false.
-startonlyifidle BOOLEAN | If specified as true, the task is only run if the system is idle at the task's scheduled run time. Default is false.
-workingdir PATH | Sets PATH as the working directory when the task is executed.

itask_delete_itasktrigger ITASK_HANDLE INDEX
Deletes the task trigger at position INDEX in the list of triggers for the task associated with handle ITASK_HANDLE.
itask_edit_dialog ITASK_HANDLE
Displays a dialog that allows the user to edit the task properties. Note that the dialog is modal and will lock out other windows until it is closed.
itask_end ITASK_HANDLE
Terminates (forcibly if necessary) the task associated with handle ITASK_HANDLE it it is running.
itask_get_info ITASK_HANDLE ?options?
Returns the settings for the task associated with handle ITASK_HANDLE. Any of the options described in itask_configure, except -password, may be specified to retrieve the corresponding setting. In addition, the command supports the following additional options:

-all | Returns all settings.
-lastruntime | Returns the last time that the task was run in the format Year-Month-Day Hour:Minutes:Seconds. (Note the month must be specified numerically.) An empty string is returned if the task has not been run yet.
-nextruntime | Returns the next time that the task is scheduled to run in the format Year-Month-Day Hour:Minutes:Seconds. (Note the month must be specified numerically.) The return value may also be one of disabled if the task is disabled, notriggers if no triggers are defined for it, or oneventonly if the task is configured to run on events as opposed to time.
-status | Returns the status of the task which is one of ready, running, disabled, partiallydefined, or unknown.

itask_get_itasktrigger ITASK_HANDLE INDEX
Returns an interface handle for an existing task trigger for the task associated with the handle ITASK_HANDLE. INDEX is the index of the trigger in the list of triggers defined for the task. When no longer required, the returned handle must be released by calling itasktrigger_release.
itask_get_itasktrigger_count ITASK_HANDLE
Returns the number of task triggers defined for the task associated with handle ITASK_HANDLE.
itask_get_itasktrigger_string ITASK_HANDLE INDEX
Returns a string description for an existing task trigger for the task associated with the handle ITASK_HANDLE. INDEX is the index of the trigger in the list of triggers defined for the task.
itask_get_runtimes_within_interval ITASK_HANDLE ?options?
Returns a list of times that the task is scheduled to run within a specified interval. Each item in the list is in the format Year-Month-Day Hour:Minutes:Seconds. The following options may be specified:

-count COUNT | The maximum number of time elements to return. COUNT must be less than 1440. The actual number returned may of course be less than COUNT depending on how many times the task is scheduled to run in the specified interval.
-end DATETIMESPEC | The ending time of the interval specified as Year-Month-Day Hour:Minutes:Seconds. By default, this is January 1, 2038. Note the month must be specified numerically.
-start DATETIMESPEC | The starting time of the interval specified as Year-Month-Day Hour:Minutes:Seconds. By default, this is the current time. Note the month must be specified numerically.
-statusvar VARNAME | If specified, VARNAME in the caller's context is set to the status of the call. This is success to indicate successful retrieval of the scheduled times. Otherwise, it may also be be one of disabled if the task is disabled, notriggers if no triggers are defined for it, or oneventonly if the task is configured to run on events as opposed to time. In all these three cases, the return value of the command is an empty list.

itask_new_itasktrigger ITASK_HANDLE
Creates a new task trigger for the task associated with the handle ITASK_HANDLE. The command returns a list of two elements. The first is the index of the newly created trigger in the list of triggers defined for the task. The second element is an interface handle to the newly defined task trigger. When no longer required, this must be released by calling itasktrigger_release.
itask_release ITASK_HANDLE
Releases resources associated with a task handle.
itask_run ITASK_HANDLE
Runs the task associated with handle ITASK_HANDLE.
itask_save ITASK_HANDLE
Saves any changes that have been made to the task associated with handle ITASK_HANDLE.
itaskscheduler_delete_task ITASKSCHEDULER_HANDLE TASKNAME
Deletes an existing task with name TASKNAME from the task scheduler associated with the handle ITASKSCHEDULER_HANDLE.
itaskscheduler_get_itask ITASKSCHEDULER_HANDLE TASKNAME
Returns an interface handle to an existing task with name TASKNAME. ITASKSCHEDULER_HANDLE is an interface handle to a task scheduler instance returned by itaskscheduler_new. The returned handle must be released by calling itask_release when it is no longer required.
itaskscheduler_get_target_system ITASKSCHEDULER_HANDLE
Returns the name of the system that the task scheduler associated with the handle ITASKSCHEDULER_HANDLE operates on.
itaskscheduler_get_tasks ITASKSCHEDULER_HANDLE
Returns a list of the names of the tasks contained in the task scheduler associated with the handle ITASKSCHEDULER_HANDLE.
itaskscheduler_new ?-system SYSTEMNAME?
Returns an interface handle to the task scheduler on the local system, or if the -system option is specified, on a remote system. The returned handle must be released by calling itaskscheduler_release when it is no longer required.
itaskscheduler_new_itask ITASKSCHEDULER_HANDLE TASKNAME
Creates a new task with name TASKNAME and returns an interface handle to it. ITASKSCHEDULER_HANDLE is an interface handle to a task scheduler instance returned by itaskscheduler_new. The returned handle must be released by calling itask_release when it is no longer required.
itaskscheduler_release ITASKSCHEDULER_HANDLE
Releases resources associated with a task scheduler handle returned by itaskscheduler_new.
itaskscheduler_set_target_system ITASKSCHEDULER_HANDLE SYSTEMNAME
Sets the task scheduler associated with the handle ITASKSCHEDULER_HANDLE to be the system identified by SYSTEMNAME.
itaskscheduler_task_exists ITASKSCHEDULER_HANDLE TASKNAME
Returns true if a new task with name TASKNAME exists in the task scheduler associated with handle ITASKSCHEDULER_HANDLE.
itasktrigger_configure ITASKTRIGGER_HANDLE ?options?
Configures the task trigger associated with the handle ITASKTRIGGER_HANDLE.

The following options may be specified to configure the task trigger:

-begindate DATESPEC | Specifies the date on which the trigger is activated. DATESPEC must be in the format YEAR-MONTH-DAY. Defaults to the current date.
-daysofmonth MONTHDAYMASK | Specifies the days of the month that the task is scheduled to run. MONTHDAYMASK is a bitmask with the low order bit corresponding to the first day of the month. This option only has effect if the value of the -type option is monthlydate.
-disabled BOOLEAN | If specified as true, disables the trigger so it has no effect. Default is false.
-duration MINUTES | Specifies the number of minutes after the task starts that the trigger is active. The task will be continuously restarted during this period with the interval between starts given by the option -interval.
-enddate DATESPEC | Specifies the date on which the trigger becomes inactive. DATESPEC must be in the format YEAR-MONTH-DAY. If DATESPEC is the empty string, there is no end date and the trigger never becomes inactive. This is also the default.
-interval MINUTES | See description of -duration.
-killatdurationend BOOLEAN | If specified as true, the task is terminated if it is still running at the end of the trigger duration. Default is false.
-months MONTHMASK | Specifies the months in which the trigger is active. MONTHMASK is a bitmask with the low order bit corresponding to January. The trigger is active in those months for which the corresponding bit is set. By default, the trigger is active for all months. This option is only used if the -type option specifies the trigger type to be either monthlydate or monthlydow.
-period PERIOD | If -type is daily, PERIOD is the number of days between invocations of the task. Similarly, if -type is weekly, PERIOD is the number of weeks between invocations of the task. This option is not used for other trigger types. If unspecified, this option defaults to 1.
-starttime TIMESPEC | Specifies the time at which the task is to be run. TIMESPEC is of the form HOUR:MINUTES.
-type TRIGGERTYPE Specifies the type of the trigger. If TRIGGERTYPE is once, the task will only be run once.

A value of daily or weekly will cause the task to be scheduled daily or weekly respectively. In both cases, the interval between runs being governed by the -period option. Furthermore, in the weekly case, the option -weekdays will control which days of the week the task is run.

If TRIGGERTYPE is monthlydate, the task will be scheduled for the days defined by the -months and -daysofmonth options.

A value of monthlydow allows the task to be scheduled during a specific week of a month. The -weekofmonth option specifies which week of the month, the -weekdays option specifies which days in that week, and -months option specifies which months are included.

In addition, there are three trigger types that are event based - if TRIGGERTYPE is onidle, the trigger is activated when the system becomes idle, atsystemstart causes the task to run every time the system starts and atlogon causes it to run everytime the user logs on.
-weekdays WEEKMASK | Specifies the days of a week that the trigger should be activated. WEEKMASK is a bitmask corresponding to days of the week with the low order bit corresponding to Sunday. This option is only used if -type is specified as weekly or monthlydow.
-weekofmonth WEEKNUMBER | Specifies the week of the month that a task should be active. WEEKNUMBER must be an integer in the range 1-5 where 1-4 correspond to the first four weeks while a value of 5 corresponds to the last week of the month.

itasktrigger_get_info ITASKTRIGGER_HANDLE
Returns the settings for the task trigger associated with the handle ITASKTRIGGER_HANDLE. The settings are returned as a flat list of option value pairs. See itasktrigger_configure for information about the returned fields. Note that the returned fields depend on the trigger type as noted there.
itasktrigger_release ITASKTRIGGER_HANDLE
Releases resources associated with a task trigger handle.
mstask_create TASKNAME ?options?
This is command is a wrapper around that the various task scheduler interfaces that allows for easy creation of a task. It handles the common case where a task has a single associated trigger.

The command creates a new task based on the specified options. It accepts all the task related options as described for the itask_configure command. It associates a single trigger with the task and accepts all task trigger configuration options described for task triggers in itasktrigger_configure except for -disabled.

In addition, the command accepts the option -system which allows specification of which system the task is to be created on. By default, the task is created on the local system.
mstask_delete TASKNAME ?options?
This is command is a wrapper around that the various task scheduler interfaces that allows for easy deletion of a task. TASKNAME is the name that identifies the task.

The command accepts the option -system which allows specification of which system the task is to be deleted. By default, the task is deleted on the local system.

COPYRIGHT

Copyright © 2004-2009 Ashok P. Nadkarni


Microsoft Windows Installer - Microsoft Windows Installer support

Microsoft Windows Installer

Commands for accessing Microsoft Windows Installer

SYNOPSIS

package require twapi

load_msi_prototypes MSICOMOBJ MSITYPE
INSTALLEROBJ AddSource ARGS
INSTALLEROBJ ClearSourceList ARGS
INSTALLEROBJ CollectUserInfo ARGS
INSTALLEROBJ ComponentClients ARGS
INSTALLEROBJ ComponentPath ARGS
INSTALLEROBJ ComponentQualifiers ARGS
INSTALLEROBJ Components ARGS
INSTALLEROBJ ConfigureFeature ARGS
INSTALLEROBJ ConfigureProduct ARGS
INSTALLEROBJ CreateRecord ARGS
INSTALLEROBJ EnableLog ARGS
INSTALLEROBJ Environment ARGS
INSTALLEROBJ ExtractPatchXMLData ARGS
INSTALLEROBJ FeatureParent ARGS
INSTALLEROBJ Features ARGS
INSTALLEROBJ FeatureState ARGS
INSTALLEROBJ FeatureUsageCount ARGS
INSTALLEROBJ FeatureUsageDate ARGS
INSTALLEROBJ FileAttributes ARGS
INSTALLEROBJ FileSize ARGS
INSTALLEROBJ FileVersion ARGS
INSTALLEROBJ InstallProduct ARGS
INSTALLEROBJ LastErrorRecord ARGS
INSTALLEROBJ OpenPackage ARGS
INSTALLEROBJ OpenDatabase ARGS
INSTALLEROBJ OpenProduct ARGS
INSTALLEROBJ Patches ARGS
INSTALLEROBJ PatchesEx ARGS
INSTALLEROBJ ProductInfo ARGS
INSTALLEROBJ ProductsEx ARGS
INSTALLEROBJ Products ARGS
INSTALLEROBJ ProductState ARGS
INSTALLEROBJ ProvideComponent ARGS
INSTALLEROBJ RegistryValue ARGS
INSTALLEROBJ ReinstallFeature ARGS
INSTALLEROBJ ReinstallProduct ARGS
INSTALLEROBJ RelatedProducts ARGS
INSTALLEROBJ RemovePatches ARGS
INSTALLEROBJ ShortcutTarget ARGS
INSTALLEROBJ SummaryInformation ARGS
INSTALLEROBJ UILevel ARGS
INSTALLEROBJ UseFeature ARGS
INSTALLEROBJ Version ARGS
MSIDBOBJ ApplyTransform ARGS
MSIDBOBJ Commit ARGS
MSIDBOBJ CreateTransformSummaryInfo ARGS
MSIDBOBJ DatabaseState ARGS
MSIDBOBJ EnableUIPreview ARGS
MSIDBOBJ Export ARGS
MSIDBOBJ GenerateTransform ARGS
MSIDBOBJ Import ARGS
MSIDBOBJ Merge ARGS
MSIDBOBJ OpenView ARGS
MSIDBOBJ PrimaryKeys ARGS
MSIDBOBJ TablePersistent ARGS
MSIRECORDOBJ ClearData ARGS
MSIRECORDOBJ DataSize ARGS
MSIRECORDOBJ FieldCount ARGS
MSIRECORDOBJ FormatText ARGS
MSIRECORDOBJ IntegerData ARGS
MSIRECORDOBJ IsNull ARGS
MSIRECORDOBJ ReadStream ARGS
MSIRECORDOBJ SetStream ARGS
MSIRECORDOBJ StringData ARGS
MSISUMMARYOBJ Persist ARGS
MSISUMMARYOBJ Property ARGS
MSISUMMARYOBJ PropertyCount ARGS
MSISTRINGLISTOBJ Count ARGS
MSISTRINGLISTOBJ Item ARGS
MSIVIEWOBJ Close ARGS
MSIVIEWOBJ ColumnInfo ARGS
MSIVIEWOBJ Execute ARGS
MSIVIEWOBJ Fetch ARGS
MSIVIEWOBJ GetError ARGS
MSIVIEWOBJ Modify ARGS

DESCRIPTION

This module provides commands for accessing the Microsoft Windows Installer (MSI) component through its COM interfaces. The primary motivation for this module is that although the Installer provides a COM type library, its type library may not be available on the target system. This module provides the required type definitions for the various interfaces.

Creation and Destruction of MSI objects

MSI objects are created through TWAPI's COM interface commands. The Installer object is created through the command

set msiobj [comobj WindowsInstaller.Installer]

Once an MSI object is no longer needed, it must be deleted like any other COM object.

$msiobj -destroy

Note a final call to $MSIOBJ -destroy is required for all MSI objects, not just the top-level Installer object.

Once an MSI object is created, its type library must be explicitly loaded by calling load_msi_prototypes with the object command and the object type.

twapi::load_msi_prototypes $msiobj Installer

Example: List installed products

load_msi_prototypes MSICOMOBJ MSITYPE
Loads the type information corresponding to the MSI type MSITYPE into the COM object command MSICOMOBJ. The sections below describe the various types of MSI objects that can be loaded. When an object of a type is created, it should be passed to load_msi_prototypes along with the type before making any method calls on the objects.

Installer object

An Installer object supports the following methods:

INSTALLEROBJ AddSource ARGS
Refer to Windows Installer Reference for a description and parameters.
INSTALLEROBJ ClearSourceList ARGS
Refer to Windows Installer Reference for a description and parameters.
INSTALLEROBJ CollectUserInfo ARGS
Refer to Windows Installer Reference for a description and parameters.
INSTALLEROBJ ComponentClients ARGS
Refer to Windows Installer Reference for a description and parameters.
INSTALLEROBJ ComponentPath ARGS
Refer to Windows Installer Reference for a description and parameters.
INSTALLEROBJ ComponentQualifiers ARGS
Refer to Windows Installer Reference for a description and parameters.
INSTALLEROBJ Components ARGS
Refer to Windows Installer Reference for a description and parameters.
INSTALLEROBJ ConfigureFeature ARGS
Refer to Windows Installer Reference for a description and parameters.
INSTALLEROBJ ConfigureProduct ARGS
Refer to Windows Installer Reference for a description and parameters.
INSTALLEROBJ CreateRecord ARGS
Refer to Windows Installer Reference for a description and parameters.
INSTALLEROBJ EnableLog ARGS
Refer to Windows Installer Reference for a description and parameters.
INSTALLEROBJ Environment ARGS
Refer to Windows Installer Reference for a description and parameters.
INSTALLEROBJ ExtractPatchXMLData ARGS
Refer to Windows Installer Reference for a description and parameters.
INSTALLEROBJ FeatureParent ARGS
Refer to Windows Installer Reference for a description and parameters.
INSTALLEROBJ Features ARGS
Refer to Windows Installer Reference for a description and parameters.
INSTALLEROBJ FeatureState ARGS
Refer to Windows Installer Reference for a description and parameters.
INSTALLEROBJ FeatureUsageCount ARGS
Refer to Windows Installer Reference for a description and parameters.
INSTALLEROBJ FeatureUsageDate ARGS
Refer to Windows Installer Reference for a description and parameters.
INSTALLEROBJ FileAttributes ARGS
Refer to Windows Installer Reference for a description and parameters.
INSTALLEROBJ FileSize ARGS
Refer to Windows Installer Reference for a description and parameters.
INSTALLEROBJ FileVersion ARGS
Refer to Windows Installer Reference for a description and parameters.
INSTALLEROBJ InstallProduct ARGS
Refer to Windows Installer Reference for a description and parameters.
INSTALLEROBJ LastErrorRecord ARGS
Refer to Windows Installer Reference for a description and parameters.
INSTALLEROBJ OpenPackage ARGS
Refer to Windows Installer Reference for a description and parameters.
INSTALLEROBJ OpenDatabase ARGS
Refer to Windows Installer Reference for a description and parameters.
INSTALLEROBJ OpenProduct ARGS
Refer to Windows Installer Reference for a description and parameters.
INSTALLEROBJ Patches ARGS
Refer to Windows Installer Reference for a description and parameters.
INSTALLEROBJ PatchesEx ARGS
Refer to Windows Installer Reference for a description and parameters.
INSTALLEROBJ ProductInfo ARGS
Refer to Windows Installer Reference for a description and parameters.
INSTALLEROBJ ProductsEx ARGS
Refer to Windows Installer Reference for a description and parameters.
INSTALLEROBJ Products ARGS
Refer to Windows Installer Reference for a description and parameters.
INSTALLEROBJ ProductState ARGS
Refer to Windows Installer Reference for a description and parameters.
INSTALLEROBJ ProvideComponent ARGS
Refer to Windows Installer Reference for a description and parameters.
INSTALLEROBJ RegistryValue ARGS
Refer to Windows Installer Reference for a description and parameters.
INSTALLEROBJ ReinstallFeature ARGS
Refer to Windows Installer Reference for a description and parameters.
INSTALLEROBJ ReinstallProduct ARGS
Refer to Windows Installer Reference for a description and parameters.
INSTALLEROBJ RelatedProducts ARGS
Refer to Windows Installer Reference for a description and parameters.
INSTALLEROBJ RemovePatches ARGS
Refer to Windows Installer Reference for a description and parameters.
INSTALLEROBJ ShortcutTarget ARGS
Refer to Windows Installer Reference for a description and parameters.
INSTALLEROBJ SummaryInformation ARGS
Refer to Windows Installer Reference for a description and parameters.
INSTALLEROBJ UILevel ARGS
Refer to Windows Installer Reference for a description and parameters.
INSTALLEROBJ UseFeature ARGS
Refer to Windows Installer Reference for a description and parameters.
INSTALLEROBJ Version ARGS
Refer to Windows Installer Reference for a description and parameters.

Database object

A MSI Database object supports the following methods:

MSIDBOBJ ApplyTransform ARGS
Refer to Windows Installer Reference for a description and parameters.
MSIDBOBJ Commit ARGS
Refer to Windows Installer Reference for a description and parameters.
MSIDBOBJ CreateTransformSummaryInfo ARGS
Refer to Windows Installer Reference for a description and parameters.
MSIDBOBJ DatabaseState ARGS
Refer to Windows Installer Reference for a description and parameters.
MSIDBOBJ EnableUIPreview ARGS
Refer to Windows Installer Reference for a description and parameters.
MSIDBOBJ Export ARGS
Refer to Windows Installer Reference for a description and parameters.
MSIDBOBJ GenerateTransform ARGS
Refer to Windows Installer Reference for a description and parameters.
MSIDBOBJ Import ARGS
Refer to Windows Installer Reference for a description and parameters.
MSIDBOBJ Merge ARGS
Refer to Windows Installer Reference for a description and parameters.
MSIDBOBJ OpenView ARGS
Refer to Windows Installer Reference for a description and parameters.
MSIDBOBJ PrimaryKeys ARGS
Refer to Windows Installer Reference for a description and parameters.
MSIDBOBJ TablePersistent ARGS
Refer to Windows Installer Reference for a description and parameters.

Record object

A MSI Record object supports the following methods:

MSIRECORDOBJ ClearData ARGS
Refer to Windows Installer Reference for a description and parameters.
MSIRECORDOBJ DataSize ARGS
Refer to Windows Installer Reference for a description and parameters.
MSIRECORDOBJ FieldCount ARGS
Refer to Windows Installer Reference for a description and parameters.
MSIRECORDOBJ FormatText ARGS
Refer to Windows Installer Reference for a description and parameters.
MSIRECORDOBJ IntegerData ARGS
Refer to Windows Installer Reference for a description and parameters.
MSIRECORDOBJ IsNull ARGS
Refer to Windows Installer Reference for a description and parameters.
MSIRECORDOBJ ReadStream ARGS
Refer to Windows Installer Reference for a description and parameters.
MSIRECORDOBJ SetStream ARGS
Refer to Windows Installer Reference for a description and parameters.
MSIRECORDOBJ StringData ARGS
Refer to Windows Installer Reference for a description and parameters.

SummaryInfo object

A MSI SummaryInfo object supports the following methods:

MSISUMMARYOBJ Persist ARGS
Refer to Windows Installer Reference for a description and parameters.
MSISUMMARYOBJ Property ARGS
Refer to Windows Installer Reference for a description and parameters.
MSISUMMARYOBJ PropertyCount ARGS
Refer to Windows Installer Reference for a description and parameters.

StringList object

A MSI StringList object supports the following methods:

MSISTRINGLISTOBJ Count ARGS
Refer to Windows Installer Reference for a description and parameters.
MSISTRINGLISTOBJ Item ARGS
Refer to Windows Installer Reference for a description and parameters.

View object

A MSI View object supports the following methods:

MSIVIEWOBJ Close ARGS
Refer to Windows Installer Reference for a description and parameters.
MSIVIEWOBJ ColumnInfo ARGS
Refer to Windows Installer Reference for a description and parameters.
MSIVIEWOBJ Execute ARGS
Refer to Windows Installer Reference for a description and parameters.
MSIVIEWOBJ Fetch ARGS
Refer to Windows Installer Reference for a description and parameters.
MSIVIEWOBJ GetError ARGS
Refer to Windows Installer Reference for a description and parameters.
MSIVIEWOBJ Modify ARGS
Refer to Windows Installer Reference for a description and parameters.

COPYRIGHT

Copyright © 2007-2009 Ashok P. Nadkarni


Internationalization - Internationalization

Internationalization

Commands related to internationalization

SYNOPSIS

package require twapi

extract_primary_langid LANGID
extract_sublanguage_langid LANGID
format_currency NUMBER LCID ?options?
format_number NUMBER LCID ?options?
get_locale_info LCID ?options?
get_system_default_langid
get_system_default_lcid
get_system_ui_langid
get_user_default_langid
get_user_default_lcid
get_user_ui_langid
map_code_page_to_name CODEPAGENUM
map_langid_to_name LANGID

DESCRIPTION

This package provides procedures related to internationalization capabilities on Windows platforms.

Locales

A locale defines user preferences related to languages and culture-dependent formatting of numbers, currencies etc.. A locale identifier (LCID) is an integer or one of the keywords systemdefault or userdefault corresponding to the system and user default locales respectively.

The system maintains locale settings for the system as well as the user. These can be retrieved through the commands get_system_default_lcid and get_user_default_lcid respectively.

The command get_locale_info can be used to retrieve the settings associated with a particular locale.

Languages

Languages are identified by a 16 bit integer (LANGID) that includes the primary and sublanguage information. The commands extract_primary_langid and extract_sublanguage_langid may be used to retrieve these from the language identifier.

The system maintains several language settings. These can be retrieved through the commands get_system_default_langid, get_system_ui_langid, get_user_default_langid and get_user_ui_langid. Information related to a LANGID, such as it full name, can be retrieved by passing it to get_locale_info.

Formatting

Windows provides functions for formatting data as per local conventions. The command format_number formats numbers using a given locale as a base and with the ability to override particular format settings.

Commands

extract_primary_langid LANGID
Returns the primary language identifier for the language identifier specified by LANGID.
extract_sublanguage_langid LANGID
Returns the sublanguage identifier for the language identifier specified by LANGID.
format_currency NUMBER LCID ?options?
Formats NUMBER as a currency string per the given formatting specifications. LCID is a locale identifier. NUMBER must be in decimal format (the fractional part is optional) and may have a leading negative sign.

If no options are specified, the settings in the locale identified by LCID are used for formatting NUMBER.

If one or more of the following options are specified, they override the settings in the locale given by LCID.

-icurrency CURRENCYFORMAT | Controls how positive currency numbers are formatted including spacing, position of the currency symbol etc.. See the documentation for LOCALE_ICURRENCY in the Windows SDK for possible values of CURRENCYFORMAT.
-idigits DECIMALPLACES | Indicates the number of digits after the decimal point to include in the result. If specified as -1, the number of decimal places in the result is the same as in NUMBER.
-ilzero BOOLEAN | Specifies whether the result includes leading zeroes (true) or not (false) when NUMBER is a pure fraction.
-inegcurr NEGFORMAT | Controls how negative numbers are formatted including location of the currency symbol, the negative number indicator etc.. See the documentation for LOCALE_INEGCURR in the Windows SDK for possible values of NEGFORMAT.
-scurrency SYMBOL | Specifies that the string SYMBOL should be used as the monetary symbol.
-sdecimal DECIMALSEPARATOR | Specifies the string to be used to represent the decimal point.
-sgrouping GROUPNUM | Specifies the size of each group of digits to the left of the decimal point. GROUPNUM may be any integer between 0 and 9 or the value 32 which indicates the Indic convention of the grouping by the first thousand (3 digits) followed by groups of 2 digits.
-sthousand THOUSANDSEPARATOR | Specifies the string to be used as the thousands' separator.

format_number NUMBER LCID ?options?
Formats the number NUMBER as per the given formatting specifications. LCID is a locale identifier. NUMBER must be in decimal format (the fractional part is optional) and may have a leading negative sign.

If no options are specified, the settings in the locale identified by LCID are used for formatting NUMBER.

If one or more of the following options are specified, they override the settings in the locale given by LCID.

-idigits DECIMALPLACES | Indicates the number of digits after the decimal point to include in the result. If specified as -1, the number of decimal places in the result is the same as in NUMBER.
-ilzero BOOLEAN | Specifies whether the result the result includes leading zeroes (true) or not (false).
-inegnumber NEGFORMAT | Controls how negative numbers are formatted. See the documentation for LOCALE_INEGNUMBER in the Windows SDK for possible values of NEGFORMAT.
-sgrouping GROUPNUM | Specifies the size of each group of digits to the left of the decimal point. GROUPNUM may be any integer between 0 and 9 or the value 32 which indicates the Indic convention of the grouping by the first thousand (3 digits) followed by groups of 2 digits.
-sdecimal DECIMALSEPARATOR | Specifies the string to be used to represent the decimal point.
-sthousand THOUSANDSEPARATOR | Specifies the string to be used as the thousands' separator.

get_locale_info LCID ?options?
Returns a list containing information about the locale identified by LCID. The information returned depends on the options specified and is formatted as a list of the form "option VALUE...".

-ilanguage | language id
-slanguage | localized name of language
-senglanguage | English name of language
-sabbrevlangname | abbreviated language name
-snativelangname | native name of language
-icountry | country code
-scountry | localized name of country
-sengcountry | English name of country
-sabbrevctryname | abbreviated country name
-snativectryname | native name of country
-idefaultlanguage | default language id
-idefaultcountry | default country code
-idefaultcodepage | default oem code page
-idefaultansicodepage | default ansi code page
-idefaultmaccodepage | default mac code page
-slist | list item separator
-imeasure | 0 = metric, 1 = US
-sdecimal | decimal separator
-sthousand | thousand separator
-sgrouping | digit grouping
-idigits | number of fractional digits
-ilzero | leading zeros for decimal
-inegnumber | negative number mode
-snativedigits | native ascii 0-9
-scurrency | local monetary symbol
-sintlsymbol | intl monetary symbol
-smondecimalsep | monetary decimal separator
-smonthousandsep | monetary thousand separator
-smongrouping | monetary grouping
-icurrdigits | # local monetary digits
-iintlcurrdigits | # intl monetary digits
-icurrency | positive currency mode
-inegcurr | negative currency mode
-sdate | date separator
-stime | time separator
-sshortdate | short date format string
-slongdate | long date format string
-stimeformat | time format string
-idate | short date format ordering
-ildate | long date format ordering
-itime | time format specifier
-itimemarkposn | time marker position
-icentury | century format specifier (short date)
-itlzero | leading zeros in time field
-idaylzero | leading zeros in day field (short date)
-imonlzero | leading zeros in month field (short date)
-s1159 | AM designator
-s2359 | PM designator
-icalendartype | type of calendar specifier
-ioptionalcalendar | additional calendar types specifier
-ifirstdayofweek | first day of week specifier
-ifirstweekofyear | first week of year specifier
-sdayname1 | long name for Monday
-sdayname2 | long name for Tuesday
-sdayname3 | long name for Wednesday
-sdayname4 | long name for Thursday
-sdayname5 | long name for Friday
-sdayname6 | long name for Saturday
-sdayname7 | long name for Sunday
-sabbrevdayname1 | abbreviation for Monday
-sabbrevdayname2 | abbreviation for Tuesday
-sabbrevdayname3 | abbreviation for Wednesday
-sabbrevdayname4 | abbreviation for Thursday
-sabbrevdayname5 | abbreviation for Friday
-sabbrevdayname6 | abbreviation for Saturday
-sabbrevdayname7 | abbreviation for Sunday
-smonthname1 | long name for January
-smonthname2 | long name for February
-smonthname3 | long name for March
-smonthname4 | long name for April
-smonthname5 | long name for May
-smonthname6 | long name for June
-smonthname7 | long name for July
-smonthname8 | long name for August
-smonthname9 | long name for September
-smonthname10 | long name for October
-smonthname11 | long name for November
-smonthname12 | long name for December
-smonthname13 | long name for 13th month (if exists)
-sabbrevmonthname1 | abbreviation for January
-sabbrevmonthname2 | abbreviation for February
-sabbrevmonthname3 | abbreviation for March
-sabbrevmonthname4 | abbreviation for April
-sabbrevmonthname5 | abbreviation for May
-sabbrevmonthname6 | abbreviation for June
-sabbrevmonthname7 | abbreviation for July
-sabbrevmonthname8 | abbreviation for August
-sabbrevmonthname9 | abbreviation for September
-sabbrevmonthname10 | abbreviation for October
-sabbrevmonthname11 | abbreviation for November
-sabbrevmonthname12 | abbreviation for December
-sabbrevmonthname13 | abbreviation for 13th month (if exists)
-spositivesign | positive sign
-snegativesign | negative sign
-ipossignposn | positive sign position
-inegsignposn | negative sign position
-ipossymprecedes | mon sym precedes pos amt
-ipossepbyspace | mon sym sep by space from pos amt
-inegsymprecedes | mon sym precedes neg amt
-inegsepbyspace | mon sym sep by space from neg amt
-fontsignature | font signature
-siso639langname | ISO language abbreviation
-siso3166ctryname | ISO country name abbreviation
-idefaultebcdiccodepage | default ebcdic code page
-ipapersize | 1 = letter, 5 = legal, 8 = a3, 9 = a4
-sengcurrname | english name of currency
-snativecurrname | native name of currency
-syearmonth | year month format string
-ssortname | sort name
-idigitsubstitution | 0 = context, 1 = none, 2 = national

get_system_default_langid
Returns the default language identifier for the system.
get_system_default_lcid
Returns the default locale identifier for the system.
get_system_ui_langid
Returns the language identifier for the system default UI language.
get_user_default_langid
Returns the default user language identifier.
get_user_default_lcid
Returns the default user-locale identifier.
get_user_ui_langid
Returns the language identifier for the user's UI language.
map_code_page_to_name CODEPAGENUM
Returns the name of the code page identified by CODEPAGENUM.
map_langid_to_name LANGID
Returns the name of the language identified by LANGID.

COPYRIGHT

Copyright © 2005-2009 Ashok P. Nadkarni


Printers - Printers

Printers

Printer management

SYNOPSIS

package require twapi

enumerate_printers ?-location LOCATION?
printer_properties_dialog PRINTERNAME ?options?

DESCRIPTION

This module provides commands related to Windows printer management.

Printer Management

The command enumerate_printers returns all the printers on the system.

The command printer_properties_dialog displays the shell property sheet dialog for a printer.

Commands

enumerate_printers ?-location LOCATION?
Returns information about the printers on the system. The data is returned as a list of sublists. Each sublist corresponds to a printer and is a keyed list with the following fields:

name | The following value is the name of the printer.
server | The following value is the server on which the printer resides.
attrs | The following value is a list of attributes for the printer. This is a list of zero or more symbols from the following list: queued, direct, default, shared, network, hidden, local, enabledevq, keepprintedjobs, docompletefirst, workoffline, enablebidi, rawonly, published, fax, ts. Refer to the Windows SDK documentation for the meaning of these attributes.
LOCATION may be one of all (default), local or remote depending on whether all printers, local printers or remote printers are to be included in the returned list.

printer_properties_dialog PRINTERNAME ?options?
Displays the shell property dialog for the specified printer. The following options may be specified:

-hwin HWIN | If specified, HWIN is the handle to the window to be used as the parent for the dialog.
-page PAGENAME | Specifies the name of the property sheet page to be displayed. If unspecified, the default page is displayed.

COPYRIGHT

Copyright © 2006-2009 Ashok P. Nadkarni


Device management - Device management

Device management

Commands related to devices and device interfaces

SYNOPSIS

package require twapi

device_ioctl DEVICEHANDLE IOCTLCODE
start_device_notifier SCRIPT ?-deviceinterface DEVICEINTERFACE? ?-handle DEVICEHANDLE?
stop_device_notifier MONITORID

DESCRIPTION

This package provides procedures related to device information and management in Windows operating systems.

Device ioctls

The device_ioctl command provides thin wrapper around the DeviceIoControl Win32 function. This allows for device specific control commands to be issued to devices. You will need to refer to the Windows SDK documentation for specifics of the ioctls supported by various devices.

Device notifications

Device notifications are generated by Windows to inform applications about changes in device configurations as well as related events. For example, notifications can be used by an application to learn about media change in CD-ROM drives, plugging in of a USB device, mounting a remote share and so on. These notifications allow applications to save any changes and release resources as appropriate.

Notifications are also used by the system to inform applications about pending changes giving them the chance to cancel them.

TWAPI delivers device notifications through callback scripts registered by the application through the start_device_notifier command. Applications must specify the device or device interface class for which they wish to receive notifications and the corresponding script to be invoked to receive them.

Commands

device_ioctl DEVICEHANDLE IOCTLCODE
This is a thin wrapper around the Win32 DeviceIoControl function. Primary role of the wrapper is to do automatic output buffer management for the caller. DEVICEHANDLE, usually obtained through create_file, is a handle to the device of interest. IOCTLCODE is the IOCTL code to be sent to the device. The command returns the result as a Tcl binary value that should in general be parsed with the Tcl binary scan command.

start_device_notifier SCRIPT ?-deviceinterface DEVICEINTERFACE? ?-handle DEVICEHANDLE?
Registers SCRIPT to be invoked when the events are generated from a specified device class or device.

The command creates a new notifier and returns its identifier. When no longer interested in the specified changes, the returned identifier should be passed to stop_device_notifier to stop the notifications and release associated resources.

If no additional options were specified to the command, or if the -deviceinterface option was specified with DEVICEINTERFACE as an empty string, all device interfaces are monitored. If DEVICEINTERFACE is one of the keywords port or volume, then all ports and all volumes respectively are monitored. Otherwise, DEVICEINTERFACE must be the GUID for a particular device interface class, and only that interface class is monitored. Refer to the Windows SDK for a list of GUIDs for various device interface classes.

If the -handle option is specified, DEVICEHANDLE must be a handle to a resource on the device obtained through either create_file or get_tcl_channel_handle. In this case, only event notifications from that particular device are passed to the callback script.

At most one of the options -deviceinterface and -handle can be specified.

The callback SCRIPT is invoked with additional arguments. The first argument is the id of the notifier that was returned by this command. The second argument is the event notification type and may be followed by additional arguments specific to the type.

For compatibility with future releases, the callback script should ignore notification types not listed below. For the same reason, it should also ignore any additional arguments or unexpected values for listed arguments.

Certain event types require the callback script to return a value. These are noted below.

The notification type and the corresponding arguments are shown in the table below. The symbols match exactly the DBT_* symbols defined in the Windows SDK except for the character case and prefix. For example, devicearrival corresponds to DBT_DEVICEARRIVAL. More detail about each event can be obtained by looking at the SDK documentation for the corresponding symbol.

configchangecanceled | A request to change the current dock/undock device configuration was canceled. No additional arguments are present.
configchanged | The current device configuration has changed due to docking or undocking. No additional arguments are present.
customevent | A custom event defined by a driver. An additional argument may be present if the notifier was created with a -devicehandle option. This provides more detail on the event and has one of the following values: io_volume_change, io_volume_dismount, io_volume_dismount_failed, io_volume_mount, io_volume_lock, io_volume_lock_failed, io_volume_unlock, io_volume_name_change, io_volume_physical_configuration_change, io_volume_device_interface, io_media_arrival, io_media_removal, io_device_becoming_ready, io_device_external_request, io_media_eject_request, io_drive_requires_cleaning, io_tape_erase, io_disk_layout_change. Refer to the Windows SDK and DDK for more information on these.
devicearrival A new device or media has become available. The first additional argument is one of deviceinterface, handle, port or volume depending on source of the notification.

If this first argument in deviceinterface, (ie. device interfaces are being monitored (DEVICEINTERFACE is unspecified, an empty string, or a device interface GUID), it is followed by the device interface class GUID for the new device interface, and the device interface class name.

If the value is handle, two additional arguments may be present containing the internal device and notification handles. These should be treated as opaque.

If the value is port, one additional argument, the name of the port, may be present.

If the value is volume, the first additional argument is a list of drive letters corresponding to the new detected volumes (note there may be more than one). This is followed by a list of attributes. If the list includes mediachange, it indicates that new media was inserted (e.g. a CD-ROM); otherwise, it indicates a new physical device (e.g. a USB pen drive). If the list includes networkvolume, it indicates the new volume is accessed over the network.
devicequeryremove Request permission to remove a device. The application can deny the request by returning the string deny. Any other value will be treated as an allow. It is important that the script return an answer in prompt fashion. Any significant processing should be queued for later.

The arguments are the same as those for devicearrival when the device source type is handle.

Note this notification is only delivered when the -handle option is used. The application can therefore easily use the notifier id to associate the notification with a specific device. If the callback script returns anything other than deny, it should first close all open handles on the device, including the one passed as the argument value for the -handle option. Otherwise, the device removal will fail.
devicequeryremovefailed | A request to remove a device was canceled, either because an application denied it or there were open handles to the device. Additional arguments are the same as devicequeryremove.
deviceremovecomplete | Removal of a device or media has been completed. For physical devices this means the device has been physically disconnected. For volumes, this indicates the volume has been dismounted. Additional arguments are identical to those of devicearrival.
deviceremovepending | A device is being removed and not available. Additional arguments are identical to those of devicearrival.
devicetypespecific | An event specific to the type of device. Additional arguments are identical to those of devicearrival.
devnodes_changed | The system device tree has been modified. Windows does not provide any additional detail about the change and it is up to the application to examine the device tree components of interest.
querychangeconfig | Request to change the current dock/undock configuration. The application can allow or deny the request. The command has no additional arguments. See devicequeryremove for more detail on how the script should respond.
userdefined | A user defined event sent by an application using BroadcaseSystemMessage. An additional argument specifies the name of the event (vendor defined).

stop_device_notifier MONITORID
Cancels monitoring of device changes. MONITORID which must be an identifier previously returned by start_device_notifier.

COPYRIGHT

Copyright © 2008 Ashok P. Nadkarni


Power management - Power management

Power management

Power management

SYNOPSIS

package require twapi

get_device_power_state DEVICEHANDLE
get_power_status
SetThreadExecutionState EXECUTIONSTATE
start_power_monitor SCRIPT
stop_power_monitor POWER_ID
suspend_system ?options?

DESCRIPTION

This module provides commands related to power management in a Windows system.

Overview

The command suspend_system may be used to put the system in stand by or hibernate states. You can prevent the system from being suspended due to inactivity through the SetThreadExecutionState command.

The current state of the power subsystem, including battery status, can be obtained through the get_power_status command. The state of an individual device can be obtained through the get_device_power_state command.

Changes in the power subsystem state can be monitored through the start_power_monitor and stop_power_monitor.

Commands

get_device_power_state DEVICEHANDLE
Returns 1 if the device indicated by DEVICEHANDLE is fully powered up and 0 if it is in a low-power state. DEVICEHANDLE is a handle to the device or to an object on the device. For example, it can be the handle returned by a get_tcl_channel_handle command corresponding to a Tcl file handle.

DEVICEHANDLE must not be a handle to a display device.
get_power_status
Returns a keyed list containing information about the state of the power system. The list includes the fields in the table below.

-acstatus | Indicates the state of the AC power. May have the values on, off or unknown.
-batterystate | Indicates the state of the battery charge. May be critical, low, high or unknown.
-batterycharging | Indicates whether the battery is being charged. May have the values true, false or unknown.
-batterylifepercent | Indicates the percentage of the full battery life remaining or has the value unknown.
-batterylifetime | Indicates the remaining battery life time in seconds, if known, or has the value unknown.
-batteryfulllifetime | Indicates the number of seconds of battery life when it is full, or has the value unknown.

SetThreadExecutionState EXECUTIONSTATE
Refer to the Windows SDK documentation for details.
start_power_monitor SCRIPT
Begins monitoring of power state changes. SCRIPT will be invoked when the state of the power subsystem changes, for example, when the system switches to battery power.

The command returns a handle. When no longer required, this handle must be passed to the command stop_power_monitor.

Multiple monitoring scripts may be active at the same time. However, all returned handles must be passed to stop_power_monitor. before the application exits.

The callback script is invoked with two additional arguments. The first argument indicates the type of event and has one of the values in the table below.

apmbatterylow | Indicates that the system battery is low.
apmoemevent | Indicates an OEM-defined event.
apmpowerstatuschange | Indicates a change in the power status. Details may be obtained by calling get_power_status.
apmquerysuspendfailed | Indicates that a query to suspend the computer was denied.
apmresumeautomatic | Indicates that the system has woken up to handle an event.
apmresumecritical | Indicates the system has woken up after a critical system suspension (e.g. due to very low battery) where it was not possible to notify all applications before the suspension.
apmresumesuspend | Indicates that the system has resumed normal operation after a suspension.
apmsuspend | Indicates the system is about to be suspended and applications should save state and data if necessary.
The second argument passed to the callback is only meaningful when the event is apmoemevent. The value of the argument is an OEM-defined event code.

stop_power_monitor POWER_ID
Stops a previously registered script that monitors the power subsystem. POWER_ID is monitoring handle previously returned by start_power_monitor.
suspend_system ?options?
Places the system in a stand by or hibernate state. The command takes the following options:

-state STATE | STATE must be one of standby (default) or hibernate depending on whether the state into which the system is to be placed.
-force BOOLEAN | If false (default), the system sends a PBT_ATMQUERYSUSPEND message to all applications before placing the system in stand by or hibernate states. If this option is specified as true, the message is not sent and the system is immediately placed into the appropriate state.
-disablewakeevents BOOLEAN | If false (default), system wake events remain enabled. If true they are disabled.

COPYRIGHT

Copyright © 2008 Ashok P. Nadkarni


Error generation and handling - TWAPI error generation and handling

Error generation and handling

TWAPI error generation and handling

SYNOPSIS

map_windows_error ERRORCODE
try SCRIPT ?onerror ERRORPATTERN ERRORSCRIPT?... ?finally FINALSCRIPT?
win32_error WINERROR ?MESSAGE?

DESCRIPTION

This module provides various facilities for generating and handing errors and Tcl exceptions.

Error generation

TWAPI generates Tcl exceptions when errors are encountered. Information pertaining to the error is stored in Tcl global variables as with any standard Tcl errors. The global variable errorInfo contains a traceback of the Tcl stack when the error occured. The global errorCode contains a list with additional information about the error. The first element is the error class and determines the format of the rest of the list. This may take one of the following values:

TWAPI_WIN32 | This error class corresponds to Windows error codes. The second element of the list is the integer Windows error code. The third element is the corresponding localized text string describing the error. The fourth element is optional and its format is dependent on the specific error code. The command win32_error can be used to generate an error in this format.
TWAPI | This error class is used for non-Windows related errors, for example invalid options to commands. The format is similar to that of TWAPI_WIN32 except that the error code is an internal TWAPI error code and the text is not localized.

Error handling

Several TWAPI commands pertain to error handling. map_windows_error returns the text description of an operating system error code.

try provides exception handling with finalization features.

Commands

map_windows_error ERRORCODE
Returns the text string corresponding to a Windows error code.
try SCRIPT ?onerror ERRORPATTERN ERRORSCRIPT?... ?finally FINALSCRIPT?
The command executes SCRIPT in the caller's context. If the script completes without generating any Tcl exceptions, the command executes the script FINALSCRIPT if specified. The result of the command is the result of SCRIPT.

If SCRIPT generates any errors, the command matches the Tcl global ::errorCode variable against each specified ERRORPATTERN in turn. When the first match is found, the corresponding ERRORSCRIPT is executed. Then FINALSCRIPT is executed if specified. The return value from the command is the result of the executed ERRORSCRIPT script.

If the none of the ERRORPATTERN arguments match when an error occurs in SCRIPT, the command executes FINALSCRIPT if specified, and then regenerates the original error.

Each ERRORPATTERN should be a list and is matched against the first (facility) and second (code) elements of ::errorCode. If ERRORPATTERN is empty, it matches any value of ::errorCode. If ERRORPATTERN contains only one element, it is matched against the first element of ::errorCode with the second field of ::errorCode not used for matching. When matching against the second element of ::errorCode, first a exact string match is tried and if that fails, an integer match is tried if both operands being compared are valid integers.

When a ERRORSCRIPT script is run, the global Tcl variables ::errorCode, ::errorInfo are automatically brought into scope without needing a global statement in the script and contain the values set when SCRIPT generated the error. In addition, the variable ::errorResult is set to the error message set by the original error. This behavior is similar to the try_eval command from TclX.
win32_error WINERROR ?MESSAGE?
Generates a Tcl exception corresponding to the Windows error code WINERROR. MESSAGE may be specified as the error message in which case the system error message for WINERROR is appended to it.

COPYRIGHT

Copyright © 2003-2009 Ashok P. Nadkarni


Miscellaneous - Miscellaneous commands

Miscellaneous

Various TWAPI ancillary commands

SYNOPSIS

package require twapi

expand_environment_strings STRING
export_public_commands
format_message ?options?
get_command_line
get_command_line_args COMMANDLINE
get_version ?-patchlevel?
import_commands
large_system_time_to_secs_since_1970 SYSTEMTIMEVALUE ?BOOLEAN?
large_system_time_to_timelist SYSTEMTIMEVALUE
parseargs ARGLISTVAR OPTLIST ?-ignoreunknown? ?-nulldefault? ?-maxleftover MAXLEFTOVER?
secs_since_1970_to_large_system_time SECONDS
timelist_to_large_system_time TIMELIST

DESCRIPTION

This module provides miscellaneous utility commands.

get_version returns TWAPI version information. export_public_commands and import_commands enable export and import of commands defined in the TWAPI namespace. parseargs parses an argument list based on specified options. get_command_line retrieves the command line passed to the process. get_command_line_args parses a command line using Windows conventions. The command expand_environment_strings replaces environment variables in a string with their values. format_message formats a operating system or application message.

Commands

expand_environment_strings STRING
Returns the string formed by replacing all environment variable references in STRING with their values. Environment variable references are in the form %ENVIRONMENTVAR%. References to undefined environment variables are not replaced.
export_public_commands
Export public commands in the twapi:: namespace. The commands in the twapi:: namespace are not exported by default.
format_message ?options?
Formats and returns a message string based on a format string. The format string may be directly supplied, obtained from a loaded library or module, or the system message tables. The format string may contain format insert specifiers of the form %N where N is a number between 1 and 99. The format specifier is replaced by the corresponding positional parameter. The format specifier %0 is treated specially as indicating that a newline character is not to be appended to the result. See FormatMessage in the Windows SDK for more details regarding this command including format specifiers. The command takes the following options:

-module MODULE | Specifies that the format string is to be loaded from the module identified by MODULE. MODULE may either be a handle returned from a command such as load_library or the path to a DLL. If this option is specified, options -messageid and -langid must also be specified. This option cannot be used with the -fmtstring option.
-fmtstring FORMATSTRING | Specifies that FORMATSTRING should be used as the format string for the message. Cannot be used with the -module option.
-messageid MESSAGEID | Specifies the message identifier of the format string. This option cannot be used with the -fmtstring option.
-langid LANGID | Specifies the language identifier to be used in constructing the message. This option cannot be used with the -fmtstring option.
-includesystem | Specifies that the system message tables should also be searched in addition to the message tables in the module specified by -module. This option cannot be used with the -fmtstring option.
-params PARAMLIST | Specifies a list of positional parameters that are to be used to replace the %N format insert sequences in the format string. If the number of parameters does not match the number of escape sequences, a Tcl exception may be generated unless the -ignoreinserterrors is specified.
-ignoreinserterrors | Normally, a Tcl exception is raised if the number of parameters specified through the -params option does not match the %N specifiers in the format string. If this option is specified, instead of generating an exception, the command behaves as though -ignoreinserts was specified.
-ignoreinserts | If specified, the %N format insert sequences are not replaced in the returned string.
-width MAXLINEWIDTH | By default, the returned string contains the same line breaks as in the original format string. The -width option may be used to control the maximum line width in the created message. If MAXLINEWIDTH is between 1 and 255, the command will insert line end characters at appropriate points in the message. In this case, line end characters in the original message are ignored. However, hard coded line end characters, specified as %n in the format string are kept. A negative value of MAXLINEWIDTH also ignores line end characters while keeping the hard coded %n line end specifiers, but does not insert and line end characters to limit the line length. A value of 0 for MAXLINEWIDTH is identical to the default behaviour.

get_command_line
Returns the command line of the current process. This may be passed to the get_command_line_args function to split the line into arguments.
get_command_line_args COMMANDLINE
Parses COMMANDLINE as per Windows command line conventions and returns a list of the parsed arguments. The main advantage of this over using the argv and argv0 variables in tclsh and wish is that this call will correctly handle Unicode arguments.
get_version ?-patchlevel?
Without any arguments, the command returns the major/minor TWAPI version number in the form MAJOR.MINOR. If the option -patchlevel is specified, the returned string includes patchlevel and release information similar to the Tcl info patchlevel command, for example, 1.0.2 for final release of version 1.0 patch 2, 1.0b3 for the third beta release of version 1.0 and 1.0a3 for the third alpha release of version 1.0.
import_commands
Imports all public commands in the twapi:: namespace into the caller's namespace.
large_system_time_to_secs_since_1970 SYSTEMTIMEVALUE ?BOOLEAN?
Some Windows functions return time as the number of 100 nanosecond units since Jan 1, 1601. The command converts such time values to seconds since the epoch Jan 1, 1970. If BOOLEAN is false (default), an integral number of seconds is returned. Otherwise, the fractional part is also returned.
large_system_time_to_timelist SYSTEMTIMEVALUE
Some Windows functions return time as the number of 100 nanosecond units since Jan 1, 1601. The command converts such time values to a list of 7 elements representing the year, month, day, hour, minutes, seconds and milliseconds.
parseargs ARGLISTVAR OPTLIST ?-ignoreunknown? ?-nulldefault? ?-maxleftover MAXLEFTOVER?
Parses the options specified in a list of arguments. ARGLISTVAR is the name of a variable in the caller's scope that contains a list of arguments. Option names are case-sensitive.

OPTLIST specifies the valid options allowed and is list of option specifiers. Each option specifier is a list of up to 3 elements and takes the following form:

OPTNAME?.OPTTYPE? ?DEFAULTVALUE ?VALIDVALUELIST??

OPTNAME is the name of the option (without a leading -) and is required. OPTTYPE should be separated from the name with a . and specifies the type of the option. It must have one of the following values: arg, bool, int, or switch. In the first three cases, the argument following the option is taken as the value of the option and must be of an appropriate type: an arbitrary string, a boolean value (0, 1, off, on, false, true) or an integer respectively. If the option type is switch, or is not specified at all, then the option is not associated with any value and is treated as a binary switch.

DEFAULTVALUE, specifies a default value to be assumed for the option if it is not present in ARGLISTVAR. This is ignored for options of type switch.

If VALIDVALUELIST is specified, it is treated as a list of allowed values for the option. If an option's value is not in the list, the command will return an error. VALIDVALUELIST is ignored if the option type is bool or switch.

The command returns a list of the form OPTION VALUE OPTION VALUE.... If the -nulldefault option is not present, only options that are present in ARGLISTVAR, or have a default value specified, or are of type switch are included in the returned result. If the -nulldefault option is present, then the returned list also includes values for options that are not present - 0 for options of type int and bool, and an empty string for arguments of type arg.

As a side effect, the variable ARGLISTVAR is modified to remove the parsed options and associated values. If the -maxleftover option is specified, the command will raise a Tcl error if the number of arguments left over after parsing the options is more than MAXLEFTOVER.

The command will normally generate a Tcl error if the arguments include an unknown option (an argument that begins with a - character and is not in OPTLIST). If the -ignoreunknown option is specified to the command, unknown options in ARGLISTVAR are ignored instead of an error being generated and are not removed from ARGLISTVAR.
secs_since_1970_to_large_system_time SECONDS
This command converts SECONDS which is the number of seconds since the epoch Jan 1, 1970 to the number of 100 nanoseconds since Jan 1, 1601.
timelist_to_large_system_time TIMELIST
Converts TIMELIST to the number of 100 nanoseconds since Jan 1, 1601. TIMELIST must be a list of 7 elements representing the year, month, day, hour, minutes, seconds and milliseconds.

COPYRIGHT

Copyright © 2004-2009 Ashok P. Nadkarni


Examples - Tcl Windows API extension examples

Examples

Tcl Windows API usage examples

DESCRIPTION

The examples in this section are broken out by area. Note that many of these will require administrative privileges to run. For clarity, the examples do minimal validation and error checking.

The examples may be run by passing to a Tcl interpreter. For example,

tclsh checkservicepack.example 3

will print whether service pack 3 is installed.

The examples are broken up into the following categories: System information, File monitoring, Window management, Simulating user input, Playing sounds, Disk configuration, Network shares, Processes and threads, Windows services, Users and groups, Access control, Clipboard access, Network configuration, Event log and Performance monitoring.

System information

Print OS version and configuration

Verify if Terminal Services are present

Verify a service pack is installed

Print the NETBIOS name of the computer

File monitoring

Monitor changes in a directory

Window management

Minimize all windows for a given application

Hide all windows for a given application

Show all windows for a given application

Move a window to the top left corner of the screen

Remove the title bar from a window

Bring a specified window to the foreground

Keep a window on top of all other windows

Change the caption of a window

Simulating user input

Send text string to a specified window

Send menu shortcut keys to a specified window

Open the system menu of the specified window with the mouse

Start a program when a hotkey is pressed

Example: Draw a square in MS Paint using the mouse

Playing sounds

Generate a continuous tone on the system speaker

Play a system sound

Play a system sound continuously for 10 seconds

Play a WAV sound file

Disk configuration

List all the drives on the system

List all remote drives on the system

List all fixed drives that have less than 10% free space

Modify the volume label for a drive

Check if the given drive supports Unicode file names

Check if the given drive has sufficient free space

Network shares

Export a file share that can be connected to from remote clients

Map a drive to a file share exported from a server

List all network shares exported on the system

List all network shares to which the system is connected

Show information related to a mapped drive

Processes and threads

Ask all invocations of a given program to gracefully exit

Forcibly terminate all invocations of a given program

Show the user account under which each process is running

Show the DLL's loaded in a process

Windows services

Show all Windows services that are currently running

Show all Windows services that start automatically at boot time

Stop and restart a Windows service

Change a service configuration to start under a specific user account

Show the services that depend on the specified service

Show the services that the specified service depends on

Install a service

Remove a service

Users and groups

List the users on a system

List the group membership for a user

List the users in a group

Show properties of a user account

Create a new user account

Delete a user account

Add a user to a local group

Remove a user from a local group

Add a local group account

Delete a local group account

Access control

Protect a file from access by a specific user

Show the access control entries on the specified file

Clipboard access

Copy contents of the clipboard to standard output

Copy standard input to the clipboard

Transform the data in the clipboard

Get HTML format data from the clipboard

Network configuration

Show network interfaces

Map an IP address to a physical address

Event log

Dump event log to standard output

Performance monitoring

Chart CPU utilization

Show virtual memory statistics usage

Show network statistics

COPYRIGHT

Copyright © 2003, Ashok P. Nadkarni


Version History - TWAPI Version History

Version History

Tcl Windows API extension version history

DESCRIPTION

Summarizes the list of changes for each version of TWAPI.

Version 2.2

  • This will be the last version of TWAPI to support Windows 2000 and Tcl 8.4. Later versions will require Windows XP and Tcl 8.5 as minimum requirements.
  • Added commands comobj_object, progid_to_clsid, and clsid_to_progid.
  • Device notifications significantly enhanced. New commands start_device_notifier and stop_device_notifier for handling device event notifications. INCOMPATIBLE CHANGE Commands start_device_change_monitor and stop_device_change_monitor are no longer available.
  • Support for Tcl-based Windows services enhanced to handle additional control signals and system events.
  • Added GetSystemMetrics and GetSystemWow64Directory, but no Tcl wrappers.

Version 2.1

  • Built desktop and server specific TWAPI packages containing a subset of the TWAPI commands with a smaller footprint. Reduced footprint of full TWAPI package as well.
  • Added recycle_file.
  • Added error notifications to begin_filesystem_monitor.
  • Added options -foundcodepage, -foundlangid and -datetime to get_file_version_resource.
  • Added Wow64EnableWow64FsRedirection, Wow64DisableWow64FsRedirection, and Wow64RevertWow64FsRedirection.
  • Added new formats to get_current_user.
  • Added SHChangeNotify, CryptAcquireContext, CryptReleaseContext, and CryptGenRandom. No Tcl wrappers for these.

Version 2.0

  • INCOMPATIBLE CHANGE Windows NT 4.0 is no longer a supported platform.
  • Added support for distribution as a single file Tcl module for Tcl 8.5.
  • Added support for Tcl-based Windows services.
  • Added Microsoft Windows Installer interface support.
  • Added SSPI support (experimental).
  • Added Power Management module.
  • Added start_device_change_monitor and stop_device_change_monitor.
  • Added start_clipboard_monitor and stop_clipboard_monitor.
  • Added -patterns option to begin_filesystem_monitor.
  • Added get_priority_class, set_priority_class, get_thread_relative_priority and set_thread_relative_priority.
  • Added commands get_outgoing_interface, get_route and get_routing_table.
  • Added commands get_display_devices, get_display_monitors, get_display_monitor_from_window, get_display_monitor_from_point, get_display_monitor_from_rect, get_display_monitor_info.
  • Added commands find_physical_disks and get_physical_disk_info.
  • Added create_file.
  • Added device_ioctl.
  • Added -extents option to get_volume_info.
  • Added -isnull subcommand to COM objects.
  • Added get_input_idle_time.
  • Added large_system_time_to_timelist and timelist_to_large_system_time.
  • Added -modulename, -modulepath, -bindtime options to get_tcp_connections and get_udp_connections. Modified -matchremoteaddr and -matchlocaladdr options to allow DNS names and accept multiple addresses.
  • Added -messageonlywindow option to find_windows.
  • Added options -noexist and -noaccess to get_thread_info. INCOMPATIBLE CHANGE The command no longer raises an exception if a thread does not exist or cannot be accessed.
  • Additional performance optimizations.

Version 1.1

  • Added enhanced Windows task scheduler interface.
  • Added commands find_lm_sessions, end_lm_sessions, get_lm_session_info and find_lm_connections dealing with Lan Manager sessions and connections.
  • Added commands find_lm_open_files, close_lm_open_file and get_lm_open_file_info dealing with files opened in Lan Manager sessions.
  • Added find_domain_controller command.
  • Added get_file_times and set_file_times dealing with file timestamps.
  • Enhanced get_process_info and get_thread_info return additional process and thread information.
  • Enhanced get_processor_info to return additional processor information.
  • Enhanced get_memory_info to return additional swap file information.
  • Replaced Windows performance counter calls with native Win32 calls resulting in almost two orders of magnitude better performance in retrieving process, thread and system information.
  • Added get_system_time.
  • Added secs_since_1970_to_large_system_time.
  • Added variant_time_to_timelist and timelist_to_variant_time.
  • Added -handle option to get_resource_security_descriptor and options -handle, -unprotect_dacl and -unprotect_sacl to set_resource_security_descriptor.
  • Added -logonsession option to get_process_ids.
  • Include process id and attribute information (if available) in data returned by get_service_status and get_multiple_service_status.
  • INCOMPATIBLE CHANGE Changed default value of new_share option -secd.
  • Bug fixes.

Version 1.0

  • Added read_inifile_section and read_inifile_section_names.
  • INCOMPATIBLE CHANGE Removed unsupported commands get_open_handles and get_open_handle_pids. They used undocumented system functions and caused some nasty behaviour with the latest service packs.
  • Added option -stdchannels to create_process.

Version 1.0 Beta

  • INCOMPATIBLE CHANGE The error class stored in errorCode when Windows encounters an error has changed. In V0.9 and before, the error class was WINDOWS. To prevent clashes with other extensions, the error class now used is TWAPI_WIN32. Code that traps errors using pattern matching in try or otherwise parses errorCode will need to be modified accordingly.
  • Added COM module.
  • Added get_system_parameters_info and set_system_parameters_info.
  • Added get_file_version_resource.
  • Added map_langid_to_name.

Version 0.9

Note: only bug fixes that are incompatible with previous releases are mentioned here.

  • INCOMPATIBLE CHANGE Remote file shares now have type file instead of disk for consistency with local file shares.
  • Added write_shortcut and read_shortcut.
  • Added write_url_shortcut, read_url_shortcut and invoke_url_shortcut.
  • Added get_primary_domain_info.
  • Added commands address_to_hostname, hostname_to_address, port_to_service and service_to_port.
  • Added command get_system_info.
  • Added get_computer_name.
  • Added -logonsession option to get_process_info.
  • Added Windows 2000 support for shell_object_properties_dialog, volume_properties_dialog, file_properties_dialog, printer_properties_dialog.
  • Added -user option to get_process_ids.
  • Added get_user_local_groups_recursive.
  • Added command get_security_descriptor_control.
  • Added commands get_ace_text and get_security_descriptor_text.

Version 0.8

  • INCOMPATIBLE CHANGE Changed to require at least Service Pack 4 on Windows NT 4.0. The extension will no longer load on otherwise. This was required to support the LSA related functions.
  • Added commands find_logon_sessions and get_logon_session_info for dealing with logon sessions.
  • Added commands to retrieve information related to Windows shell Themes.
  • Added commands get_global_group_info and get_local_group_info.
  • Added commands get_tcp_connections and get_udp_connections and terminate_tcp_connections.
  • Added LSA related commands add_account_rights, remove_account_rights, find_accounts_with_right, get_accounts_with_rights,
  • Modified commands delete_user, delete_global_group and delete_local_group to remove account rights before deleting the account.
  • Added enumerate_printers.
  • Added shell_object_properties_dialog, volume_properties_dialog, file_properties_dialog, printer_properties_dialog.
  • Added get_system_uptime.
  • Added large_system_time_to_secs.
  • Added configure_window_titlebar.
  • Added get_client_share_info. get_mapped_share_info is now deprecated.
  • Added suspend_system.
  • Added get_privilege_description,
  • Added option -description to get_service_configuration.
  • Added options -noaccess and -noexist to commands get_process_info, get_process_parent and get_process_commandline. INCOMPATIBLE CHANGE These commands no longer raise a Tcl error if the process does not exist or if access is denied to the process.
  • Added command map_code_page_to_name
  • Added option -sid to get_user_account_info.
  • Added commands is_system_pid and is_idle_pid.
  • Added commands extract_primary_langid and extract_sublanguage_langid.
  • Significant improvement in retrieval of performance related data.
  • INCOMPATIBLE CHANGE The format of return value of the get_token_privileges command has changed when the -all option is specified. The value returned by the -privileges option of the get_process_info has changed accordingly.
  • INCOMPATIBLE CHANGE get_drive_type now returns invalid as the drive type for non-existent drives instead of generating an error.

Version 0.7

  • Added high level Tcl interface for console access to replace direct Win32 API calls.
  • Added volume and mount point related commands (see disk.html)
  • INCOMPATIBLE CHANGE Enhanced begin_filesystem_monitor to return more detail.
  • Enhanced get_service_status to return the process id of the service.
  • For consistency, renamed get_drive_info to get_volume_info and get_logical_drives to find_logical_drives. Older names will still work.
  • Miscellaneous bug fixes.

Version 0.6

  • Added commands begin_filesystem_monitor and end_filesystem_monitor for monitoring file system changes.
  • Added module Desktops and Window Stations.
  • Added module Internationalization.
  • Added command get_shell_folder.
  • Added command get_desktop_workarea.
  • Added commands get_desktop_wallpaper and set_desktop_wallpaper.

Version 0.5

  • Removed dependencies on the external cmdline and TclExcept packages. These are no longer required.
  • Added the Task Scheduler module
  • Added duplicate_handle
  • Added get_primary_domain_controller
  • Added options -groups, -primarygroup, -user and -privileges to commands get_process_info and get_thread_info
  • Added parseargs for option parsing
  • Added get_process_parent
  • Added get_process_commandline and option -commandline to get_process_info
  • Added command get_process_exit_code
  • Added command get_display_size
  • Added commands get_command_line and get_command_line_args
  • Added try command
  • Added get_version to get TWAPI version information
  • Added eval_with_privileges, enable_privileges and disable_privileges
  • Added -sync option to move_window and resize_window commands.
  • INCOMPATIBLE CHANGE Return values from enable_token_privileges, disable_token_privileges and disable_all_token_privileges have changed.
  • INCOMPATIBLE CHANGE Command arguments for open_process_token and open_thread_token have changed.
  • INCOMPATIBLE CHANGE stop_sound usage has changed.
  • INCOMPATIBLE CHANGE Usage and semantics of the -toplevel option for find_windows has changed.
  • INCOMPATIBLE CHANGE Removed -dpcbypassrate and -apcbypassrate options from command get_processor_info as they are not present on XP and Windows 2003.
  • Greatly expanded test coverage.

Version 0.4

  • Added support to be sourced as a single file Starkit
  • Added the Network configuration module
  • Added the Clipboard module
  • Added get_memory_info to retrieve system physical and virtual memory information
  • Added get_open_handle_pids to retrieve a list of processes that have an open handle to a resource.
  • Added option -handles to get_process_info to retrieve a list of open handles in a process.
  • Added get_open_handles to retrieve information about open handles in the system.
  • Added -device option to get_drive_info command
  • INCOMPATIBLE CHANGE Changed set_drive_volumename to set_drive_label and changed option -volumename of get_drive_info to -label. This is to avoid future confusion with logical volumes as defined by Windows.
  • Added options -processormodel, -processorname and -processorspeed to get_processor_info.
  • INCOMPATIBLE CHANGE Changed the arguments to commands get_process_handle and get_thread_handle.
  • INCOMPATIBLE CHANGE Changed get_os_info to not return memory related information. get_memory_info provides a superset of the same information.
  • Documentation is now in Windows compiled help format with index and search.

Version 0.3

  • Added the Event log module
  • Added the Console module
  • Added register_hotkey and unregister_hotkey
  • Added create_process, get_process_handle and get_thread_handle
  • Added suspend_thread and resume_thread
  • Added shutdown_system and abort_system_shutdown
  • Added format_message and map_windows_error
  • Added logoff_user and lock_workstation
  • Added get_current_user
  • Added expand_environment_strings
  • Added load_library and free_library
  • Added get_processor_count and get_active_processor_mask
  • Enhanced get_os_info to return additional OS information
  • Enhanced get_processor_info to return additional processor information
  • Added commands read_inifile_key, write_inifile_key, delete_inifile_key and delete_inifile_section for manipulating INI files.
  • Added process_waiting_for_input
  • Added block_input
  • Added close_handles
  • Added get_tcl_channel_handle
  • Bug fixes to delete_share, close_window

Version 0.2

  • Added the Security module containing commands for user/group management, resource protection, access control, authorization and impersonation
  • Added the Network shares module containing commands for configuration of network shares
  • Added play_sound for basic audio playback
  • Added send_keys command (clone of Visual Basic SendKeys using same syntax) for generating keystrokes
  • Added find_windows
  • Added get_logical_drives
  • Added get_drive_type
  • Added set_drive_volumename
  • Added get_mouse_location
  • Added get_computer_netbios_name
  • INCOMPATIBLE CHANGE Changed parameters and return format for get_process_modules.
  • INCOMPATIBLE CHANGE Changed the -machine and -display_name options in the services module to -system and -displayname for consistency with other modules.
  • INCOMPATIBLE CHANGE Several commands that used to return multiple values in fieldname value format have been changed so that the fieldname matches the option specified to retrieve the field (to include the - prefix). These commands include get_device_drivers, get_process_info, get_disk_info, get_user_account_info, lookup_account_name
  • INCOMPATIBLE CHANGE get_service_configuration options and return format has changed.
  • INCOMPATIBLE CHANGE The return values from the commands start_service, stop_service, pause_service, resume_service and interrogate_service have changed. Moreover, start_service and stop_service will no longer throw an exception if the service is already running or stopped respectively.
  • Allow window styles to be expressed as symbols in addition to bitmasks
  • The commands start_service, stop_service, pause_service, resume_service now take an additional -wait option.

Version 0.1

  • Initial release

COPYRIGHT

Copyright © 2003-2009 Ashok P. Nadkarni