rust windwos 两个edit框
use winapi::shared::minwindef::LOWORD;
use windows::{
core::*,
Win32::{
Foundation::*,
Graphics::Gdi::{BeginPaint, EndPaint, PAINTSTRUCT},
System::LibraryLoader::GetModuleHandleA,
UI::WindowsAndMessaging::*,
},
};
// 两个全局静态变量,用于保存 Edit 控件的句柄
static mut EDIT_BOX1: HWND = HWND(std::ptr::null_mut());
static mut EDIT_BOX2: HWND = HWND(std::ptr::null_mut());
// 按钮的唯一 ID(WM_COMMAND 中用来识别该按钮的点击事件)
const BTN_ID: u16 = 1001;
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, "Failed to register window class!");
let hwnd = CreateWindowExA(
WINDOW_EX_STYLE::default(),
window_class,
s!("Window with Two Edit Boxes"),
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 main window");
}
let hwnd_c = hwnd.clone();
let hwnd_c1 = hwnd_c.clone();
// 创建第一个 Edit 控件
let edit_box1 = CreateWindowExA(
WINDOW_EX_STYLE::default(),
s!("EDIT"),
s!(""), // 初始文本为空
WS_CHILD | WS_VISIBLE | WS_BORDER, // 样式:子控件、可见、带边框
10, // X 位置
10, // Y 位置
260, // 宽度
30, // 高度
hwnd.unwrap(),
None, // 不需要在 WM_COMMAND 里直接识别它,可填 None
instance,
None,
);
if edit_box1.is_err() {
panic!("Failed to create edit_box1");
}
EDIT_BOX1 = edit_box1.unwrap();
// 创建第二个 Edit 控件
let edit_box2 = CreateWindowExA(
WINDOW_EX_STYLE::default(),
s!("EDIT"),
s!(""),
WS_CHILD | WS_VISIBLE | WS_BORDER,
10,
50,
260,
30,
hwnd_c.unwrap(),
None,
instance,
None,
);
if edit_box2.is_err() {
panic!("Failed to create edit_box2");
}
EDIT_BOX2 = edit_box2.unwrap();
// 创建按钮
let button1 = CreateWindowExA(
WINDOW_EX_STYLE::default(),
s!("BUTTON"),
s!("Click Me!"),
WS_VISIBLE | WS_CHILD,
10,
100,
100,
40,
hwnd_c1.unwrap(),
// 把按钮的 ID 传给 HMENU,这样在 WM_COMMAND 中就能通过 wm_id == BTN_ID 来判断
HMENU(BTN_ID as *mut std::ffi::c_void),
instance,
None,
);
if button1.is_err() {
panic!("Failed to create button");
}
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_COMMAND => {
let wm_id = LOWORD(wparam.0 as u32);
// 判断是否是我们定义的按钮被点击
if wm_id == BTN_ID {
// 按钮点击事件:读取两个 Edit 框的内容并显示
let text1 = get_edit_text(EDIT_BOX1);
let text2 = get_edit_text(EDIT_BOX2);
let msg_for_box = format!(
"Edit Box 1 Content:\n{}\n\nEdit Box 2 Content:\n{}",
text1, text2
);
MessageBoxA(window, PCSTR(msg_for_box.as_ptr()), s!("Two Edit Boxes"), MB_OK);
}
LRESULT(0)
}
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),
}
}
}
/// 读取指定 Edit 控件内的文本(ANSI)到 String
fn get_edit_text(hwnd_edit: HWND) -> String {
unsafe {
let mut buffer = [0u8; 256];
let len = GetWindowTextA(hwnd_edit, &mut buffer);
String::from_utf8_lossy(&buffer[..len as usize]).to_string()
}
}
fn esl_id11(s: &str) -> String {
// 1) 取从第 8 个字符开始的子串(假设 s 至少有 9 个字符,否则会 panic,可自行做更多安全检查)
let decimal_str = &s[8..];
// 2) 将该子串解析为十进制整数
let decimal_val = match decimal_str.parse::<u64>() {
Ok(val) => val,
Err(_) => {
// 解析失败时可自定义返回值或处理逻辑
eprintln!("Failed to parse '{}' as a decimal number", decimal_str);
return "PARSE_ERROR\n".to_string();
}
};
// 3) 转成 16 进制字符串(不做任何零填充)
let hex_str = format!("{:x}", decimal_val); // 小写十六进制
// 定义一个“安全切片”函数,超出范围时返回空串(Python 的切片不会报错,Rust 默认会 panic)
fn safe_slice(st: &str, start: usize, end: usize) -> &str {
st.get(start..end).unwrap_or("")
}
// 4) 按照“每 2 个字符”分段:_s[0:2], _s[2:4], _s[4:6], _s[6:8]
let part1 = safe_slice(&hex_str, 0, 2);
let part2 = safe_slice(&hex_str, 2, 4);
let part3 = safe_slice(&hex_str, 4, 6);
let part4 = safe_slice(&hex_str, 6, 8);
// 5) 拼接为 "XX-XX-XX-XX\n" 并转大写
let esl_id_11 = format!("{}-{}-{}-{}{}", part1, part2, part3, part4, "\n").to_uppercase();
// 打印与返回
println!("{}", esl_id_11);
esl_id_11
}
[package]
name = "to18"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
windows-sys="0.59.0"
winapi = { version = "0.3.8", features = ["winuser","libloaderapi"] }
eframe = "0.24"
egui = "0.24"
[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",
]
效果图