microsoft / windows-rs

Rust for Windows
https://kennykerr.ca/rust-getting-started/
Apache License 2.0
10.1k stars 473 forks source link

Try is not implemented for `Foundation::HWND` #3147

Closed aurelienlh closed 2 days ago

aurelienlh commented 3 days ago

Summary

_ I launch the code as it is and it print the error int the title but It's working if I erase the "?" line 37 before the object "CreateWindowExA" in crates/samples/windows/createwindow/src/main.rs

Crate manifest

[package]
name = "driver1"
version = "0.1.0"
edition = "2021"
[dependencies.windows]
version = "0.57.0"
features = [
    "Win32_Graphics_Gdi",
    "Win32_System_LibraryLoader",
    "Win32_UI_WindowsAndMessaging",
]

Crate code

use windows::{
    core::*, Win32::Foundation::*, Win32::Graphics::Gdi::ValidateRect,
    Win32::System::LibraryLoader::GetModuleHandleA, Win32::UI::WindowsAndMessaging::*,
};

fn main() -> Result<()> {
    unsafe {
        let instance = GetModuleHandleA(None)?;
        let window_class = s!("window");

        let wc = WNDCLASSA {
            hCursor: LoadCursorW(None, IDC_ARROW)?,
            hInstance: instance.into(),
            lpszClassName: window_class,

            style: CS_HREDRAW | CS_VREDRAW,
            lpfnWndProc: Some(wndproc),
            ..Default::default()
        };

        let atom = RegisterClassA(&wc);
        debug_assert!(atom != 0);

        CreateWindowExA(
            WINDOW_EX_STYLE::default(),
            window_class,
            s!("This is a sample window"),
            WS_OVERLAPPEDWINDOW | WS_VISIBLE,
            CW_USEDEFAULT,
            CW_USEDEFAULT,
            CW_USEDEFAULT,
            CW_USEDEFAULT,
            None,
            None,
            instance,
            None,
        )?;

        let mut message = MSG::default();

        while GetMessageA(&mut message, None, 0, 0).into() {
            DispatchMessageA(&message);
        }

        Ok(())
    }
}

extern "system" fn wndproc(window: HWND, message: u32, wparam: WPARAM, lparam: LPARAM) -> LRESULT {
    unsafe {
        match message {
            WM_PAINT => {
                println!("WM_PAINT");
                _ = ValidateRect(window, None);
                LRESULT(0)
            }
            WM_DESTROY => {
                println!("WM_DESTROY");
                PostQuitMessage(0);
                LRESULT(0)
            }
            _ => DefWindowProcA(window, message, wparam, lparam),
        }
    }
}
riverar commented 2 days ago

https://github.com/microsoft/windows-rs/tree/master/crates/samples

You need to pick the version of the samples that match the version of the crate you're trying to use.

The samples for 0.57 can be found at https://github.com/microsoft/windows-rs/blob/0.57.0/crates/samples/. This create window sample does not have a ? on that line. (https://github.com/microsoft/windows-rs/blob/0.57.0/crates/samples/windows/create_window/src/main.rs#L39)

Hope that helps!