notify_service/
notify_service.rs

1/// This is an example program that demonstrates how to send a user-defined control code to a given service.
2///
3/// Run in command prompt as admin:
4///
5/// `notify_service.exe SERVICE_NAME`
6///
7/// Replace the `SERVICE_NAME` placeholder above with the name of the service that the program
8/// should notify.
9
10#[cfg(windows)]
11fn main() -> windows_service::Result<()> {
12    use std::env;
13    use windows_service::{
14        service::{ServiceAccess, UserEventCode},
15        service_manager::{ServiceManager, ServiceManagerAccess},
16    };
17
18    let service_name = env::args().nth(1).unwrap_or("ping_service".to_owned());
19
20    let manager_access = ServiceManagerAccess::CONNECT;
21    let service_manager = ServiceManager::local_computer(None::<&str>, manager_access)?;
22
23    let service = service_manager.open_service(
24        &service_name,
25        ServiceAccess::PAUSE_CONTINUE | ServiceAccess::USER_DEFINED_CONTROL,
26    )?;
27
28    const NO_OP: UserEventCode = unsafe { UserEventCode::from_unchecked(128) };
29    const CUSTOM_STOP: UserEventCode = unsafe { UserEventCode::from_unchecked(130) };
30
31    println!("Send `NO_OP` notification to {}", service_name);
32    let state = service.notify(NO_OP)?;
33    println!("{:?}", state.current_state);
34
35    println!("Send `CUSTOM_STOP` notification to {}", service_name);
36    let state = service.notify(CUSTOM_STOP)?;
37    println!("{:?}", state.current_state);
38
39    Ok(())
40}
41
42#[cfg(not(windows))]
43fn main() {
44    panic!("This program is only intended to run on Windows.");
45}