#[cfg(target_os = "windows")]
pub fn ensure_single_instance() {
extern "system" {
fn CreateMutexW(
lp_mutex_attributes: *mut std::ffi::c_void,
b_initial_owner: i32,
lp_name: *const u16,
) -> *mut std::ffi::c_void;
fn GetLastError() -> u32;
fn CloseHandle(h_object: *mut std::ffi::c_void) -> i32;
fn FindWindowW(class_name: *const u16, window_name: *const u16) -> *mut std::ffi::c_void;
fn ShowWindow(h_wnd: *mut std::ffi::c_void, n_cmd_show: i32) -> i32;
fn SetForegroundWindow(h_wnd: *mut std::ffi::c_void) -> i32;
fn IsIconic(h_wnd: *mut std::ffi::c_void) -> i32;
}
const ERROR_ALREADY_EXISTS: u32 = 183;
const SW_RESTORE: i32 = 9;
const SW_SHOW: i32 = 5;
let name: Vec<u16> = "Global\\start_kamft_single_instance\0"
.encode_utf16()
.collect();
unsafe {
let handle = CreateMutexW(std::ptr::null_mut(), 1, name.as_ptr());
if handle.is_null() {
return;
}
if GetLastError() == ERROR_ALREADY_EXISTS {
CloseHandle(handle);
let title: Vec<u16> = "招财进宝小助手\0".encode_utf16().collect();
let hwnd = FindWindowW(std::ptr::null(), title.as_ptr());
if !hwnd.is_null() {
if IsIconic(hwnd) != 0 {
ShowWindow(hwnd, SW_RESTORE); } else {
ShowWindow(hwnd, SW_SHOW); }
SetForegroundWindow(hwnd); }
std::process::exit(0);
}
}
}
#[cfg(not(target_os = "windows"))]
pub fn ensure_single_instance() {
}