microsoft / windows-rs

Rust for Windows
https://kennykerr.ca/rust-getting-started/
Apache License 2.0
10.32k stars 484 forks source link

Use ShellExecuteW to start as administrator, no UAC window pops up #2596

Closed fanchenio closed 1 year ago

fanchenio commented 1 year ago

My code

use windows::{
    core::{HSTRING, PCWSTR},
    Win32::UI::{Shell::ShellExecuteW, WindowsAndMessaging::SW_SHOWDEFAULT},
};

fn main() {
    let operation = String::from("runas");
    let file =
        String::from("D:\\Program Files\\Tencent\\QQMusic\\QQMusic1944.11.24.29\\QQMusic.exe");
    let params = String::from("");
    let dir = String::from("D:\\Program Files\\Tencent\\QQMusic\\QQMusic1944.11.24.29");

    let operation = HSTRING::from(operation.as_str());
    let file = HSTRING::from(file.as_str());
    let params = HSTRING::from(params.as_str());
    let dir = HSTRING::from(dir.as_str());

    let operation = PCWSTR(operation.as_ptr());
    let file = PCWSTR(file.as_ptr());
    let params = PCWSTR(params.as_ptr());
    let dir = PCWSTR(dir.as_ptr());

    unsafe {
        // execute
        ShellExecuteW(windows::Win32::Foundation::HWND(0), operation, file, params, dir, SW_SHOWDEFAULT);
    }
}

Under normal circumstances, a window should pop up asking whether to start it as an administrator, but it did not pop up, but the application was opened directly. What is the problem?

riverar commented 1 year ago

Here's a simpler approach:

use windows::{
    w, Win32::UI::{WindowsAndMessaging::SW_SHOWDEFAULT, Shell::ShellExecuteW},
};

fn main() {
    unsafe {
        ShellExecuteW(
            None,
            w!("runas"),
            w!("D:\\Program Files\\Tencent\\QQMusic\\QQMusic1944.11.24.29\\QQMusic.exe"),
            None,
            w!("D:\\Program Files\\Tencent\\QQMusic\\QQMusic1944.11.24.29"),
            SW_SHOWDEFAULT,
        );
    }
}