rust - 读取windows注册表的值

本文提供了读取windows注册表值的方法。

读取字符串的值

rust 复制代码
#![cfg(windows)]
use anyhow::Result;
use windows::{core::*, Win32::System::Registry::*};

/// 查询windows注册表的值
fn query_reg_value() -> Result<String> {
    unsafe {
        // 打开注册表
        let mut key = HKEY::default();
        RegOpenKeyExA(
            HKEY_LOCAL_MACHINE,
            s!(r"SOFTWARE\GitForWindows"),
            0,
            KEY_QUERY_VALUE,
            &mut key,
        )?;

        // 获得 value 的字节数
        let mut len = 0;
        RegQueryValueExA(
            key,
            s!("InstallPath"),
            None,
            None,
            None,
            Some(&mut len),
        )?;

        // 获取 value 的值
        let mut buffer = vec![0u8; (len) as usize];
        RegQueryValueExA(
            key,
            s!("InstallPath"),
            None,
            None,
            Some(buffer.as_mut_ptr() as _),
            Some(&mut len),
        )?;

        // 转换为字符串
        let value = String::from_utf8_lossy(&buffer);

        // 去掉结尾的空字符
        let value = value.trim_end_matches("\0");

        Ok(value.to_string())
    }
}

#[test]
fn test_query_reg_value() {
    let actual = query_reg_value().unwrap();
    let expect = r"C:\Program Files\Git".to_string();
    assert_eq!(actual, expect);
}
相关推荐
周伯通*1 小时前
Windows上,使用远程桌面连接Ubuntu
linux·windows·ubuntu
许野平2 小时前
Rust: Warp RESTful API 如何得到客户端IP?
tcp/ip·rust·restful·ip地址
GDAL4 小时前
GNU力量注入Windows:打造高效跨平台开发新纪元
服务器·windows·gnu
许野平5 小时前
Rust:Result 和 Error
开发语言·后端·rust·error·result
小徐敲java7 小时前
Windows本地制作java证书(与jeecgboot配置本地证书ssl问题)
java·windows·ssl
春蕾夏荷_7282977257 小时前
electron nsis打包windows应用程序
javascript·windows·electron·nsis
Freestyle Coding7 小时前
使用rust自制操作系统内核
c语言·汇编·microsoft·rust·操作系统
偷偷小野猪7 小时前
Windows 常用的键盘快捷键总结
windows
Splashtop高性能远程控制软件9 小时前
centos远程桌面连接windows
linux·windows·centos·远程控制·远程桌面
楚钧艾克12 小时前
Windows系统通过部署wsl + Goland进行跨平台开发
linux·windows·后端·ubuntu·golang