How to call ReadConsoleInputW using Zig in Windows
ReadConsoleInputW can be used to mimic kbhit() C function found in Borland C/C++.OS: Windows 10 22H2
Zig: 0.12
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 }); | |
} | |
} | |
} | |
} | |
} |
PS C:\prj> zig build-exe -lc .\ReadConsoleInputW.zig
No comments:
Post a Comment