Skip to content

Instantly share code, notes, and snippets.

@tribhuwan-kumar
Last active June 13, 2025 14:19
Show Gist options
  • Select an option

  • Save tribhuwan-kumar/5e9f93852b13f80849efe77d647a3a17 to your computer and use it in GitHub Desktop.

Select an option

Save tribhuwan-kumar/5e9f93852b13f80849efe77d647a3a17 to your computer and use it in GitHub Desktop.
launch application and gets its pid - rust

this isn't working as execpted:

image

first of all it isn't returning the pid of apps lauched uwp apps & for some apps its returing a pid but the pid is not valid

when lauching whatsapp (installed from microsoft store):

image

// it's an example file
use windows::{
core::PCWSTR,
Win32::{
Foundation::{CloseHandle, HWND, HANDLE},
UI::Shell::{
ShellExecuteExW, SHELLEXECUTEINFOW, SEE_MASK_NOASYNC, SEE_MASK_NOCLOSEPROCESS,
},
System::Threading::GetProcessId,
UI::WindowsAndMessaging::SW_SHOWNORMAL,
},
};
use tracing::Level;
use windows::Win32::System::Registry::HKEY;
use windows::Win32::Foundation::HINSTANCE;
fn launch_app(app_id: &str) -> Result<u32, String> {
let app_id_wide: Vec<u16> = app_id.encode_utf16().chain(Some(0)).collect();
let operation_wide: Vec<u16> = "open".encode_utf16().chain(Some(0)).collect();
let mut exec_info = SHELLEXECUTEINFOW {
cbSize: std::mem::size_of::<SHELLEXECUTEINFOW>() as u32,
fMask: SEE_MASK_NOASYNC | SEE_MASK_NOCLOSEPROCESS,
hwnd: HWND(std::ptr::null_mut()),
lpVerb: PCWSTR(operation_wide.as_ptr()),
lpFile: PCWSTR(app_id_wide.as_ptr()),
lpClass: PCWSTR::null(),
lpIDList: std::ptr::null_mut(),
lpParameters: PCWSTR::null(),
lpDirectory: PCWSTR::null(),
hkeyClass: HKEY(std::ptr::null_mut()),
hInstApp: HINSTANCE(std::ptr::null_mut()),
dwHotKey: 0,
Anonymous: Default::default(),
nShow: SW_SHOWNORMAL.0,
hProcess: HANDLE(std::ptr::null_mut()),
};
let _ = unsafe { ShellExecuteExW(&mut exec_info).map_err(|e| println!("failed: {:?}", e)) };
let h_process: HANDLE = exec_info.hProcess;
if h_process.is_invalid() {
return Err("No process handle returned".to_string());
}
let pid = unsafe { GetProcessId(h_process) };
unsafe { let _ = CloseHandle(h_process); };
if pid == 0 {
Err("Failed to get process ID".to_string())
} else {
Ok(pid)
}
}
#[tokio::main]
async fn main() -> Result<(), String> {
tracing_subscriber::fmt::Subscriber::builder()
.with_max_level(Level::DEBUG)
.init();
// let app_id = "shell:AppsFolder\\5319275A.WhatsAppDesktop_cv1g1gvanyjgm!App";
// let app_id = "shell:AppsFolder\\TelegramMessengerLLP.TelegramDesktop_t4vj0pshhgkwm!Telegram.TelegramDesktop.Store";
// let app_id = "shell:AppsFolder\\308046B0AF4A39CB;PrivateBrowsingAUMID";
// let app_id = "shell:AppsFolder\\308046B0AF4A39CB";
let app_id = "shell:AppsFolder\\MSEdge";
let result = launch_app(app_id);
println!("pid: {:?}", result);
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment