-
Notifications
You must be signed in to change notification settings - Fork 947
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
No getkey()? #1010
Comments
See the docs: You get events as they happen delivered to the closure you pass to Edit: ... If you want to remember some state across events, implementing that is your responsibility. Maybe we could change this issue to be about including an example for this pattern. |
@felixrabe What about access to the current keyboard state, XkbGetState() for example. |
The ability to check a key isn't available on all Winit platforms (e.g. web) so the API doesn't expose a way to do it. |
It could be a candidate for adding to a platform-specific extension trait. |
For anyone visiting this issue in 2025, tracking the keyboard state requires setting: event_loop.listen_device_events(DeviceEvents::Always); to ensure device events are delivered while your application does not have focus. It is still not possible to correctly initialize the state of each key without the ability to query that state at application startup. The state of a key can be tracked correctly after the first key press or release. An example with winit 0.30.9 use std::collections::HashMap;
use winit::application::ApplicationHandler;
use winit::event::{DeviceEvent, DeviceId, ElementState, RawKeyEvent, WindowEvent};
use winit::event_loop::{ActiveEventLoop, DeviceEvents, EventLoop};
use winit::keyboard::{KeyCode, PhysicalKey};
use winit::window::{Window, WindowId};
#[derive(Default)]
struct App {
window: Option<Window>,
keys: HashMap<KeyCode, ElementState>,
}
impl ApplicationHandler for App {
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
self.window = Some(event_loop.create_window(Default::default()).unwrap());
}
fn device_event(
&mut self,
_event_loop: &ActiveEventLoop,
_device_id: DeviceId,
event: DeviceEvent,
) {
if let DeviceEvent::Key(RawKeyEvent {
physical_key: PhysicalKey::Code(key_code),
state,
}) = event
{
self.keys.insert(key_code, state);
println!("{:#?}", self.keys);
}
}
fn window_event(
&mut self,
event_loop: &ActiveEventLoop,
_window_id: WindowId,
event: WindowEvent,
) {
if let WindowEvent::CloseRequested = event {
event_loop.exit();
}
}
}
fn main() {
let event_loop = EventLoop::new().unwrap();
event_loop.listen_device_events(DeviceEvents::Always);
let mut app = App::default();
event_loop.run_app(&mut app).unwrap();
} |
To probe for the current state of a key or button.
Edit: Getter for mouse location.
The text was updated successfully, but these errors were encountered: