Crate winsafe

source ·
Expand description

Windows API and GUI in safe, idiomatic Rust.

CrateGitHubDocs (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:

FeatureDescription
advapiAdvapi32.dll, for Windows Registry
comctlComCtl32.dll, for Common Controls
comdlgComDlg32.dll, for the old Common Dialogs
dshowDirectShow
gdiGdi32.dll, the Windows GDI
guiThe WinSafe high-level GUI abstractions
kernelKernel32.dll, all others will include it
ktmKtmw32.dll, the Kernel Transaction Manager
msimgMsimg32.dll
oleOLE and basic COM support
oleautOLE Automation
shellShell32.dll and Shlwapi.dll, the COM-based Windows Shell
userUser32.dll, the basic Windows GUI support
uxthemeUxTheme.dll, extended window theming
versionVersion.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:

AliasErrorUsed for
SysResultERRORStandard system errors.
HrResultHRESULTCOM errors.
AnyResultBox<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:

UtilityUsed for
EncodingString encodings.
FileFile read/write and other operations.
FileMappedMemory-mapped file operations.
IniManaging key/value pairs of a .ini file.
pathFile path operations.
ResourceInfoRetrieve embedded data from executables or DLLs.
task_dlgVarious dialog prompts.
WStringManaging native wide strings.

Modules

Native constants.
RAII implementation for various resources, which automatically perform cleanup routines when the object goes out of scope.
guigui
High-level GUI abstractions for user windows and native controls. They can be created programmatically or by loading resources from a .res file. These files can be created with a WYSIWYG resource editor.
Parameters of window messages.
pathkernel
File path utilities.
The WinSafe prelude.
task_dlgcomctl and ole
Provides high-level abstractions to TaskDialogIndirect and HWND::TaskDialog functions.
Virtual tables of COM interfaces.

Macros

Generates sequential u16 constants starting from the given value.

Structs

ACCELuser
ACCEL struct.
ACLkernel
ACL struct.
ATOMuser
ATOM returned by RegisterClassEx.
Variant parameter for:
BITMAP struct.
BSTRoleaut
A string data type used with COM automation.
COLORREF struct.
A pointer to pointer to a COM virtual table.
DEVMODE struct.
DVINFOdshow
DVINFO struct.
FILETIMEkernel
FILETIME struct.
Filekernel
Manages an HFILE handle, which provides file read/write and other operations. It is closed automatically when the object goes out of scope.
Manages an HFILEMAP handle, which provides memory-mapped file operations, including read/write through slices. It is closed automatically when the object goes out of scope.
GUIDkernel
GUID struct.
HACCELuser
Handle to an accelerator table.
Handle to an access token. Originally just a HANDLE.
Handle to a bitmap.
HBRUSHuser
Handle to a brush.
Handle to a cursor.
HDCuser
Handle to a device context.
HDITEMcomctl
HDITEM struct.
HDLAYOUTcomctl
HDLAYOUT struct.
HDROPshell
HEAPLIST32 struct.
HELPINFO struct.
HEVENTkernel
Handle to an event. Originally just a HANDLE.
HFILEkernel
Handle to a file. Originally just a HANDLE.
HFILEMAPkernel
Handle to a file mapping. Originally just a HANDLE.
Address of a mapped view. Originally just an LPVOID.
HFINDFILEkernel
Handle to a file search. Originally just a HANDLE.
Handle to a font.
HGLOBALkernel
Handle to a global memory block. Originally just a HANDLE.
HHOOKuser
Handle to a hook.
HICONuser
Handle to an icon.
Handle to an image list.
HINSTANCEkernel
Handle to an instance, same as HMODULE.
HKEYadvapi
Handle to a registry key.
HLOCALkernel
Handle to a local memory block.
HMENUuser
Handle to a menu.
Handle to a display monitor.
HPENgdi
Handle to a pen GDI object.
HPIPEkernel
Handle to an anonymous pipe. Originally just a HANDLE.
HPROCESSkernel
Handle to a process. Originally just a HANDLE.
Handle to a process list snapshot. Originally just a HANDLE.
HRGNuser
Handle to a region GDI object.
HRSRCkernel
Handle to a resource. Originally just a HANDLE.
HRSRCMEMkernel
Handle to a resource memory block. Originally just an HGLOBAL.
HTHEMEuxtheme
Handle to a theme.
HTHREADkernel
Handle to a thread. Originally just a HANDLE.
Handle to a transaction. Originally just a HANDLE.
HTREEITEMcomctl
Handle to a tree view item.
Handle to an updateable resource. Originally just a HANDLE.
HWNDuser
Handle to a window.
IBaseFilter COM interface over IBaseFilterVT.
IBindCtx COM interface over IBindCtxVT.
IDataObject COM interface over IDataObjectVT.
IDispatcholeaut
IDispatch COM interface over IDispatchVT.
IDropTarget COM interface over IDropTargetVT.
IEnumFilters COM interface over IEnumFiltersVT.
IFileDialog COM interface over IFileDialogVT.
IFilterGraph COM interface over IFilterGraphVT.
IMediaFilter COM interface over IMediaFilterVT.
IMediaSeeking COM interface over IMediaSeekingVT. Inherits from IUnknown.
IModalWindow COM interface over IModalWindowVT.
IPersist COM interface over IPersistVT.
IPicture COM interface over IPictureVT.
IPindshow
IPin COM interface over IPinVT.
IShellItem COM interface over IShellItemVT.
IShellItem2 COM interface over IShellItem2VT.
IShellLink COM interface over IShellLinkVT.
IStream COM interface over IStreamVT.
ITaskbarList COM interface over ITaskbarListVT.
ITypeInfooleaut
ITypeInfo COM interface over ITypeInfoVT.
IUnknown COM interface over IUnknownVT. It’s the base to all COM interfaces.
Inikernel
High-level abstraction to load, manage and serialize sections and key/value pairs of a .ini file.
IniEntrykernel
A single key/value pair of an IniSection of an Ini.
A single section of an Ini.
LANGIDkernel
LANGID language identifier.
LCIDkernel
LCID locale identifier.
LITEMcomctl
LITEM struct.
LOGBRUSH struct.
LOGFONT struct.
LOGPEN struct.
LVBKIMAGEcomctl
LVBKIMAGE struct.
LVCOLUMNcomctl
LVCOLUMN struct.
LVFINDINFO struct.
LVGROUPcomctl
LVGROUP struct.
LVITEMcomctl
LVITEM struct.
LVTILEINFO struct.
MCGRIDINFO struct.
MENUINFO struct.
MSGuser
MSG struct.
NMCHARcomctl
NMCHAR struct.
NMDAYSTATE struct.
NMHDRcomctl
NMHDR struct.
NMLINKcomctl
NMLINK struct.
NMLISTVIEW struct.
NMLVLINKcomctl
NMLVLINK struct.
NMLVSCROLL struct.
NMMOUSEcomctl
NMMOUSE struct.
NMOBJECTNOTIFYcomctl and ole
NMTREEVIEW struct.
NMTVASYNCDRAWcomctl and gdi
OVERLAPPED struct.
PBRANGEcomctl
PBRANGE struct.
PIN_INFO struct.
POINTuser
POINT struct.
RECTuser
RECT struct.
RGBQUAD struct.
Retrieves data from an embedded resource, which can be read from an EXE or a DLL file.
An language block of ResourceInfo, composed of a language ID and a code page.
SIZEuser
SIZE struct.
SYSTEMTIME struct.
TASKDIALOGCONFIGcomctl and ole
TBBUTTONcomctl
TBBUTTON struct.
TBMETRICScomctl
TBMETRICS struct.
TBSAVEPARAMSadvapi and comctl
TBSAVEPARAMS struct.
TCITEMcomctl
TCITEM struct.
TVITEMcomctl
TVITEM struct.
TVITEMEXcomctl
TVITEMEX struct.
TVSORTCBcomctl
TVSORTCB struct.
UDACCELcomctl
UDACCEL struct.
VARIANToleaut
VARIANT struct.
WINDOWPOS struct.
WStringkernel
Stores a Vec<u16> buffer for a null-terminated Unicode UTF-16 wide string natively used by Windows.

Enums

Variant parameter for:
Variant parameter used in window class functions:
Variant parameter for:
Variant parameter for:
BmpIdbRescomctl
Variant parameter for:
BmpInstIdcomctl
Variant parameter for:
Variant parameter for:
Variant parameter for:
Encodingkernel
String encodings.
Access types for File::open and FileMapped::open.
Variant parameter for:
Variant parameter for:
Variant parameter for:
Variant parameter for:
Variant parameter for:
IconIdcomctl and ole
Variant parameter for:
IconIdTdiconcomctl and ole
Variant parameter for:
Variant parameter for:
Variant parameter for:
IdMenuuser
Variant parameter used in menu methods:
Variant parameter for:
Variant parameter for:
Variant parameter for:
IdPosuser
Variant parameter for:
IdStrkernel
A resource identifier.
IdTdiconStrcomctl and ole
Variant parameter for:
IdxCbNonecomctl
Variant type for:
IdxStrcomctl
Variant parameter for:
Variant parameter for:
Variant parameter for:
PtIdxcomctl
Variant parameter for:
Registry value types.
ResStrscomctl
Variant parameter for:
RtStrkernel
A predefined resource identifier.
Variant parameter for:

Functions

AnyPopup function.
ChooseColor function.
ClipCursor function.
CoInitializeEx function, which initializes the COM library. When succeeding, returns an informational error code.
CopyFilekernel
CopyFile function.
DecryptFile function.
DeleteFile function.
EncryptFile function.
EndMenu function.
GdiFlush function.
GetLastError function.
GetLocalTime function.
GetMessage function.
GetTempPath function.
GetUserName function.
HIBYTEkernel
HIBYTE function. Originally a macro.
HIDWORDkernel
Returns the high-order u32 of an u64.
HIWORDkernel
HIWORD function. Originally a macro.
IsAppThemed static method.
IsThemeActive static method.
LOBYTEkernel
LOBYTE function. Originally a macro.
LODWORDkernel
Returns the low-order u32 of an u64.
LOWORDkernel
LOWORD function. Originally a macro.
MAKEDWORDkernel
Function that implements MAKELONG, MAKEWPARAM, and MAKELPARAM macros.
MAKEQWORDkernel
Similar to MAKEDWORD, but for u64.
MAKEWORDkernel
MAKEWORD function. Originally a macro.
MoveFilekernel
MoveFile function.
MulDivkernel
MulDiv function.
OffsetRect function.
PathCombine function.
PtInRect function.
ReplaceFile function.
SetLastError function.
ShowCursor function.
Sleepkernel
Sleep function.
SystemTimeToVariantTime function. The inverse operation is performed by VariantTimeToSystemTime.
TaskDialogIndirectcomctl and ole
UnionRect function.
VarQueryValueversion
VarQueryValue function.
VariantTimeToSystemTime function. The inverse operation is performed by SystemTimeToVariantTime.

Type Definitions

AnyResultkernel
A Result alias which returns a Box<dyn Error + Send + Sync> on failure.
Type alias to CCHOOKPROC callback function.
Type alias to DLGPROC callback function.
Type alias to EDITWORDBREAKPROC callback function.
Type alias to HOOKPROC callback function.
A Result alias for COM error codes, which returns an HRESULT on failure.
Type alias to PFNLVCOMPARE callback function.
Type alias to PFNLVGROUPCOMPARE callback function.
Type alias to PFNTVCOMPARE callback function.
PFTASKDIALOGCALLBACKcomctl and ole
Type alias to PFTASKDIALOGCALLBACK calback function.
Type alias to SUBCLASSPROC callback function.
SysResultkernel
A Result alias for native system error codes, which returns an ERROR on failure.
Type alias to TIMERPROC callback function.
Type alias to WNDPROC callback function.