如何设置 Windows 执行级别以要求用户提供 Rust 程序的管理员权限?

问题描述 投票:0回答:3

我正在编写一个 Windows CLI 应用程序,我需要以管理员身份运行它。在 C# 中,我会将此行添加到 app.manifest:

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" /> 

我如何在 Rust 中做到这一点?

windows rust
3个回答
16
投票

太晚了,但还是回答。 :-)

请查看

winres
图书馆。它包含以下示例:

以下清单会将 exe 标记为请求管理员 特权。因此,每次执行时,都会出现一个 Windows UAC 对话框 出现。

let mut res = winres::WindowsResource::new();
res.set_manifest(r#"
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
    <security>
        <requestedPrivileges>
            <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
        </requestedPrivileges>
    </security>
</trustInfo>
</assembly>
"#);

完整的示例已记录并可在此处获取。

我一直在一个包含图标并需要管理员权限的项目中使用这个库,它的

build.rs
使用
winres
托管在这里。查看生成的可执行文件:

HTH


2
投票

有一个 open RFC #721 用于 Rust 中的明显支持。

除了讨论添加本机支持的方法之外,这些帖子还包含使用链接器开关或其他工具的各种解决方法的链接。目前还没有好的方法来传递链接器开关;您必须将

rustflags

 选项放入 
Cargo 配置文件 并将参数传递给 rustc
,如下所示:
["-C", "link-args=/exoticlinkerswitch"]
。这显然不太便携。

对于工具,您可以

使用 Windows SDK 中的 mt.exe

 在程序编译后将清单添加到您的程序中

请注意,Cargo 目前无法自动执行构建后步骤。但是,有一个 Cargo 扩展

cargo-make

 支持此类构建过程。您可以通过
cargo install cargo-make
安装它。


0
投票
这是实现此目的的另一种方法:)

fn run_as_admin() -> bool{ if let Ok(current_exe) = std::env::current_exe() { if let Some(current_exe_str) = current_exe.to_str() { unsafe { let hwnd: HWND = std::mem::zeroed(); let status = ShellExecuteA( hwnd, PCSTR::from_raw("runas\0".as_ptr()), PCSTR::from_raw(current_exe_str.as_ptr()), PCSTR::null(), PCSTR::null(), SW_SHOW, ); if !status.is_invalid() { return true; } } } } false
希望这有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.