### Win32 Helper Utilities (win32.zig) Source: https://context7.com/marlersoft/zigwin32/llms.txt Leverage Zig-idiomatic wrappers from the win32.zig module for tasks like creating Unicode strings, handling boolean constants, formatting error codes, initializing GUIDs and property keys, extracting coordinates from LPARAM, and extracting low/high words from 32-bit values. ```zig const std = @import("std"); const win32 = @import("win32"); const zig = win32.zig; pub fn main() void { // Unicode string literal helper const wide_str = zig.L("Hello, World!"); // Returns [*:0]const u16 // Boolean constants const true_val = zig.TRUE; // BOOL = 1 const false_val = zig.FALSE; // BOOL = 0 // Format Win32 error codes for display const error_code: u32 = 5; // ERROR_ACCESS_DENIED std.debug.print("Error: {} ", .{zig.fmtError(error_code)}); // Output: "Error: 5 (Access is denied.)" // Just the message without the code std.debug.print("{} ", .{zig.fmtErrorString(error_code)}); // Output: "Access is denied." // GUID initialization from string const guid = zig.Guid.initString("01234567-89AB-CDEF-0123-456789ABCDEF"); // Property key initialization const prop_key = zig.PropertyKey.init("01234567-89AB-CDEF-0123-456789ABCDEF", 2); // Extract coordinates from LPARAM (mouse messages) const lparam: win32.foundation.LPARAM = 0x00640032; // x=50, y=100 const x = zig.xFromLparam(lparam); const y = zig.yFromLparam(lparam); const point = zig.pointFromLparam(lparam); // Low/high word extraction const value: u32 = 0xDEADBEEF; const low = zig.loword(value); // 0xBEEF const high = zig.hiword(value); // 0xDEAD } ``` -------------------------------- ### Configure Build System (build.zig) Source: https://context7.com/marlersoft/zigwin32/llms.txt In your build.zig file, add zigwin32 as a dependency and import its module into your executable. ```zig // build.zig const std = @import("std"); pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); const win32 = b.dependency("win32", .{}).module("win32"); const exe = b.addExecutable(.{ .name = "my-app", .root_source_file = b.path("src/main.zig"), .target = target, .optimize = optimize, }); exe.root_module.addImport("win32", win32); b.installArtifact(exe); } ``` -------------------------------- ### Create and Display a Basic Win32 Window in Zig Source: https://context7.com/marlersoft/zigwin32/llms.txt This snippet shows how to register a window class, create a window, and enter a message loop to display a basic Win32 window. It includes a simple window procedure to handle `WM_DESTROY` and `WM_PAINT` messages. ```zig const std = @import("std"); const win32 = @import("win32"); const zig = win32.zig; const L = zig.L; const HWND = win32.foundation.HWND; const LPARAM = win32.foundation.LPARAM; const WPARAM = win32.foundation.WPARAM; const LRESULT = win32.foundation.LRESULT; const messaging = win32.ui.windows_and_messaging; const gdi = win32.graphics.gdi; fn wndProc(hwnd: HWND, msg: u32, wparam: WPARAM, lparam: LPARAM) callconv(.C) LRESULT { switch (msg) { messaging.WM_DESTROY => { messaging.PostQuitMessage(0); return 0; }, messaging.WM_PAINT => { var ps: gdi.PAINTSTRUCT = undefined; const hdc = gdi.BeginPaint(hwnd, &ps) orelse return 0; defer _ = gdi.EndPaint(hwnd, &ps); _ = gdi.TextOutW(hdc, 10, 10, L("Hello from zigwin32!"), 20); return 0; }, else => return messaging.DefWindowProcW(hwnd, msg, wparam, lparam), } } pub fn main() !void { const hInstance = win32.system.library_loader.GetModuleHandleW(null); const wc = messaging.WNDCLASSEXW{ .cbSize = @sizeOf(messaging.WNDCLASSEXW), .style = .{ }, .lpfnWndProc = wndProc, .cbClsExtra = 0, .cbWndExtra = 0, .hInstance = hInstance, .hIcon = null, .hCursor = messaging.LoadCursorW(null, messaging.IDC_ARROW), .hbrBackground = gdi.GetStockObject(gdi.WHITE_BRUSH), .lpszMenuName = null, .lpszClassName = L("ZigWin32Window"), .hIconSm = null, }; if (messaging.RegisterClassExW(&wc) == 0) { return error.RegisterClassFailed; } const hwnd = messaging.CreateWindowExW( .{ }, L("ZigWin32Window"), L("zigwin32 Window"), messaging.WS_OVERLAPPEDWINDOW, messaging.CW_USEDEFAULT, messaging.CW_USEDEFAULT, 800, 600, null, null, hInstance, null, ) orelse return error.CreateWindowFailed; _ = messaging.ShowWindow(hwnd, messaging.SW_SHOW); _ = messaging.UpdateWindow(hwnd); var msg: messaging.MSG = undefined; while (messaging.GetMessageW(&msg, null, 0, 0) != 0) { _ = messaging.TranslateMessage(&msg); _ = messaging.DispatchMessageW(&msg); } } ``` -------------------------------- ### Import Win32 Modules in Zig Source: https://context7.com/marlersoft/zigwin32/llms.txt Demonstrates how to import various Win32 API subsystems in Zig. Import only the modules you need to manage compile times. ```zig const win32 = @import("win32"); // Foundation - Core types and error codes const foundation = win32.foundation; // HANDLE, HWND, HRESULT, NTSTATUS, BOOL, POINT, RECT, SIZE // GetLastError, CloseHandle, SetLastError // UI - Windows, messaging, controls const ui = win32.ui; const messaging = ui.windows_and_messaging; // CreateWindow, DefWindowProc, PostMessage const controls = ui.controls; // Buttons, edit boxes, list views const hi_dpi = ui.hi_dpi; // DPI awareness APIs const shell = ui.shell; // Shell APIs, notifications // Graphics - Drawing and display const graphics = win32.graphics; const gdi = graphics.gdi; // GDI functions: TextOut, BitBlt, CreateBrush const direct2d = graphics.direct2d; // Direct2D APIs const direct3d11 = graphics.direct3d11; // Direct3D 11 APIs const direct3d12 = graphics.direct3d12; // Direct3D 12 APIs const dxgi = graphics.dxgi; // DXGI APIs // System - OS services const system = win32.system; const threading = system.threading; // Threads, synchronization primitives const memory = system.memory; // Virtual memory, heap APIs const com = system.com; // COM infrastructure const registry = system.registry; // Registry access const io = system.io; // I/O completion ports // Networking const networking = win32.networking; const win_sock = networking.win_sock; // Winsock TCP/UDP const win_http = networking.win_http; // WinHTTP APIs // Security const security = win32.security; const crypto = security.cryptography; // CryptoAPI, CNG // Storage const storage = win32.storage; // File system, XPS // Helper module with Zig-idiomatic wrappers const z = win32.zig; // L(), FAILED(), SUCCEEDED(), fmtError(), closeHandle(), etc. ``` -------------------------------- ### Add zigwin32 as a Dependency (build.zig.zon) Source: https://context7.com/marlersoft/zigwin32/llms.txt Declare zigwin32 as a dependency in your project's build.zig.zon file. Remember to add the hash after the first build attempt. ```zig // build.zig.zon .{ .name = "my-app", .version = "0.1.0", .dependencies = .{ .win32 = .{ .url = "https://github.com/marlersoft/zigwin32/archive/refs/heads/main.tar.gz", // Add hash after first build attempt }, }, } ``` -------------------------------- ### Create and Manage Threads in Zig Source: https://context7.com/marlersoft/zigwin32/llms.txt Demonstrates creating a new thread, passing data to it, and waiting for its completion. Ensure proper error handling for thread creation and synchronization. ```zig const std = @import("std"); const win32 = @import("win32"); const zig = win32.zig; const threading = win32.system.threading; const foundation = win32.foundation; fn threadProc(param: ?*anyopaque) callconv(.C) u32 { const value = @as(*u32, @ptrCast(@alignCast(param))); std.debug.print("Thread received value: {d} ", .{value.*}); value.* *= 2; return 0; } pub fn main() !void { var data: u32 = 42; // Create a new thread const thread_handle = threading.CreateThread( null, // default security attributes 0, // default stack size threadProc, // thread function &data, // parameter threading.THREAD_CREATE_RUN_IMMEDIATELY, null, // don't need thread ID ) orelse { const err = foundation.GetLastError(); std.debug.print("CreateThread failed: {s} ", .{zig.fmtError(@intFromEnum(err))}); return error.CreateThreadFailed; }; defer zig.closeHandle(thread_handle); // Wait for thread to complete (infinite timeout) const wait_result = threading.WaitForSingleObject(thread_handle, threading.INFINITE); if (wait_result != .WAIT_OBJECT_0) { return error.WaitFailed; } std.debug.print("Thread completed. New value: {d} ", .{data}); // Output: Thread completed. New value: 84 } ``` -------------------------------- ### TCP Client with WinSock in Zig Source: https://context7.com/marlersoft/zigwin32/llms.txt Establishes a TCP connection to a server, sends an HTTP request, and receives a response using Zig's WinSock bindings. Ensure Winsock is initialized before use and cleaned up afterward. ```zig const std = @import("std"); const win32 = @import("win32"); const zig = win32.zig; const ws = win32.networking.win_sock; pub fn main() !void { // Initialize Winsock var wsa_data: ws.WSADATA = undefined; const startup_result = ws.WSAStartup(0x0202, &wsa_data); if (startup_result != 0) { std.debug.print("WSAStartup failed: {d} ", .{startup_result}); return error.WSAStartupFailed; } defer _ = ws.WSACleanup(); // Create TCP socket const sock = ws.socket(ws.AF_INET, ws.SOCK_STREAM, ws.IPPROTO_TCP); if (sock == ws.INVALID_SOCKET) { const err = ws.WSAGetLastError(); std.debug.print("socket() failed: {d} ", .{err}); return error.SocketCreateFailed; } defer _ = ws.closesocket(sock); // Setup server address (localhost:8080) var server_addr = ws.sockaddr_in{ .sin_family = ws.AF_INET, .sin_port = ws.htons(8080), .sin_addr = .{ .S_un = .{ .S_addr = ws.htonl(0x7F000001) } }, // 127.0.0.1 .sin_zero = [_]u8{0} ** 8, }; // Connect to server const connect_result = ws.connect(sock, @ptrCast(&server_addr), @sizeOf(ws.sockaddr_in)); if (connect_result == ws.SOCKET_ERROR) { const err = ws.WSAGetLastError(); std.debug.print("connect() failed: {d} ", .{err}); return error.ConnectFailed; } // Send data const message = "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n"; const send_result = ws.send(sock, message.ptr, @intCast(message.len), 0); if (send_result == ws.SOCKET_ERROR) { return error.SendFailed; } // Receive response var buffer: [1024]u8 = undefined; const recv_result = ws.recv(sock, &buffer, buffer.len, 0); if (recv_result > 0) { std.debug.print("Received: {s} ", .{buffer[0..@intCast(recv_result)]}); } } ``` -------------------------------- ### Using Foundation Types and Constants Source: https://context7.com/marlersoft/zigwin32/llms.txt Utilize core Windows types like HANDLE and HWND, common HRESULT and NTSTATUS codes, and constants such as MAX_PATH. The zig module provides helpers like SUCCEEDED and FAILED for checking HRESULT values. ```zig const win32 = @import("win32"); const foundation = win32.foundation; pub fn main() void { // Handle types const invalid_handle = foundation.INVALID_HANDLE_VALUE; // Common HRESULT values const not_impl = foundation.E_NOTIMPL; const out_of_mem = foundation.E_OUTOFMEMORY; const invalid_arg = foundation.E_INVALIDARG; const fail = foundation.E_FAIL; // NTSTATUS codes const success = foundation.STATUS_SUCCESS; const access_denied = foundation.STATUS_ACCESS_DENIED; const pending = foundation.STATUS_PENDING; // Common constants const max_path = foundation.MAX_PATH; // 260 // Check HRESULT success/failure const zig = win32.zig; const hr: foundation.HRESULT = 0; if (zig.SUCCEEDED(hr)) { // Operation succeeded } if (zig.FAILED(hr)) { // Operation failed } } ``` -------------------------------- ### GDI Graphics Operations in Zig Source: https://context7.com/marlersoft/zigwin32/llms.txt This snippet demonstrates GDI drawing operations using zigwin32 helpers, including filling rectangles, drawing text (ANSI and Unicode), and measuring text. It also shows how to safely manage GDI resources like brushes and device contexts. ```zig const std = @import("std"); const win32 = @import("win32"); const zig = win32.zig; const gdi = win32.graphics.gdi; const HWND = win32.foundation.HWND; pub fn paintWindow(hwnd: HWND) void { // Safe begin/end paint with panic on failure const hdc, const ps = zig.beginPaint(hwnd); defer zig.endPaint(hwnd, &ps); // Create and use a solid brush const red_brush = zig.createSolidBrush(0x000000FF); // BGR format defer zig.deleteObject(@ptrCast(red_brush)); // Fill a rectangle const rect = win32.foundation.RECT{ .left = 10, .top = 10, .right = 100, .bottom = 100 }; zig.fillRect(hdc, rect, red_brush); // Text output (ANSI) zig.textOutA(hdc, 120, 50, "Hello, GDI!"); // Text output (Wide/Unicode) zig.textOutW(hdc, 120, 80, zig.L("Unicode Text")); // Get text dimensions const text = "Measure me"; const size = zig.getTextExtentA(hdc, text); std.debug.print("Text width: {}, height: \n", .{ size.cx, size.cy }); // Invalidate window to trigger repaint zig.invalidateHwnd(hwnd); } pub fn cleanupDC(hdc: gdi.HDC) void { // Safe DC deletion with panic on failure zig.deleteDc(hdc); } ``` -------------------------------- ### Import and Access Win32 Modules Source: https://context7.com/marlersoft/zigwin32/llms.txt Import the win32 module and access its hierarchical API structure for various subsystems like foundation, graphics, and UI. ```zig const win32 = @import("win32"); // Access foundation types const HANDLE = win32.foundation.HANDLE; const HWND = win32.foundation.HWND; const BOOL = win32.foundation.BOOL; // Access specific subsystems const gdi = win32.graphics.gdi; const messaging = win32.ui.windows_and_messaging; const threading = win32.system.threading; // Or import everything at once (larger compile times) const everything = win32.everything; ``` -------------------------------- ### Configure MessageBox Panic Handler Source: https://context7.com/marlersoft/zigwin32/llms.txt Set up a custom panic handler that displays a message box with the error details before crashing the application. This is configured in the root module. ```zig const std = @import("std"); const win32 = @import("win32"); const zig = win32.zig; // Set up message box panic handler in root module pub const panic = zig.messageBoxThenPanic(.{ .title = "Application Error", .style = .{ .ICONERROR = 1, }, }).panic; pub fn main() void { // Any panic will now show a message box first riskyOperation() catch |err| { std.debug.panic("Operation failed: {}", .{err}); // Shows message box with "Operation failed: ..." then crashes }; } fn riskyOperation() !void { return error.SomethingWentWrong; } ``` -------------------------------- ### Create Zigwin32 Version Branches Script Source: https://github.com/marlersoft/zigwin32/wiki/Branching This shell script automates the creation of git branches for different win32metadata versions. It checks out each version, resets the current branch, commits the changes, and creates a new branch for the next version, effectively simulating the repository's growth and history clearing process. ```sh #!/usr/bin/env sh set -ex branches=$(cat < 1.0x, 120 DPI -> 1.25x, 144 DPI -> 1.5x // Scale integer values for DPI const base_width: i32 = 100; const scaled_width = zig.scaleDpi(i32, base_width, dpi); std.debug.print("Base width: {d}, Scaled: {d} ", .{ base_width, scaled_width }); // Scale float values for DPI const base_font_size: f32 = 12.0; const scaled_font = zig.scaleDpi(f32, base_font_size, dpi); std.debug.print("Base font: {d:.1}pt, Scaled: {d:.1}pt ", .{ base_font_size, scaled_font }); // Get client area size const client_size = zig.getClientSize(hwnd); std.debug.print("Client area: {d}x{d} ", .{ client_size.cx, client_size.cy }); } ``` -------------------------------- ### Manage Window Data with Long Pointer Operations Source: https://context7.com/marlersoft/zigwin32/llms.txt Store and retrieve application-defined data associated with a window using `setWindowLongPtrW` and `getWindowLongPtrW`. Ensure UNICODE is set to true for automatic W-suffix function selection. ```zig const std = @import("std"); const win32 = @import("win32"); const zig = win32.zig; const HWND = win32.foundation.HWND; const messaging = win32.ui.windows_and_messaging; const WindowData = struct { counter: u32, name: [*:0]const u8, }; pub fn setupWindowData(hwnd: HWND, data: *WindowData) void { // Store pointer in window's user data (GWLP_USERDATA = -21) // Uses wide version (W suffix) - set UNICODE = true in root for automatic selection _ = zig.setWindowLongPtrW(hwnd, messaging.GWLP_USERDATA, @intFromPtr(data)); } pub fn getWindowData(hwnd: HWND) ?*WindowData { const ptr = zig.getWindowLongPtrW(hwnd, messaging.GWLP_USERDATA); if (ptr == 0) return null; return @ptrFromInt(ptr); } // Example in window procedure fn wndProc(hwnd: HWND, msg: u32, wparam: usize, lparam: isize) callconv(.C) isize { switch (msg) { messaging.WM_CREATE => { var data = WindowData{ .counter = 0, .name = "MyWindow" }; setupWindowData(hwnd, &data); return 0; }, messaging.WM_LBUTTONDOWN => { if (getWindowData(hwnd)) |data| { data.counter += 1; std.debug.print("Click count: {} ", .{data.counter}); } return 0; }, else => return messaging.DefWindowProcW(hwnd, msg, wparam, lparam), } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.