Question Asker
Question Asker

Reputation: 55

How to detect keystrokes and mouse movements using winit?

I am writing a program in Rust where I want to be able to get keystrokes and mouse movements and use them to control a camera (WASD and Mouse). How would I use winit to get these? I've been banging my head agains a wall for about an hour, and this is all I've come up with so far:

if self.input.key_pressed(VirtualKeyCode::Escape) || self.input.close_requested() {
                    *control_flow = ControlFlow::Exit;
                    return;
                } else {
                    for key_code in VirtualKeyCode.iter() {
                        if self.input.key_pressed(key_code) {
                            println!("Pressed key: {:?}", key_code);
                        }
                    }
                }

I have no idea where to even start with getting mouse movements. Any help would be much appritiated as I'm new to programming and find the winit documentation on KeyboardInput to be rather lacking in depth.

Upvotes: 2

Views: 2426

Answers (1)

etchesketch
etchesketch

Reputation: 873

It looks like they have an example in their github repo https://github.com/rust-windowing/winit/blob/master/examples/key_binding.rs

The relevant code appears to be

event_loop.run(move |event, _, control_flow| {
        *control_flow = ControlFlow::Wait;

        match event {
            Event::WindowEvent { event, .. } => match event {
                WindowEvent::CloseRequested => *control_flow = ControlFlow::Exit,
                WindowEvent::ModifiersChanged(new) => {
                    modifiers = new.state();
                }
                WindowEvent::KeyboardInput { event, .. } => {
                    if event.state == ElementState::Pressed && !event.repeat {
                        match event.key_without_modifiers().as_ref() {
                            Key::Character("1") => {
                                if modifiers.shift_key() {
                                    println!("Shift + 1 | logical_key: {:?}", event.logical_key);
                                } else {
                                    println!("1");
                                }
                            }
                            _ => (),
                        }
                    }
                }
                _ => (),
            },
            _ => (),
        };
    });

In the above example mouse events are not being handled though. To handle mouse events match event with WindowEvent::CursorMoved {device_id,position}.

Upvotes: 1

Related Questions