Press a key using WIN32 API in Zig

This commit is contained in:
Marek S. Łukasiewicz 2026-02-08 13:20:56 +01:00
parent 8783d4f43e
commit 917c881da8
5 changed files with 103 additions and 0 deletions

50
build.zig Normal file
View file

@ -0,0 +1,50 @@
const std = @import("std");
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
const win32_dep = b.dependency("zigwin32", .{});
const mod = b.addModule("win_telegraph", .{
.root_source_file = b.path("src/root.zig"),
.target = target,
.imports = &.{
.{ .name = "win32", .module = win32_dep.module("win32") },
},
});
const exe = b.addExecutable(.{
.name = "win_telegraph",
.root_module = b.createModule(.{
.root_source_file = b.path("src/main.zig"),
.target = target,
.optimize = optimize,
.imports = &.{
.{ .name = "win_telegraph", .module = mod },
},
}),
});
b.installArtifact(exe);
const run_step = b.step("run", "Run the app");
const run_cmd = b.addRunArtifact(exe);
run_step.dependOn(&run_cmd.step);
run_cmd.step.dependOn(b.getInstallStep());
if (b.args) |args| {
run_cmd.addArgs(args);
}
const mod_tests = b.addTest(.{
.root_module = mod,
});
const run_mod_tests = b.addRunArtifact(mod_tests);
const exe_tests = b.addTest(.{
.root_module = exe.root_module,
});
const run_exe_tests = b.addRunArtifact(exe_tests);
const test_step = b.step("test", "Run tests");
test_step.dependOn(&run_mod_tests.step);
test_step.dependOn(&run_exe_tests.step);
}

20
build.zig.zon Normal file
View file

@ -0,0 +1,20 @@
.{
.name = .win_telegraph,
.version = "0.0.0",
.fingerprint = 0xd9b97c83665bc0f3, // Changing this has security and trust implications.
.minimum_zig_version = "0.15.2",
.dependencies = .{
.zigwin32 = .{
.url = "git+https://github.com/marlersoft/zigwin32.git#3be22a8d33d330662b1fbb5b68c9411bf0293e27",
.hash = "zigwin32-25.0.28-preview-AAAAAB6N5AP3iLHsHKzg7r_aiDyYWo92qLOAG2eBLWhE",
},
},
.paths = .{
"build.zig",
"build.zig.zon",
"paddle",
"src",
"LICENSE",
//"README.md",
},
}

3
mise.toml Normal file
View file

@ -0,0 +1,3 @@
[tools]
zig = "0.15.2"
zls = "0.15.1"

10
src/main.zig Normal file
View file

@ -0,0 +1,10 @@
const std = @import("std");
const win_telegraph = @import("win_telegraph");
pub fn main() !void {
std.debug.print("Will press space in 3 seconds\n", .{});
std.Thread.sleep(3 * std.time.ns_per_s);
win_telegraph.setKey(.SPACE, true);
win_telegraph.setKey(.SPACE, false);
}

20
src/root.zig Normal file
View file

@ -0,0 +1,20 @@
const std = @import("std");
const win32 = @import("win32").everything;
pub const Key = win32.VIRTUAL_KEY;
pub fn setKey(key: Key, pressed: bool) void {
var ip: win32.INPUT = .{
.type = .KEYBOARD,
.Anonymous = .{
.ki = .{
.wVk = key, // virtual-key code for the chosen key
.wScan = 0, // hardware scan code for key
.dwFlags = .{ .KEYUP = if (pressed) 0 else 1 },
.time = 0,
.dwExtraInfo = 0,
},
},
};
_ = win32.SendInput(1, @ptrCast(&ip), @sizeOf(win32.INPUT));
}