Skip to content

Instantly share code, notes, and snippets.

@Ciantic
Created February 18, 2023 00:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ciantic/e8762b297b3b77b2fdab8692bd52b3f4 to your computer and use it in GitHub Desktop.
Save Ciantic/e8762b297b3b77b2fdab8692bd52b3f4 to your computer and use it in GitHub Desktop.
Just simple CreateThread example with proper way to QUIT.
use windows::{
core::{GUID, HSTRING},
Win32::{
Foundation::HWND,
System::{
Com::{CoInitializeEx, COINIT_APARTMENTTHREADED},
Threading::{
CreateThread, GetCurrentThreadId, WaitForSingleObject, THREAD_CREATION_FLAGS,
},
},
UI::WindowsAndMessaging::{
DispatchMessageW, GetMessageW, PostQuitMessage, TranslateMessage, MSG, WM_USER,
},
},
};
unsafe extern "system" fn handler(_arg: *mut c_void) -> u32 {
let mut msg = MSG::default();
unsafe {
while GetMessageW(&mut msg, None, 0, 0).as_bool() {
if msg.message == WM_USER + 0x10 {
PostQuitMessage(0);
}
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
}
0
}
fn create_thread() {
let thread_id = None;
let handle = unsafe {
CreateThread(
None,
0,
Some(handler),
None,
THREAD_CREATION_FLAGS::default(),
thread_id,
)
}
.unwrap();
// Send a message to the notification thread to quit
unsafe {
PostThreadMessageW(
win_thread_id,
WM_USER + 0x10,
WPARAM::default(),
LPARAM::default(),
);
}
// Join the thread
unsafe { WaitForSingleObject(handle, u32::MAX) };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment