Convert Figma logo to code with AI

microsoft logowindows-rs

Rust for Windows

12,749
664
12,749
25

Top Related Projects

115,493

Empowering everyone to build reliable and efficient software.

Automatically generates Rust FFI bindings to C (and some C++) libraries.

6,825

Safe interop between Rust and C++

Rust bindings to Windows API

Quick Overview

Windows-rs is a Rust library that provides bindings to the Windows API, allowing Rust developers to easily interact with Windows systems and create native Windows applications. It offers a safe and idiomatic Rust interface to the Windows API, making it easier to develop Windows-specific functionality in Rust projects.

Pros

  • Provides safe and idiomatic Rust bindings to the Windows API
  • Automatically generates bindings from Windows metadata, ensuring up-to-date and comprehensive coverage
  • Offers excellent performance with minimal overhead
  • Supports both the stable and nightly Rust compilers

Cons

  • Limited to Windows platforms, reducing cross-platform compatibility
  • Learning curve for developers unfamiliar with the Windows API
  • Documentation can be sparse for some less common API calls
  • May require additional setup for certain Windows SDK features

Code Examples

  1. Creating a message box:
use windows::{
    core::*,
    Win32::UI::WindowsAndMessaging::*,
};

fn main() -> Result<()> {
    unsafe {
        MessageBoxA(None, s!("Hello, world!"), s!("Greeting"), MB_OK);
    }
    Ok(())
}
  1. Enumerating windows:
use windows::{
    Win32::Foundation::*,
    Win32::UI::WindowsAndMessaging::*,
};

unsafe extern "system" fn enum_windows_proc(hwnd: HWND, _: LPARAM) -> BOOL {
    let mut text = [0u16; 512];
    let len = GetWindowTextW(hwnd, &mut text);
    if len > 0 {
        println!("Window: {}", String::from_utf16_lossy(&text[..len as usize]));
    }
    true.into()
}

fn main() -> Result<()> {
    unsafe {
        EnumWindows(Some(enum_windows_proc), LPARAM(0));
    }
    Ok(())
}
  1. Playing a system sound:
use windows::{
    core::*,
    Win32::Media::Audio::*,
    Win32::UI::WindowsAndMessaging::*,
};

fn main() -> Result<()> {
    unsafe {
        PlaySoundW(w!("SystemAsterisk"), None, SND_ALIAS | SND_ASYNC);
    }
    Ok(())
}

Getting Started

To use windows-rs in your Rust project, add the following to your Cargo.toml:

[dependencies]
windows = "0.48"

[build-dependencies]
windows = "0.48"

Then, create a build.rs file in your project root:

fn main() {
    windows::build!(
        Windows::Win32::UI::WindowsAndMessaging::*,
        Windows::Win32::Foundation::*
    );
}

Now you can use the Windows API in your Rust code. Remember to import the necessary modules and handle errors appropriately.

Competitor Comparisons

115,493

Empowering everyone to build reliable and efficient software.

Pros of rust

  • Comprehensive standard library and ecosystem for general-purpose programming
  • Cross-platform support for multiple operating systems and architectures
  • Extensive documentation and community resources

Cons of rust

  • Steeper learning curve, especially for systems programming concepts
  • Longer compilation times due to its sophisticated type system and borrow checker
  • Larger project scope and complexity, which can be overwhelming for beginners

Code comparison

rust:

fn main() {
    println!("Hello, world!");
    let numbers = vec![1, 2, 3, 4, 5];
    let sum: i32 = numbers.iter().sum();
}

windows-rs:

use windows::Win32::UI::WindowsAndMessaging::*;

fn main() -> windows::Result<()> {
    unsafe { MessageBoxA(None, "Hello, world!", "windows-rs", MB_OK) };
    Ok(())
}

The rust example showcases general-purpose programming with standard library features, while windows-rs demonstrates Windows API integration for native Windows development.

Automatically generates Rust FFI bindings to C (and some C++) libraries.

Pros of rust-bindgen

  • Generates bindings for a wide variety of C and C++ libraries, not limited to Windows APIs
  • Offers more customization options for fine-tuning generated bindings
  • Supports complex C++ features like templates and inheritance

Cons of rust-bindgen

  • Requires more setup and configuration for each project
  • May generate less idiomatic Rust code compared to hand-crafted bindings
  • Can be slower to compile due to the complexity of C++ parsing

Code Comparison

rust-bindgen:

#[derive(Debug)]
struct BindgenOptions {
    header: String,
    clang_args: Vec<String>,
}

let bindings = bindgen::Builder::default()
    .header("header.h")
    .parse_callbacks(Box::new(bindgen::CargoCallbacks))
    .generate()
    .expect("Unable to generate bindings");

windows-rs:

use windows::Win32::UI::WindowsAndMessaging::*;

#[windows::core::implement(IUnknown)]
struct MyClass;

let hwnd = CreateWindowExW(
    WINDOW_EX_STYLE::default(),
    w!("BUTTON"),
    w!("Click me"),
    WINDOW_STYLE::default(),
    0, 0, 100, 100,
    None,
    None,
    None,
    None,
);

The code examples showcase the different approaches: rust-bindgen requires more setup but offers flexibility, while windows-rs provides a more streamlined, Windows-specific API.

