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);
}
相关推荐
Source.Liu3 小时前
【unitrix】 4.21 类型级二进制数基本结构体(types.rs)
rust
SoniaChen333 小时前
Rust基础-part2-变量和可变类型
开发语言·后端·rust
寻月隐君4 小时前
Rust 错误处理终极指南:从 panic! 到 Result 的优雅之道
后端·rust·github
ljh5746491196 小时前
Airtest 的 Poco 框架中,offspring()
windows
斜月三16 小时前
windows部署多实例filebeat监控相同路径下文件
windows·filebeat
CHANG_THE_WORLD17 小时前
Rustup 安装加速:使用国内镜像源解决下载慢问题
rust·rustup
尽兴-19 小时前
如何将多个.sql文件合并成一个:Windows和Linux/Mac详细指南
linux·数据库·windows·sql·macos
chilavert3181 天前
技术演进中的开发沉思-30 MFC系列:五大机制
c++·windows
萧曵 丶1 天前
Rust 仿射类型(Affine Types)
rust·仿射类型
寻月隐君1 天前
Rust核心利器:枚举(Enum)与模式匹配(Match),告别空指针,写出优雅健壮的代码
后端·rust·github