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);
}
相关推荐
DY009J14 小时前
从 MSYS2 环境中提取独立 MinGW-w64 工具链的技术方案
c++·windows
J2虾虾14 小时前
Java使用jcifs读取Windows的共享文件
java·开发语言·windows
angushine15 小时前
Windows下循环复制一个文件
windows
liulilittle15 小时前
OPENPPP2 1.0.0.26145 正式版发布:内核态 SYSNAT 性能飞跃 + Windows 平台避坑指南
开发语言·网络·c++·windows·通信·vrrp
分布式存储与RustFS15 小时前
Windows原生版RustFS:无需Docker,1分钟本地对象存储环境搭建
windows·docker·容器·对象存储·minio·企业存储·rustfs
xjt_090116 小时前
Oh My Codex 快速使用指南
windows
独隅16 小时前
在 Windows 上部署 TensorFlow 模型的全面指南
人工智能·windows·tensorflow
.生产的驴16 小时前
Vue3 超大字体font-slice按需分片加载,极速提升首屏速度, 中文分片加载方案,性能优化
前端·vue.js·windows·青少年编程·性能优化·vue·rescript
Tomhex17 小时前
Rust智能指针使用指南
rust
小白o菜17 小时前
Claude Code在windows部署,使用第三方api,如open router等
windows·claude·openrouter·aicodemirror·小鱼api