6,825

Safe interop between Rust and C++

Pros of cxx

  • More general-purpose, allowing Rust-C++ interop for various projects
  • Provides bidirectional FFI, enabling seamless integration between Rust and C++
  • Offers automatic generation of idiomatic Rust and C++ code

Cons of cxx

  • Requires more setup and configuration for Windows-specific functionality
  • May have a steeper learning curve for developers primarily working with Windows APIs
  • Less specialized for Windows development compared to windows-rs

Code Comparison

cxx:

#[cxx::bridge]
mod ffi {
    extern "C++" {
        include!("example.h");
        fn do_something(value: i32) -> String;
    }
}

windows-rs:

use windows::Win32::UI::WindowsAndMessaging::*;

let hwnd = unsafe { CreateWindowExA(...) };
unsafe { ShowWindow(hwnd, SW_SHOW) };

Summary

cxx is a versatile tool for Rust-C++ interoperability, offering bidirectional FFI and automatic code generation. It's suitable for various projects but may require more setup for Windows-specific tasks. windows-rs, on the other hand, is tailored for Windows development, providing a more straightforward approach to working with Windows APIs. The choice between the two depends on the project's specific requirements and the developer's familiarity with Windows development.

Rust bindings to Windows API

Pros of winapi-rs

  • More mature and stable, with a longer history of use in the Rust ecosystem
  • Provides a lower-level, more direct mapping to Windows API functions
  • Smaller binary size and potentially faster compile times

Cons of winapi-rs

  • Requires more manual memory management and unsafe code
  • Less idiomatic Rust API, often requiring more boilerplate
  • Slower development pace and less frequent updates

Code Comparison

winapi-rs:

use winapi::um::winuser::{MessageBoxW, MB_OK};
use std::ptr::null_mut;

unsafe {
    MessageBoxW(null_mut(), wide_string!("Hello").as_ptr(), wide_string!("Title").as_ptr(), MB_OK);
}

windows-rs:

use windows::Win32::UI::WindowsAndMessaging::{MessageBoxW, MESSAGEBOX_STYLE};

unsafe {
    MessageBoxW(None, "Hello", "Title", MESSAGEBOX_STYLE::MB_OK);
}

The windows-rs example demonstrates a more Rust-idiomatic approach with better type safety and less manual string conversion. However, winapi-rs provides a closer representation of the underlying Windows API, which may be preferred in certain low-level scenarios.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

windows-rs provides Rust crates for Windows APIs, from COM support and system services to UI and raw bindings.

Prefer the focused crates below when they cover the functionality you need. For additional APIs, windows-bindgen can generate a minimal project-specific binding, while windows and windows-sys provide broad API coverage behind feature flags for binary applications.

Reusable libraries should avoid the windows and windows-sys umbrella crates. They add dependency weight and version churn, and several libraries can bring incompatible versions of the same large crate into one dependency tree. Prefer the focused crates for shared Windows types and generate any remaining private bindings with windows-bindgen.

Each crate page covers usage and maintenance. Generated API documentation is available on docs.rs.

Crates

Core types and interop

CrateDescription
windows-coreCOM and WinRT types, traits, and authoring macros.
windows-resultWindows error handling and propagation.
windows-stringsWindows string types, conversions, and macros.
windows-linkLinks C-style functions without import libraries.

Values and collections

CrateDescription
windows-collectionsWinRT collections.
windows-numericsGraphics vectors and matrices.
windows-referenceImplementation of WinRT IReference<T>.
windows-timeWinRT DateTime and TimeSpan types.

Async and threading

CrateDescription
windows-futureWinRT asynchronous operations as Rust futures.
windows-threadingSafe wrapper over the Win32 thread pool.

System services

CrateDescription
windows-registrySafe Windows registry access.
windows-servicesSupport for authoring Windows services.
windows-versionQueries the Windows version at runtime.

UI and graphics

CrateDescription
windows-reactorDeclarative UI library backed by WinUI 3.
windows-canvas2D graphics built on Direct2D.
windows-compositionWindows composition visuals.
windows-webviewSafe wrapper around the WebView2 browser control.
windows-windowWindow creation and message dispatch.
windows-pickersWindows file and folder pickers.
windows-animationWrapper around the Windows Animation Manager.
windows-reactor-setupStages the Windows App Runtime.

Code generation and metadata

CrateDescription
windows-clangGenerates RDL from C and C++ headers using libclang.
windows-defaultEmbedded Windows metadata for build tools.
windows-metadataReads and writes ECMA-335 metadata.
windows-rdlParses RDL and generates ECMA-335 metadata.
cppwinrtPackages the C++/WinRT compiler.

Macro implementation

These crates implement macros exported by windows-core. Applications should use the windows-core exports rather than depend on them directly.

CrateDescription
windows-implementImplements the #[implement] macro.
windows-interfaceImplements the #[interface] macro.

Windows API bindings

Use windows-bindgen when the focused crates above do not cover the APIs you need. Binary applications may instead prefer the convenience of the pre-generated windows or windows-sys umbrella crate.

CrateDescription
windows-bindgenGenerates Rust bindings from Windows metadata.
windowsTyped bindings for C-style, COM, and WinRT APIs.
windows-sysRaw bindings for C-style Windows APIs.