我正在编写一个 Windows CLI 应用程序,我需要以管理员身份运行它。在 C# 中,我会将此行添加到 app.manifest:
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
我如何在 Rust 中做到这一点?
太晚了,但还是回答。 :-)
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
有一个 open RFC #721 用于 Rust 中的明显支持。
除了讨论添加本机支持的方法之外,这些帖子还包含使用链接器开关或其他工具的各种解决方法的链接。目前还没有好的方法来传递链接器开关;您必须将rustflags
选项放入Cargo 配置文件 并将参数传递给
rustc
,如下所示:
["-C", "link-args=/exoticlinkerswitch"]
。这显然不太便携。对于工具,您可以
使用 Windows SDK 中的 mt.exe
在程序编译后将清单添加到您的程序中。 请注意,Cargo 目前无法自动执行构建后步骤。但是,有一个 Cargo 扩展
cargo-make
支持此类构建过程。您可以通过
cargo install cargo-make
安装它。
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
希望这有帮助。