Created
May 1, 2025 14:43
-
-
Save DavidArsene/441c54c15cae83acc86b3511cd853672 to your computer and use it in GitHub Desktop.
Tiny Ctrl+C handler for Rust. Windows-only, thread-unsafe.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #![allow(static_mut_refs)] | |
| use windows::core::BOOL; | |
| use windows::Win32::Foundation::*; | |
| use windows::Win32::System::Console::*; | |
| #[derive(Debug, Clone, Copy, PartialEq, Eq)] | |
| pub enum Event { | |
| None, | |
| CtrlC, | |
| CtrlBreak, | |
| CtrlClose, | |
| CtrlLogoff, | |
| CtrlShutdown, | |
| } | |
| static mut CTRL_C: Event = Event::None; | |
| unsafe extern "system" fn handler_routine(ctrl_type: u32) -> BOOL { | |
| if check() { | |
| std::process::exit(STATUS_CONTROL_C_EXIT.0); | |
| } | |
| CTRL_C = match ctrl_type { | |
| CTRL_C_EVENT => Event::CtrlC, | |
| CTRL_BREAK_EVENT => Event::CtrlBreak, | |
| CTRL_CLOSE_EVENT => Event::CtrlClose, | |
| CTRL_LOGOFF_EVENT => Event::CtrlLogoff, | |
| CTRL_SHUTDOWN_EVENT => Event::CtrlShutdown, | |
| _ => Event::None, | |
| }; | |
| TRUE | |
| } | |
| pub fn check() -> bool { which() != Event::None } | |
| pub fn which() -> Event { unsafe { CTRL_C } } | |
| unsafe extern "C" fn startup() { | |
| let _ = SetConsoleCtrlHandler(Some(handler_routine), true); | |
| } | |
| #[used] | |
| #[cfg_attr(not(target_env = "gnu"), unsafe(link_section = ".CRT$XCU"))] | |
| #[cfg_attr(target_env = "gnu", unsafe(link_section = ".ctors"))] | |
| static __CTOR: unsafe extern "C" fn() = startup; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment