Crate winsafe[][src]

Win32 GUI and related APIs in safe, idiomatic Rust.

WinSafe has:

If you’re looking for a comprehensive Win32 coverage, take a look at winapi or windows crates, which are unsafe, but have everything.

To use this crate, put this in your Cargo.toml:

[dependencies]
winsafe = "0.0.2"

Links:

Modules overview

The Win32 bindings are divided into a few modules:

And additionally:

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

Now this C code:

PostQuitMessage(0);

Is equivalent to:

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::{co::MB, HWND};

let hwnd = HWND::GetDesktopWindow();
hwnd.MessageBox("Hello, world", "Title", MB::OKCANCEL | MB::ICONINFORMATION)
    .unwrap();

The method MessageBox, like all native 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::{RegisterClassEx, WNDCLASSEX, WString};

let buf = WString::from_str("MY_WINDOW");

let mut wcx = WNDCLASSEX::default();
wcx.set_lpszClassName(&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.

GUI

On top of the Win32 bindings, WinSafe features a set of high-level GUI structs, which scaffolds the boilerplate needed to build native Win32 GUI applications. Unless you’re doing something really specific, these high-level wrappers are highly recommended.

GUI structs can be found in module gui.

Modules

co

Win32 constants and types of constants.

dshow

DirectShow COM interfaces.

gui

High-level GUI abstractions for user windows and native controls.

msg

Parameters of window messages.

shell

Shell COM interfaces.

Structs

ACCEL

ACCEL struct.

ACL

ACL struct.

ALTTABINFO

ALTTABINFO struct.

ATOM

ATOM returned by RegisterClassEx.

BITMAPINFOHEADER

BITMAPINFOHEADER struct.

BUTTON_IMAGELIST

BUTTON_IMAGELIST struct.

BUTTON_SPLITINFO

BUTTON_SPLITINFO struct.

BY_HANDLE_FILE_INFORMATION

BY_HANDLE_FILE_INFORMATION method.

CLSID

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

COLORREF

COLORREF struct.

CREATESTRUCT

CREATESTRUCT struct.

DATETIMEPICKERINFO

DATETIMEPICKERINFO struct.

FILETIME

FILETIME struct.

GUID

GUID struct.

HACCEL

Handle to an accelerator table.

HBITMAP

Handle to a bitmap.

HBRUSH

Handle to a brush.

HCURSOR

Handle to a cursor.

HDC

Handle to a device context.

HDROP

Handle to an internal drop structure.

HDWP

Handle to a deferred window position.

HELPINFO

HELPINFO struct.

HEVENT

Handle to an event. Originally just a HANDLE.

HFILE

Handle to a file. Originally just a HANDLE.

HFILEMAP

Handle to a file mapping. Originally just a HANDLE.

HFILEMAPVIEW

Address of a mapped view. Originally just an LPVOID.

HFONT

Handle to a font.

HHOOK

Handle to a hook.

HICON

Handle to an icon.

HIMAGELIST

Handle to an image list.

HINSTANCE

Handle to an instance, same as HMODULE.

HKEY

Handle to a registry key.

HLOCAL

Handle to a local memory block.

HMENU

Handle to a menu.

HPEN

Handle to a pen GDI object.

HRGN

Handle to a region GDI object.

HTHEME

Handle to a theme.

HTREEITEM

Handle to an tree view item.

HWND

Handle to a window.

IDispatch

IDispatch COM interface over IDispatchVT. Inherits from IUnknown.

IDispatchVT

IDispatch virtual table.

IID

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

IMAGELISTDRAWPARAMS

IMAGELISTDRAWPARAMS struct.

IPersist

IPersist COM interface over IPersistVT. Inherits from IUnknown.

IPersistVT

IPersist virtual table.

ITypeInfo

ITypeInfo COM interface over ITypeInfoVT. Inherits from IUnknown.

ITypeInfoVT

ITypeInfo virtual table.

IUnknown

IUnknown COM interface over IUnknownVT. It’s the base to all COM interfaces.

IUnknownVT

IUnknown virtual table, base to all COM virtual tables.

LANGID

LANGID language identifier.

LCID

LCID locale identifier.

LITEM

LITEM struct.

LOGFONT

LOGFONT struct.

LVCOLUMN

LVCOLUMN struct.

LVFINDINFO

LVFINDINFO struct.

LVITEM

LVITEM struct.

MENUINFO

MENUINFO struct.

MENUITEMINFO

MENUITEMINFO struct.

MINMAXINFO

MINMAXINFO struct.

MSG

MSG struct.

NCCALCSIZE_PARAMS

NCCALCSIZE_PARAMS struct.

NMBCDROPDOWN

NMBCDROPDOWN struct.

NMBCHOTITEM

NMBCHOTITEM struct.

NMCHAR

NMCHAR struct.

NMCUSTOMDRAW

NMCUSTOMDRAW struct.

NMDATETIMECHANGE

NMDATETIMECHANGE struct.

NMDATETIMEFORMAT

NMDATETIMEFORMAT struct.

NMDATETIMEFORMATQUERY

NMDATETIMEFORMATQUERY struct.

NMDATETIMESTRING

NMDATETIMESTRING struct.

NMDATETIMEWMKEYDOWN

NMDATETIMEWMKEYDOWN struct.

NMDAYSTATE

NMDAYSTATE struct.

NMHDR

NMHDR struct.

NMIPADDRESS

NMIPADDRESS struct.

NMITEMACTIVATE

NMITEMACTIVATE struct.

NMLINK

NMLINK struct.

NMLISTVIEW

NMLISTVIEW struct.

NMLVCACHEHINT

NMLVCACHEHINT struct.

NMLVDISPINFO

NMLVDISPINFO struct.

NMLVEMPTYMARKUP

NMLVEMPTYMARKUP struct.

NMLVFINDITEM

NMLVFINDITEM struct.

NMLVGETINFOTIP

NMLVGETINFOTIP struct.

NMLVKEYDOWN

NMLVKEYDOWN struct.

NMLVLINK

NMLVLINK struct.

NMLVODSTATECHANGE

NMLVODSTATECHANGE struct.

NMLVSCROLL

NMLVSCROLL struct.

NMMOUSE

NMMOUSE struct.

NMSELCHANGE

NMSELCHANGE struct.

NMTRBTHUMBPOSCHANGING

NMTRBTHUMBPOSCHANGING struct.

NMTVASYNCDRAW

NMTVASYNCDRAW struct.

NMVIEWCHANGE

NMVIEWCHANGE struct.

NONCLIENTMETRICS

NONCLIENTMETRICS struct.

OSVERSIONINFOEX

OSVERSIONINFOEX struct.

OVERLAPPED

OVERLAPPED struct.

PAINTSTRUCT

PAINTSTRUCT struct.

PBRANGE

PBRANGE struct.

POINT

POINT struct.

RECT

RECT struct.

SCROLLINFO

SCROLLINFO struct.

SECURITY_ATTRIBUTES

SECURITY_ATTRIBUTES struct.

SECURITY_DESCRIPTOR

SECURITY_DESCRIPTOR struct.

SIZE

SIZE struct.

STYLESTRUCT_WS

STYLESTRUCT struct for WS.

STYLESTRUCT_WS_EX

STYLESTRUCT struct for WS_EX.

SYSTEMTIME

SYSTEMTIME struct.

TEXTMETRIC

TEXTMETRIC struct.

TIME_ZONE_INFORMATION

TIME_ZONE_INFORMATION struct.

TRACKMOUSEEVENT

TRACKMOUSEEVENT struct.

WINDOWINFO

WINDOWINFO struct.

WINDOWPLACEMENT

WINDOWPLACEMENT struct.

WINDOWPOS

WINDOWPOS struct.

WNDCLASSEX

WNDCLASSEX struct.

WString

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

Enums

AtomStr

Variant parameter used in window class functions:

BitmapIcon

Variant parameter for:

BitmapPtrStr

Variant parameter used in menu methods:

BroadNull

Variant parameter for:

HwndFocus

Variant parameter for:

HwndHmenu

Variant parameter for:

HwndPlace

Variant parameter for:

HwndPointId

Variant parameter for:

IdIdcStr

Variant parameter for:

IdIdiStr

Variant parameter for:

IdMenu

Variant parameter used in menu methods:

IdPos

Variant parameter used in menu methods:

IdStr

Variant parameter for:

IndexAll

Variant parameter for:

NccspRect

Variant parameter for:

RegistryValue

Variant value returned by RegQueryValueEx.

WsWsex

Variant parameter for:

Traits

ComVT

Trait for any COM virtual table.

Functions

AdjustWindowRectEx

AdjustWindowRectEx function.

CoCreateInstance

CoCreateInstance function.

CoInitializeEx

CoInitializeEx function. Returns some error codes as success status.

CoTaskMemFree

CoTaskMemFree function.

CoUninitialize

CoUninitialize function.

CopyFileW

CopyFile function.

DecryptFile

DecryptFile function.

DeleteFile

DeleteFile function.

DispatchMessage

DispatchMessage function.

EncryptFile

EncryptFile function.

EncryptionDisable

EncryptionDisable function.

ExpandEnvironmentStrings

ExpandEnvironmentStrings function.

FileTimeToSystemTime

FileTimeToSystemTime function.

GetAsyncKeyState

GetAsyncKeyState function.

GetDialogBaseUnits

GetDialogBaseUnits function.

GetDoubleClickTime

GetDoubleClickTime function.

GetEnvironmentStrings

GetEnvironmentStrings function.

GetFileAttributes

GetFileAttributes method.

GetLastError

GetLastError function.

GetLogicalDriveStrings

GetLogicalDriveStrings function.

GetMessage

GetMessage function.

GetQueueStatus

GetQueueStatus function.

GetSysColor

GetSysColor function.

GetSystemMetrics

GetSystemMetrics function.

GetSystemTime

GetSystemTime function.

GetSystemTimeAsFileTime

GetSystemTimeAsFileTime function.

GetSystemTimePreciseAsFileTime

GetSystemTimePreciseAsFileTime function.

GetTempPath

GetTempPath function.

GetTickCount64

GetTickCount64 function.

HIBYTE

HIBYTE function. Originally a macro.

HIDWORD

Returns the high-order u32 of an u64.

HIWORD

HIWORD function. Originally a macro.

HRESULT_FROM_WIN32

HRESULT_FROM_WIN32 function. Originally a macro.

InitCommonControls

InitCommonControls function.

IsGUIThread

IsGUIThread function.

IsWindows7OrGreater

IsWindows7OrGreater function.

IsWindows8OrGreater

IsWindows8OrGreater function.

IsWindows8Point1OrGreater

IsWindows8Point1OrGreater function.

IsWindows10OrGreater

IsWindows10OrGreater function.

IsWindowsServer

IsWindowsServer function.

IsWindowsVersionOrGreater

IsWindowsVersionOrGreater function.

IsWindowsVistaOrGreater

IsWindowsVistaOrGreater function.

LOBYTE

LOBYTE function. Originally a macro.

LODWORD

Returns the low-order u32 of an u64.

LOWORD

LOWORD function. Originally a macro.

LockSetForegroundWindow

LockSetForegroundWindow function.

MAKEDWORD

Function that implements MAKELONG, MAKEWPARAM, and MAKELPARAM macros.

MAKEWORD

MAKEWORD function. Originally a macro.

MoveFile

MoveFile function.

MulDiv

MulDiv function.

MultiByteToWideChar

MultiByteToWideChar function.

OutputDebugString

OutputDebugString function.

PeekMessage

PeekMessage function.

PostMessage

PostMessage function. Note that this function is asychronous.

PostQuitMessage

PostQuitMessage function.

RegisterClassEx

RegisterClassEx function.

SetCaretBlinkTime

SetCaretBlinkTime function.

SetCaretPos

SetCaretPos function.

SetCursorPos

SetCursorPos function.

SetLastError

SetLastError function.

SetProcessDPIAware

SetProcessDPIAware function.

ShowCursor

ShowCursor function.

Sleep

Sleep function.

SoundSentry

SoundSentry function.

SystemParametersInfo

SystemParametersInfo function.

SystemTimeToFileTime

SystemTimeToFileTime function.

SystemTimeToTzSpecificLocalTime

SystemTimeToTzSpecificLocalTime function.

TrackMouseEvent

TrackMouseEvent function.

TranslateMessage

TranslateMessage function.

UnregisterClass

UnregisterClass function.

VerSetConditionMask

VerSetConditionMask function.

VerifyVersionInfo

VerifyVersionInfo function.

WaitMessage

WaitMessage function.

WideCharToMultiByte

WideCharToMultiByte function.

Type Definitions

DLGPROC

Type alias to DLGPROC callback function.

HOOKPROC

Type alias to HOOKPROC callback function.

PPComVT

Type alias to pointer to pointer to a COM virtual table.

SUBCLASSPROC

Type alias to SUBCLASSPROC callback function.

TIMERPROC

Type alias to TIMERPROC callback function.

WNDENUMPROC

Type alias to WNDENUMPROC callbak function.

WNDPROC

Type alias to WNDPROC callback function.

WinResult

A specialized Result for Win32 operations, which return a ERROR on failure.