Skip to content

Instantly share code, notes, and snippets.

@RKennedy9064
Created July 23, 2019 18:47
Show Gist options
  • Save RKennedy9064/d6d78ab3b30ee6c667c25f25ab304b61 to your computer and use it in GitHub Desktop.
Save RKennedy9064/d6d78ab3b30ee6c667c25f25ab304b61 to your computer and use it in GitHub Desktop.
use std::{
borrow::BorrowMut,
error::Error
};
use winapi::{
shared::{
basetsd::{DWORD_PTR, UINT_PTR},
minwindef::{LPARAM, LRESULT, UINT, WPARAM},
windef::HWND
},
um::{
commctrl,
winuser
},
};
use winit::{
event::{Event, StartCause, WindowEvent},
event_loop::{ControlFlow, EventLoop, EventLoopProxy},
platform::windows::WindowExtWindows,
window::{Window, WindowBuilder}
};
const WM_NS_LAUNCH: UINT = 0x0401;
#[derive(Debug, Clone, Copy)]
enum NsEvent {
Launch,
}
#[derive(Debug)]
pub struct App {
event_loop: EventLoop<NsEvent>,
event_loop_proxy: EventLoopProxy<NsEvent>,
window: Window,
}
impl App {
pub fn new() -> Result<App, Box<dyn Error>> {
let (event_loop, window) = init()?;
let event_loop_proxy = event_loop.create_proxy();
let mut app = App {
event_loop,
event_loop_proxy,
window,
};
app.set_window_subclass();
Ok(app)
}
pub fn run(self) {
let hwnd = self.window.hwnd() as HWND;
self.event_loop.run(move |event, _, control_flow| {
match event {
Event::NewEvents(StartCause::Init) => {
unsafe {
winuser::SendMessageW(
hwnd,
WM_NS_LAUNCH,
0,
0
);
}
},
Event::WindowEvent {
event: WindowEvent::CloseRequested,
..
} => {
*control_flow = ControlFlow::Exit
},
Event::UserEvent(event) => {
println!("{:?}", event);
},
_ => *control_flow = ControlFlow::Wait,
}
});
}
fn set_window_subclass(&mut self) {
unsafe {
commctrl::SetWindowSubclass(
self.window.hwnd() as HWND,
Some(App::subclass_proc),
0,
Box::into_raw(Box::new(self)) as DWORD_PTR,
);
}
}
unsafe extern "system" fn subclass_proc(
hwnd: HWND,
msg: UINT,
wparam: WPARAM,
lparam: LPARAM,
_id: UINT_PTR,
data: DWORD_PTR,
) -> LRESULT {
match msg {
WM_NS_LAUNCH => {
let app = &mut *(data as *mut App);
let event_loop = app.event_loop.borrow_mut();
let event_loop_proxy = app.event_loop_proxy.borrow_mut();
println!("{:?}", event_loop.primary_monitor());
println!("{:?}", event_loop_proxy.send_event(NsEvent::Launch));
0
},
_ => commctrl::DefSubclassProc(hwnd, msg, wparam, lparam),
}
}
}
fn init() -> Result<(EventLoop<NsEvent>, Window), Box<dyn Error>>{
let event_loop = EventLoop::<NsEvent>::new_user_event();
let window = WindowBuilder::new()
.with_title("")
.build(&event_loop)?;
Ok((event_loop, window))
}
#![deny(warnings, clippy::all, rust_2018_idioms)]
#![deny(missing_debug_implementations, missing_copy_implementations)]
#![deny(bare_trait_objects)]
use std::error::Error;
use app::App;
mod app;
fn main() -> Result<(), Box<dyn Error>> {
let app = App::new()?;
app.run();
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment