Crate winsafe[][src]

Expand description

Windows API and GUI in safe, idiomatic Rust.

CrateGitHubDocs (stable)Docs (master branch)Examples

WinSafe has:

  • high-level structs to build native Win32 GUI applications;
  • low-level Win32 API constants, functions and structs related to GUI.

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.9", 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 structs
kernelKernel32.dll, required by all others
msimgMsimg32.dll
oleOLE and basic COM support
oleautOLE Automation
shellShell32.dll, the COM-based Windows Shell
shlwapiShlwapi.dll, for some Shell functions
userUser32.dll, the basic Windows UI support
uxthemeUxTheme.dll, extended UI 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.

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 WinResult, 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 WinResult.

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.

Modules

Native constants.

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.

File path utilities.

The WinSafe prelude.

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.

The data of the AccelMenuCtrl Ctrl option.

BHIDshell

IShellItem::BindToHandler bhid. Just a safe abstraction over a GUID.

BITMAP struct.

CHOOSECOLOR struct.

COM class ID. Just a safe abstraction over a GUID.

COLORREF struct.

A pointer to a COM virtual table.

DEVMODE struct.

DVINFOdshow

DVINFO struct.

FILETIMEkernel

FILETIME struct.

Filekernel

Manages an HFILE handle, which is closed automatically when the object goes out of scope.

Manages a memory-mapped file, which can be read/written through slices. It is closed automatically when the object goes out of scope.

GUIDole

GUID struct.

HACCELuser

Handle to an accelerator table.

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
HDWPuser32

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.

HTREEITEMcomctl

Handle to an tree view item.

Handle to an updateable resource. Originally just a HANDLE.

HWNDuser

Handle to a window.

IBaseFilter COM interface over IBaseFilterVT.

IDispatcholeaut

IDispatch COM interface over IDispatchVT.

IEnumFilters COM interface over IEnumFiltersVT.

IFileDialog COM interface over IFileDialogVT.

IFilterGraph COM interface over IFilterGraphVT.

IIDole

COM interface ID. Just a safe abstraction over a GUID.

IMediaFilter COM interface over IMediaFilterVT.

IMediaSeeking COM interface over IMediaSeekingVT. Inherits from IUnknown.

IModalWindow COM interface over IModalWindowVT.

IPersistshlwapi

IPersist COM interface over IPersistVT.

IPictureoleaut

IPicture COM interface over IPictureVT.

IPindshow

IPin COM interface over IPinVT.

IShellItem COM interface over IShellItemVT.

IStreamshlwapi

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

Keeps sections and key/value pairs of a .ini file, also doing parsing and serialization of the data.

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.

LVITEMINDEX struct.

LVTILEINFO struct.

AM_MEDIA_TYPE majortype. Just a safe abstraction over a GUID.

AM_MEDIA_TYPE formattype, originally with FORMAT prefix. Just a safe abstraction over a GUID.

MENUINFO struct.

MSGuser

MSG struct.

NMBCHOTITEM struct.

NMCHARcomctl

NMCHAR struct.

NMDAYSTATE struct.

NMHDRcomctl

NMHDR struct.

NMIPADDRESS struct.

NMLINKcomctl

NMLINK struct.

NMLISTVIEW struct.

NMLVKEYDOWN struct.

NMLVLINKcomctl

NMLVLINK struct.

NMLVSCROLL struct.

NMMOUSEcomctl

NMMOUSE struct.

NMSELCHANGE struct.

NMTREEVIEW struct.

NMTVASYNCDRAWcomctl and gdi

NMTVASYNCDRAW struct.

OVERLAPPED struct.

PBRANGEcomctl

PBRANGE struct.

POINTuser

POINT struct.

RECTuser

RECT struct.

RGBQUAD struct.

Retrieves data from an embedded resource, which can be read from an executable file or a DLL.

An language block of ResourceInfo, composed of a language ID and a code page.

SHFILEINFO struct.

SIZEuser

SIZE struct.

STARTUPINFO struct.

SYSTEMTIME struct.

SYSTEM_INFO struct.

TBADDBITMAP struct.

TBBUTTONcomctl

TBBUTTON struct.

IMediaSeeking::SetTimeFormat format. Just a safe abstraction over a GUID.

TVITEMcomctl

TVITEM struct.

TVITEMEXcomctl

TVITEMEX struct.

WINDOWPOS struct.

WStringkernel

Stores a Vec<u16> buffer for a null-terminated Unicode UTF-16 wide string natively used by Windows.

Enums

Variant parameters of a wm::Command message.

Variant parameter used in window class functions:

Variant parameter for:

BmpIdbRescomctl

Variant parameter for:

Variant parameter for:

Variant parameter for:

Encodingkernel

String encodings that can be guessed by WString::guess_encoding.

Access types for File::open and FileMapped::open.

Variant parameter for:

Variant parameter for:

Variant parameter for:

Variant parameter for:

IconIdcomctl

Variant parameter for:

Variant parameter for:

Variant parameter for:

Variant parameter for:

IdMenuuser

Variant parameter used in menu methods:

IdPosuser

Variant parameter for:

IdStrkernel

A resource identifier.

Variant parameter for:

IndexStrcomctl

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. Returns some error codes as success status.

CopyFilekernel

CopyFile function.

DecryptFile function.

DeleteFile function.

EncryptFile function.

EndMenu function.

EnumWindows function.

GetLastError function.

GetMessage function.

GetSysColor 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.

IsGUIThread function.

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.

PeekMessage function.

ReplaceFile function.

SetCaretPos function.

SetLastError function.

ShowCursor function.

Sleepkernel

Sleep function.

SoundSentry function.

TaskDialogIndirectcomctl and ole

WaitMessage function.

Type Definitions

Type alias to CCHOOKPROC callback function.

Type alias to DLGPROC callback function.

Type alias to EDITWORDBREAKPROC callback function.

ErrResultkernel

A specialized Result which returns a Box<dyn Error + Send + Sync> on failure.

Type alias to HOOKPROC callback function.

A specialized Result for Win32 COM operations, which returns an HRESULT on failure.

Type alias to PFNLVCOMPARE callback function.

Type alias to PFNLVGROUPCOMPARE callback function.

Type alias to PFTASKDIALOGCALLBACK calback function.

Type alias to SUBCLASSPROC callback function.

Type alias to TIMERPROC callback function.

Type alias to WNDPROC callback function.

WinResultkernel

A specialized Result for Win32 operations, which returns an ERROR on failure.