pub fn single_instance(app_id: &str) -> Result<Option<InstanceGuard>>Expand description
Attempts to acquire a named process-wide single-instance guard.
Returns Ok(Some(InstanceGuard)) for the first instance and Ok(None) if another
instance with the same app_id is already running.
This is a convenience wrapper around single_instance_with_scope using
InstanceScope::CurrentSession.
The mutex name is derived from app_id using a Local\... namespace, so the
single-instance behavior is scoped to the current Windows session.
Keep the returned guard alive for as long as the current process should continue to own the single-instance lock.
§Errors
Returns Error::InvalidInput if app_id is empty, contains only whitespace,
contains NUL bytes, or contains backslashes. Windows reserves backslashes in
named kernel objects for namespace separators such as Local\ and Global\.
Returns Error::WindowsApi if CreateMutexW fails.
§Examples
let app_id = format!("demo-app-{}", std::process::id());
let guard = win_desktop_utils::single_instance(&app_id)?;
assert!(guard.is_some());Examples found in repository?
1fn main() -> Result<(), Box<dyn std::error::Error>> {
2 match win_desktop_utils::single_instance("demo-app")? {
3 Some(_guard) => {
4 println!("first instance in the current session");
5 println!("press Enter to exit");
6 let mut s = String::new();
7 std::io::stdin().read_line(&mut s)?;
8 }
9 None => {
10 println!("already running in this session");
11 }
12 }
13
14 Ok(())
15}