Skip to main content

single_instance_with_scope

Function single_instance_with_scope 

Source
pub fn single_instance_with_scope(
    app_id: &str,
    scope: InstanceScope,
) -> Result<Option<InstanceGuard>>
Expand description

Attempts to acquire a named single-instance guard in the requested Windows namespace.

Returns Ok(Some(InstanceGuard)) for the first instance in the selected scope and Ok(None) if another instance with the same app_id is already running in that scope.

Use InstanceScope::CurrentSession to enforce a single instance per logged-in session, or InstanceScope::Global to enforce a single instance across sessions.

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. Returns Error::WindowsApi if CreateMutexW fails.

§Examples

let app_id = format!("demo-app-global-{}", std::process::id());
let guard = win_desktop_utils::single_instance_with_scope(
    &app_id,
    win_desktop_utils::InstanceScope::Global,
)?;
assert!(guard.is_some());
Examples found in repository?
examples/single_instance_global.rs (lines 2-5)
1fn main() -> Result<(), Box<dyn std::error::Error>> {
2    match win_desktop_utils::single_instance_with_scope(
3        "demo-app-global",
4        win_desktop_utils::InstanceScope::Global,
5    )? {
6        Some(_guard) => {
7            println!("first instance across all sessions");
8            println!("press Enter to exit");
9            let mut s = String::new();
10            std::io::stdin().read_line(&mut s)?;
11        }
12        None => {
13            println!("already running in another session or this one");
14        }
15    }
16
17    Ok(())
18}