use anyhow::{Context, Result};
use windows::core::w;
use windows::Win32::Foundation::{CloseHandle, GetLastError, ERROR_ALREADY_EXISTS, HANDLE};
use windows::Win32::System::Threading::CreateMutexW;
pub struct InstanceGuard {
handle: HANDLE,
}
impl InstanceGuard {
pub fn acquire() -> Result<Option<Self>> {
let handle = unsafe {
CreateMutexW(None, true, w!("KeyhopSingleInstanceMutex"))
.context("CreateMutexW for single-instance guard")?
};
let already_existed = unsafe { GetLastError() == ERROR_ALREADY_EXISTS };
if already_existed {
unsafe {
let _ = CloseHandle(handle);
}
return Ok(None);
}
Ok(Some(Self { handle }))
}
}
impl Drop for InstanceGuard {
fn drop(&mut self) {
unsafe {
let _ = CloseHandle(self.handle);
}
}
}