Skip to content

Instantly share code, notes, and snippets.

@nathansizemore
Created July 28, 2019 16:26
Show Gist options
  • Save nathansizemore/ca838a0fce5fece9e159e12288143349 to your computer and use it in GitHub Desktop.
Save nathansizemore/ca838a0fce5fece9e159e12288143349 to your computer and use it in GitHub Desktop.
Rust - Win32 Window Example
// Copyright 2019 Nathan Sizemore <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
// If a copy of the MPL was not distributed with this file,
// You can obtain one at http://mozilla.org/MPL/2.0/.
extern crate winapi;
use std::ffi::OsStr;
use std::iter::once;
use std::mem;
use std::os::windows::ffi::OsStrExt;
use std::ptr::null_mut;
use winapi::shared::minwindef::{LPARAM, LRESULT, WPARAM};
use winapi::shared::windef::HWND;
use winapi::um::libloaderapi::GetModuleHandleW;
use winapi::um::winuser::{
CreateWindowExW,
DefWindowProcW,
DispatchMessageW,
GetMessageW,
MessageBoxW,
PostQuitMessage,
RegisterClassExW,
TranslateMessage,
CS_HREDRAW,
CS_OWNDC,
CS_VREDRAW,
CW_USEDEFAULT,
MB_OK,
MSG,
WM_DESTROY,
WNDCLASSEXW,
WS_OVERLAPPEDWINDOW,
WS_VISIBLE,
};
fn main() {
let window_class = WNDCLASSEXW {
cbSize: mem::size_of::<WNDCLASSEXW>() as u32,
style: CS_OWNDC | CS_HREDRAW | CS_VREDRAW,
lpfnWndProc: Some(main_window_callback),
cbClsExtra: 0,
cbWndExtra: 0,
hInstance: unsafe { GetModuleHandleW(null_mut()) },
hIcon: null_mut(),
hCursor: null_mut(),
hbrBackground: null_mut(),
lpszMenuName: null_mut(),
lpszClassName: to_wide("SmolGuiWindowClass").as_ptr(),
hIconSm: null_mut(),
};
unsafe {
if RegisterClassExW(&window_class) == 0 {
MessageBoxW(
null_mut(),
to_wide("Failed to register class.").as_ptr() as *const u16,
to_wide("ERROR").as_ptr() as *const u16,
MB_OK,
);
} else {
let handle = CreateWindowExW(
0,
to_wide("SmolGuiWindowClass").as_ptr(),
to_wide("Smol Gui").as_ptr(),
WS_OVERLAPPEDWINDOW | WS_VISIBLE,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
null_mut(),
null_mut(),
GetModuleHandleW(null_mut()),
null_mut(),
);
if handle.is_null() {
MessageBoxW(
null_mut(),
to_wide("Failed to create window.").as_ptr() as *const u16,
to_wide("ERROR").as_ptr() as *const u16,
MB_OK,
);
}
}
let mut msg: MSG = mem::uninitialized();
while GetMessageW(&mut msg as *mut MSG, 0 as HWND, 0, 0) != 0 {
TranslateMessage(&msg as *const MSG);
DispatchMessageW(&msg as *const MSG);
}
}
}
unsafe extern "system" fn main_window_callback(
hwnd: HWND,
message: u32,
wparam: WPARAM,
lparam: LPARAM,
) -> LRESULT {
match message {
WM_DESTROY => {
PostQuitMessage(0);
0
}
_ => DefWindowProcW(hwnd, message, wparam, lparam),
}
}
fn to_wide(s: &str) -> Vec<u16> {
OsStr::new(s).encode_wide().chain(once(0)).collect()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment