Created
May 14, 2024 04:31
-
-
Save technoscavenger/7ffb72acdee9ff32daf85bec1c35d5d8 to your computer and use it in GitHub Desktop.
Calling ReadConsoleInputW in Zig
This file contains 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
const std = @import("std"); | |
const c = @cImport({ | |
@cInclude("windows.h"); | |
}); | |
const KEY_EVENT = 0x0001; | |
pub fn main() !void { | |
_ = std.os.windows.kernel32.SetConsoleOutputCP(65001); | |
const stdin = c.GetStdHandle(c.STD_INPUT_HANDLE); | |
var input_records: [1]c.INPUT_RECORD = undefined; | |
while (true) { | |
var num_events_read: u32 = 0; | |
const result = c.ReadConsoleInputW( | |
stdin, // Handle to the console input buffer | |
&input_records, // Pointer to the buffer to receive the input records | |
@intCast(input_records.len), // Number of input records to read | |
&num_events_read, // Pointer to the variable that receives the number of input records read | |
); | |
if (result != std.os.windows.TRUE) { | |
const err = std.os.windows.kernel32.GetLastError(); | |
std.debug.print("Failed to read console input: {}\n", .{err}); | |
break; | |
} | |
for (input_records[0..num_events_read]) |record| { | |
if (record.EventType == KEY_EVENT) { | |
const keyEvent = record.Event.KeyEvent; | |
if (keyEvent.bKeyDown != 0) { | |
// std.debug.print("Key down: {} (code: {})\n", .{ keyEvent.UnicodeChar, keyEvent.wVirtualKeyCode }); | |
std.debug.print("Key down: {c} (code: {})\n", .{ (keyEvent.uChar.AsciiChar), keyEvent.wVirtualKeyCode }); | |
} else { | |
// std.debug.print("Key up: {} (code: {})\n", .{ keyEvent.UnicodeChar, keyEvent.wVirtualKeyCode }); | |
std.debug.print("Key up: {} (code: {})\n", .{ keyEvent.uChar.UnicodeChar, keyEvent.wVirtualKeyCode }); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment