Expand description
Windows API and GUI in safe, idiomatic Rust.
Crate • GitHub • Docs (stable) • Docs (master branch) • Examples
WinSafe has:
- low-level Win32 API constants, functions and structs;
- high-level structs to build native Win32 GUI applications.
If you’re looking for a comprehensive Win32 coverage, take a look at winapi or windows crates, which are unsafe, but have everything.
Usage
Add the dependency in your Cargo.toml
:
[dependencies]
winsafe = { version = "0.0.13", features = [] }
Then you must enable the Cargo features you want to be included – these modules are named after native Windows DLL and library names, mostly.
The following Cargo features are available so far:
Feature | Description |
---|---|
advapi | Advapi32.dll, for Windows Registry |
comctl | ComCtl32.dll, for Common Controls |
comdlg | ComDlg32.dll, for the old Common Dialogs |
dshow | DirectShow |
gdi | Gdi32.dll, the Windows GDI |
gui | The WinSafe high-level GUI abstractions |
kernel | Kernel32.dll, all others will include it |
ktm | Ktmw32.dll, the Kernel Transaction Manager |
msimg | Msimg32.dll |
ole | OLE and basic COM support |
oleaut | OLE Automation |
shell | Shell32.dll and Shlwapi.dll, the COM-based Windows Shell |
user | User32.dll, the basic Windows GUI support |
uxtheme | UxTheme.dll, extended window theming |
version | Version.dll, to manipulate *.exe version info |
Note that a Cargo feature may depend on other features, which will be enabled automatically.
The GUI API
WinSafe features idiomatic bindings for the Win32 API, but on top of that,
it features a set of high-level GUI structs, which scaffolds the boilerplate
needed to build native Win32 GUI applications, event-oriented. Unless you’re
doing something really specific, these high-level wrappers are highly
recommended – you’ll usually start with the
WindowMain
.
One of the greatest strenghts of the GUI API is supporting the use of resource files, which can be created with a WYSIWYG resource editor.
GUI structs can be found in module gui
.
Native function calls
The best way to understand the idea behind WinSafe bindings is comparing them to the correspondent C code.
For example, take the following C code:
HWND hwnd = GetDesktopWindow();
SetFocus(hwnd);
This is equivalent to:
use winsafe::prelude::*;
use winsafe::HWND;
let hwnd = HWND::GetDesktopWindow();
hwnd.SetFocus();
Note how GetDesktopWindow
is a static method of HWND
, and
SetFocus
is an instance method
called directly upon hwnd
. All native handles (HWND
,
HDC
, HINSTANCE
, etc.) are structs,
thus:
- native Win32 functions that return a handle are static methods in WinSafe;
- native Win32 functions whose first parameter is a handle are instance methods.
Now this C code:
PostQuitMessage(0);
Is equivalent to:
use winsafe::prelude::*;
use winsafe::PostQuitMessage;
PostQuitMessage(0);
Since PostQuitMessage
is a free function, it’s
simply at the root of the crate.
Also note that some functions which require a cleanup routine – like
BeginPaint
, for example – will
return the resource wrapped in a guard, which will perform
the cleanup automatically. You’ll never have to manually call
EndPaint
.
Native constants
All native Win32 constants can be found in the co
module.
They’re all typed, what means that different constant types cannot be
mixed (unless you explicitly say so).
Technically, each constant type is simply a newtype with a couple implementations, including those allowing bitflag operations. Also, all constant values can be converted to its underlying integer type.
The name of the constant type is often its prefix. For example, constants of
MessageBox
function, like
MB_OKCANCEL
, belong to a type called MB
.
For example, take the following C code:
let hwnd = GetDesktopWindow();
MessageBox(hwnd, "Hello, world", "My hello", MB_OKCANCEL | MB_ICONINFORMATION);
This is equivalent to:
use winsafe::prelude::*;
use winsafe::{co::MB, HWND};
let hwnd = HWND::GetDesktopWindow();
hwnd.MessageBox("Hello, world", "Title", MB::OKCANCEL | MB::ICONINFORMATION)?;
The method MessageBox
, like most
functions that can return errors, will return
SysResult
, which can contain an
ERROR
constant.
Native structs
WinSafe implements native Win32 structs in a very restricted way. First off,
fields which control the size of the struct – often named cbSize
– are
private and automatically set when the struct is instantiated.
Pointer fields are also private, and they can be set and retrieved only
through getter and setter methods. In particular, when setting a string
pointer field, you need to pass a reference to a WString
buffer, which will keep the actual string contents.
For example, the following C code:
WNDCLASSEX wcx = {0};
wcx.cbSize = sizeof(WNDCLASSEX);
wcx.lpszClassName = "MY_WINDOW";
if (RegisterClassEx(&wcx) == 0) {
DWORD err = GetLastError();
// handle error...
}
Is equivalent to:
use winsafe::prelude::*;
use winsafe::{RegisterClassEx, WNDCLASSEX, WString};
let mut wcx = WNDCLASSEX::default();
let mut buf = WString::from_str("MY_WINDOW");
wcx.set_lpszClassName(Some(&mut buf));
if let Err(err) = RegisterClassEx(&wcx) {
// handle error...
}
Note how you don’t need to call GetLastError
to
retrieve the error code: it’s returned by the method itself in the
SysResult
.
Text encoding
Windows natively uses Unicode UTF-16.
WinSafe uses Unicode UTF-16 internally but exposes idiomatic UTF-8,
performing conversions automatically when needed, so you don’t have to worry
about OsString
or any low-level conversion.
However, there are cases where a string conversion is still needed, like
when dealing with native Win32 structs. In such cases, you can use the
WString
struct, which is also capable of working as a
buffer to receive text from Win32 calls.
Errors and result aliases
WinSafe declares a few
Result
aliases
which are returned by its functions and methods:
Alias | Error | Used for |
---|---|---|
SysResult | ERROR | Standard system errors. |
HrResult | HRESULT | COM errors. |
AnyResult | Box<dyn Error + Send + Sync> | Holding different error types. All other Result aliases can be converted into it. |
Utilities
Beyond the GUI API, WinSafe features a few high-level abstractions to deal with some particularly complex Win32 topics. Unless you need something specific, prefer using these over the raw, native calls:
Utility | Used for |
---|---|
Encoding | String encodings. |
File | File read/write and other operations. |
FileMapped | Memory-mapped file operations. |
Ini | Managing key/value pairs of a .ini file. |
path | File path operations. |
ResourceInfo | Retrieve embedded data from executables or DLLs. |
task_dlg | Various dialog prompts. |
WString | Managing native wide strings. |
Modules
gui
.res
file.
These files can be created with a WYSIWYG
resource editor.kernel
comctl
and ole
TaskDialogIndirect
and
HWND::TaskDialog
functions.Macros
u16
constants starting from the given value.Structs
user
ALTTABINFO
struct.dshow
AM_MEDIA_TYPE
struct.user
ATOM
returned by RegisterClassEx
.BITMAPFILEHEADER
struct.gdi
BITMAPINFO
struct.BITMAPINFOHEADER
struct.oleaut
comctl
BUTTON_IMAGELIST
struct.comctl
BUTTON_SPLITINFO
struct.BY_HANDLE_FILE_INFORMATION
struct.comdlg
CHOOSECOLOR
struct.COAUTHIDENTITY
struct.ole
COAUTHINFO
struct.comctl
COLORSCHEME
struct.user
COMBOBOXINFO
struct.shell
COMDLG_FILTERSPEC
struct.COMPAREITEMSTRUCT
struct.ole
COSERVERINFO
struct.user
CREATESTRUCT
struct.ole
comctl
DATETIMEPICKERINFO
struct.user
DELETEITEMSTRUCT
struct.user
DISPLAY_DEVICE
struct.user
DRAWITEMSTRUCT
struct.DVTARGETDEVICE
struct.comctl
EDITBALLOONTIP
struct.kernel
HFILE
handle, which provides file read/write
and other operations. It is closed automatically when the object goes out of
scope.kernel
HFILEMAP
handle, which provides
memory-mapped file operations, including read/write through slices. It is
closed automatically when the object goes out of scope.user
GUITHREADINFO
struct.user
kernel
HANDLE
.user
comctl
HDHITTESTINFO
struct.shell
user
kernel
HEAPLIST32
struct.kernel
HANDLE
.kernel
LPVOID
.kernel
HANDLE
.kernel
HANDLE
.comctl
advapi
kernel
user
kernel
HANDLE
.kernel
HANDLE
.kernel
HGLOBAL
.ktm
HANDLE
.comctl
kernel
HANDLE
.dshow
IBaseFilter
COM interface over IBaseFilterVT
.ole
IBindCtx
COM interface over IBindCtxVT
.ole
IDataObject
COM interface over IDataObjectVT
.oleaut
IDispatch
COM interface over IDispatchVT
.ole
IDropTarget
COM interface over IDropTargetVT
.dshow
IEnumFilters
COM interface over IEnumFiltersVT
.dshow
IEnumMediaTypes
COM interface over IEnumMediaTypesVT
.shell
IEnumShellItems
COM interface over IEnumShellItemsVT
.shell
IFileDialog
COM interface over IFileDialogVT
.shell
IFileOpenDialog
COM interface over IFileOpenDialogVT
.shell
IFileSaveDialog
COM interface over IFileSaveDialogVT
.dshow
IFileSinkFilter
COM interface over IFileSinkFilterVT
.dshow
IFilterGraph
COM interface over IFilterGraphVT
.dshow
IGraphBuilder
COM interface over IGraphBuilderVT
.comctl
and gdi
IMAGELISTDRAWPARAMS
struct.dshow
IMFGetService
COM interface over IMFGetServiceVT
.IMFVideoDisplayControl
COM interface over
IMFVideoDisplayControlVT
.dshow
IMediaControl
COM interface over IMediaControlVT
.dshow
IMediaFilter
COM interface over IMediaFilterVT
.dshow
shell
IModalWindow
COM interface over IModalWindowVT
.comctl
INITCOMMONCONTROLSEX
structole
IPersist
COM interface over IPersistVT
.ole
IPicture
COM interface over IPictureVT
.oleaut
IPropertyStore
COM interface over IPropertyStoreVT
.ISequentialStream
COM interface over ISequentialStreamVT
.shell
IShellItem
COM interface over IShellItemVT
.shell
IShellItem2
COM interface over IShellItem2VT
.shell
IShellItemArray
COM interface over IShellItemArrayVT
.shell
IShellLink
COM interface over IShellLinkVT
.shell
ITaskbarList
COM interface over ITaskbarListVT
.shell
ITaskbarList2
COM interface over ITaskbarList2VT
.shell
ITaskbarList3
COM interface over ITaskbarList3VT
.shell
ITaskbarList4
COM interface over ITaskbarList4VT
.oleaut
ITypeInfo
COM interface over ITypeInfoVT
.ole
IUnknown
COM interface over IUnknownVT
. It’s the base to
all COM interfaces.kernel
.ini
file.kernel
IniSection
of an
Ini
.kernel
Ini
.comctl
LVFINDINFO
struct.comctl
LVFOOTERINFO
struct.comctl
LVFOOTERITEM
struct.comctl
LVGROUPMETRICS
struct.comctl
LVHITTESTINFO
struct.comctl
LVINSERTGROUPSORTED
struct.comctl
LVINSERTMARK
struct.comctl
LVITEMINDEX
struct.comctl
LVSETINFOTIP
struct.comctl
LVTILEINFO
struct.comctl
LVTILEVIEWINFO
struct.comctl
MCGRIDINFO
struct.comctl
MCHITTESTINFO
struct.kernel
MEMORYSTATUSEX
struct.user
MENUBARINFO
struct.user
MENUITEMINFO
struct.MFVideoNormalizedRect
struct.user
MINMAXINFO
struct.kernel
MODULEENTRY32
struct.user
MONITORINFOEX
struct.comctl
MONTHDAYSTATE
struct.NCCALCSIZE_PARAMS
struct.comctl
NMBCDROPDOWN
struct.comctl
NMBCHOTITEM
struct.comctl
NMCUSTOMDRAW
struct.comctl
NMDATETIMECHANGE
struct.comctl
NMDATETIMEFORMAT
struct.comctl
NMDATETIMEFORMATQUERY
struct.comctl
NMDATETIMESTRING
struct.comctl
NMDATETIMEWMKEYDOWN
struct.comctl
NMDAYSTATE
struct.comctl
NMIPADDRESS
struct.comctl
NMITEMACTIVATE
struct.comctl
NMLISTVIEW
struct.comctl
NMLVCACHEHINT
struct.comctl
NMLVCUSTOMDRAW
struct.comctl
NMLVDISPINFO
struct.comctl
NMLVEMPTYMARKUP
struct.comctl
NMLVFINDITEM
struct.comctl
NMLVGETINFOTIP
struct.comctl
NMLVKEYDOWN
struct.comctl
NMLVODSTATECHANGE
struct.comctl
NMLVSCROLL
struct.comctl
and ole
NMOBJECTNOTIFY
struct.comctl
NMSELCHANGE
struct.comctl
NMTCKEYDOWN
struct.comctl
NMTRBTHUMBPOSCHANGING
struct.comctl
NMTREEVIEW
struct.comctl
and gdi
NMTVASYNCDRAW
struct.comctl
NMTVCUSTOMDRAW
stuct.comctl
NMTVITEMCHANGE
struct.comctl
NMVIEWCHANGE
struct.NONCLIENTMETRICS
struct.shell
NOTIFYICONDATA
struct.kernel
OSVERSIONINFOEX
struct.kernel
OVERLAPPED
struct.user
PAINTSTRUCT
struct.kernel
PROCESSENTRY32
struct.kernel
PROCESS_INFORMATION
struct.oleaut
PROPERTYKEY
struct.oleaut
PROPVARIANT
struct.version
version
ResourceInfo
, composed of a
language ID and a code page.user
SCROLLINFO
struct.kernel
SECURITY_ATTRIBUTES
struct.kernel
SECURITY_DESCRIPTOR
struct.shell
SHFILEINFO
struct.shell
SHFILEOPSTRUCT
struct.shell
SHSTOCKICONINFO
struct.kernel
STARTUPINFO
struct.user
STYLESTRUCT
struct.kernel
SYSTEMTIME
struct.kernel
SYSTEM_INFO
struct.comctl
and ole
TASKDIALOGCONFIG
struct.comctl
and ole
TASKDIALOG_BUTTON
struct.comctl
TBADDBITMAP
struct.comctl
TBBUTTONINFO
struct.comctl
TBINSERTMARK
struct.comctl
TBREPLACEBITMAP
struct.advapi
and comctl
TBSAVEPARAMS
struct.comctl
TCHITTESTINFO
struct.gdi
TEXTMETRIC
struct.kernel
THREADENTRY32
struct.kernel
TIME_ZONE_INFORMATION
struct.user
TITLEBARINFOEX
struct.user
TRACKMOUSEEVENT
struct.comctl
TVHITTESTINFO
struct.comctl
TVINSERTSTRUCT
struct.version
VS_FIXEDFILEINFO
struct.kernel
WIN32_FIND_DATA
struct.user
WINDOWINFO
struct.user
WINDOWPLACEMENT
struct.user
WNDCLASSEX
struct.kernel
Vec<u16>
buffer for a null-terminated
Unicode UTF-16
wide string natively used by Windows.Enums
user
user
user
comctl
comctl
comctl
user
user
kernel
kernel
File::open
and
FileMapped::open
.user
user
user
user
user
comctl
and ole
comctl
and ole
user
user
gdi
gdi
gdi
user
kernel
comctl
and ole
comctl
comctl
user
user
comctl
advapi
comctl
kernel
comctl
Functions
AdjustWindowRectEx
function.AllowSetForegroundWindow
functionAttachThreadInput
function.BroadcastSystemMessage
function.ChangeDisplaySettings
function.ChangeDisplaySettingsEx
function.comdlg
ChooseColor
function.user
ClipCursor
function.CoCreateInstance
function.CoInitializeEx
function, which
initializes
the COM library. When succeeding, returns an informational error code.CoLockObjectExternal
function.ole
CoTaskMemAlloc
function.CoTaskMemFree
function.ole
CoTaskMemRealloc
function.comdlg
CommDlgExtendedError
function.shell
CommandLineToArgv
function.advapi
DecryptFile
function.kernel
DeleteFile
function.user
DispatchMessage
function.user
EmptyClipboard
function.advapi
EncryptFile
function.advapi
EncryptionDisable
function.EnumDisplayDevices
function.EnumDisplaySettings
function.EnumDisplaySettingsEx
function.user
EnumWindows
function.kernel
ExpandEnvironmentStrings
function.kernel
FileTimeToSystemTime
function.GdiGetBatchLimit
function.GdiSetBatchLimit
function.user
GetAsyncKeyState
function.kernel
GetBinaryType
function.user
GetClipCursor
function.user
GetClipboardData
function.GetClipboardSequenceNumber
function.kernel
GetCommandLine
function.kernel
GetComputerName
function.kernel
GetCurrentDirectory
function.user
GetCursorPos
function.GetDialogBaseUnits
function.GetDoubleClickTime
function.kernel
GetEnvironmentStrings
function.kernel
GetFileAttributes
function.version
GetFileVersionInfo
function.version
GetFileVersionInfoSize
function.kernel
GetFirmwareType
function.user
GetGUIThreadInfo
function.kernel
GetLargePageMinimum
function.kernel
GetLastError
function.kernel
GetLocalTime
function.kernel
GetLogicalDriveStrings
function.GetMenuCheckMarkDimensions
function.user
GetMessage
function.user
GetMessagePos
function.kernel
GetNativeSystemInfo
function.user
GetQueueStatus
function.kernel
GetStartupInfo
function.user
GetSysColor
function.kernel
GetSystemDirectory
function.kernel
GetSystemInfo
function.user
GetSystemMetrics
function.GetSystemMetricsForDpi
function.kernel
GetSystemTime
function.kernel
GetSystemTimeAsFileTime
function.GetSystemTimePreciseAsFileTime
function.kernel
GetSystemTimes
function.kernel
GetTempPath
function.kernel
GetTickCount64
function.advapi
GetUserName
function.kernel
GetVolumeInformation
function.kernel
GlobalMemoryStatusEx
function.kernel
u32
of an u64
.user
InSendMessage
function.user
InSendMessageEx
function.user
InflateRect
function.comctl
InitCommonControls
function.comctl
InitCommonControlsEx
function.comctl
InitMUILanguage
function.InitializeSecurityDescriptor
function.user
IntersectRect
function.uxtheme
IsAppThemed
static method.uxtheme
IsCompositionActive
static method.user
IsGUIThread
function.kernel
IsNativeVhdBoot
function.user
IsRectEmpty
function.uxtheme
IsThemeActive
static method.uxtheme
IsThemeDialogTextureEnabled
static method.IsValidSecurityDescriptor
function.kernel
IsWindows7OrGreater
function.kernel
IsWindows8OrGreater
function.IsWindows8Point1OrGreater
function.kernel
IsWindows10OrGreater
function.kernel
IsWindowsServer
function.IsWindowsVersionOrGreater
function.kernel
IsWindowsVistaOrGreater
function.user
IsWow64Message
function.kernel
u32
of an u64
.LockSetForegroundWindow
function.kernel
kernel
MultiByteToWideChar
function.user
OffsetRect
function.kernel
OutputDebugString
function.oleaut
PSGetNameFromPropertyKey
function.shell
PathCombine
function.shell
PathCommonPrefix
function.shell
PathSkipRoot
function.shell
PathStripPath
function.shell
PathUndecorate
function.shell
PathUnquoteSpaces
function.user
PeekMessage
function.user
PostQuitMessage
function.PostThreadMessage
function.kernel
QueryPerformanceCounter
function.QueryPerformanceFrequency
function.user
RegisterClassEx
function.RegisterWindowMessage
function.kernel
ReplaceFile
function.shell
SHAddToRecentDocs
function.shell
SHFileOperation
function.shell
SHGetFileInfo
function.shell
SHGetKnownFolderPath
function.shell
SHGetStockIconInfo
function.SetCaretBlinkTime
function.user
SetCaretPos
function.user
SetClipboardData
function.kernel
SetCurrentDirectory
function.user
SetCursorPos
function.kernel
SetLastError
function.SetProcessDPIAware
function.shell
Shell_NotifyIcon
function.user
ShowCursor
function.user
SoundSentry
function.user
SubtractRect
function.user
SystemParametersInfo
function.kernel
SystemTimeToFileTime
function.SystemTimeToTzSpecificLocalTime
function.oleaut
SystemTimeToVariantTime
function. The inverse operation is performed by
VariantTimeToSystemTime
.comctl
and ole
TaskDialogIndirect
function.user
TrackMouseEvent
function.user
TranslateMessage
function.user
UnregisterClass
function.version
VarQueryValue
function.oleaut
VariantTimeToSystemTime
function. The inverse operation is performed by
SystemTimeToVariantTime
.kernel
VerSetConditionMask
function.kernel
VerifyVersionInfo
function.user
WaitMessage
function.kernel
WideCharToMultiByte
function.Type Definitions
kernel
Result
alias which returns a Box<dyn Error + Send + Sync>
on failure.comdlg
CCHOOKPROC
callback function.EDITWORDBREAKPROC
callback function.ole
Result
alias for COM error codes,
which returns an HRESULT
on failure.comctl
PFNLVCOMPARE
callback function.comctl
PFNLVGROUPCOMPARE
callback function.comctl
PFNTVCOMPARE
callback function.comctl
and ole
PFTASKDIALOGCALLBACK
calback function.comctl
SUBCLASSPROC
callback function.kernel
Result
alias for native system error
codes, which returns an ERROR
on failure.