// rust use windows create editbox
use windows::{
core::*, Win32::{Foundation::*, Graphics::Gdi::{BeginPaint, EndPaint, PAINTSTRUCT}, System::LibraryLoader::GetModuleHandleA, UI::WindowsAndMessaging::*},
};
fn main() -> Result<()> {
unsafe {
let instance = GetModuleHandleA(None)?;
let window_class = s!("window");
let wc = WNDCLASSA {
hCursor: LoadCursorW(None, IDC_ARROW)?,
hInstance: instance.into(),
lpszClassName: window_class,
style: CS_HREDRAW | CS_VREDRAW,
lpfnWndProc: Some(wndproc),
..Default::default()
};
let atom = RegisterClassA(&wc);
debug_assert!(atom != 0);
let hwnd = CreateWindowExA(
WINDOW_EX_STYLE::default(),
window_class,
s!("Window with Edit Box"),
WS_OVERLAPPEDWINDOW | WS_VISIBLE,
CW_USEDEFAULT,
CW_USEDEFAULT,
600, // Window width
500, // Window height
None,
None,
instance,
None,
);
if hwnd.is_err() {
panic!("Failed to create window");
}
// 创建 Edit 控件
let edit_box = CreateWindowExA(
WINDOW_EX_STYLE::default(),
s!("EDIT"),
s!(""),
WS_CHILD | WS_VISIBLE | WS_BORDER ,
10, // X position
10, // Y position
260, // Width
30, // Height
hwnd.unwrap(),
None,
instance,
None,
);
if edit_box.is_err() {
panic!("Failed to create edit box");
}
let mut message = MSG::default();
while GetMessageA(&mut message, None, 0, 0).into() {
TranslateMessage(&message);
DispatchMessageA(&message);
}
Ok(())
}
}
extern "system" fn wndproc(window: HWND, message: u32, wparam: WPARAM, lparam: LPARAM) -> LRESULT {
unsafe {
match message {
WM_PAINT => {
let mut ps = PAINTSTRUCT::default();
let hdc = BeginPaint(window, &mut ps);
EndPaint(window, &ps);
LRESULT(0)
}
WM_DESTROY => {
PostQuitMessage(0);
LRESULT(0)
}
_ => DefWindowProcA(window, message, wparam, lparam),
}
}
}
cargo.toml 配置
[dependencies]
windows-sys="0.59.0"
#winapi = { version = "0.3.8", features = ["winuser","libloaderapi"] }
[dependencies.windows]
version = "0.58.0"
features = [
"Win32_Foundation",
"Win32_UI_WindowsAndMessaging",
"Win32_Security",
"Win32_System_Threading",
"Win32_Graphics_Gdi",
"Win32_System_LibraryLoader",
"Win32_UI_WindowsAndMessaging",
]