summaryrefslogtreecommitdiffstats
path: root/src/bin/windows-test/main.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/bin/windows-test/main.rs')
-rw-r--r--src/bin/windows-test/main.rs61
1 files changed, 61 insertions, 0 deletions
diff --git a/src/bin/windows-test/main.rs b/src/bin/windows-test/main.rs
new file mode 100644
index 0000000..b8f84fe
--- /dev/null
+++ b/src/bin/windows-test/main.rs
@@ -0,0 +1,61 @@
1use std::io::{self, Write};
2use std::ptr;
3use windows_sys::Win32::Foundation::HANDLE;
4use windows_sys::Win32::System::Console::{
5 GetConsoleMode, ReadConsoleW, SetConsoleMode, GetStdHandle, STD_INPUT_HANDLE,
6 ENABLE_ECHO_INPUT, ENABLE_LINE_INPUT,
7};
8
9fn main() -> io::Result<()> {
10 unsafe {
11 let h: HANDLE = GetStdHandle(STD_INPUT_HANDLE);
12 if h == std::ptr::null_mut() || h == -1_i32 as HANDLE { return Err(io::Error::last_os_error()); }
13
14 // save current mode
15 let mut mode: u32 = 0;
16 if GetConsoleMode(h, &mut mode) == 0 { return Err(io::Error::last_os_error()); }
17
18 // disable line input and echo so input is available per-key and not echoed
19 let new_mode = mode & !(ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT);
20 if SetConsoleMode(h, new_mode) == 0 { return Err(io::Error::last_os_error()); }
21
22 print!("Press keys (q to exit): ");
23 io::stdout().flush()?;
24
25 // ReadConsoleW reads UTF-16; we'll read one wchar at a time
26 let mut buf: [u16; 1] = [0];
27 loop {
28 let mut read = 0u32;
29 if ReadConsoleW(
30 h,
31 buf.as_mut_ptr() as *mut _,
32 1,
33 &mut read,
34 ptr::null_mut(),
35 ) == 0
36 {
37 // restore mode on error before returning
38 let _ = SetConsoleMode(h, mode);
39 return Err(io::Error::last_os_error());
40 }
41
42 let ch = std::char::from_u32(buf[0] as u32).unwrap_or('\u{FFFD}');
43 if ch == 'q' { break; } // q to exit
44
45 // handle Enter (CR) so output is readable
46 if ch == '\r' {
47 println!();
48 } else {
49 // show code point (no automatic console echo)
50 print!("[{:?}]", ch);
51 io::stdout().flush()?;
52 }
53 }
54
55 // restore original console mode
56 let _ = SetConsoleMode(h, mode);
57 println!("\nexited");
58 }
59
60 Ok(())
61}