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);
}
相关推荐
caimouse12 分钟前
Reactos 第 7 章 视窗报文 — 7.4 用户空间的外挂函数
windows
辣香牛肉面36 分钟前
Windows发票工具大全
windows·发票助手
caimouse37 分钟前
Reactos 第 9 章 设备驱动 — 9.3 DPC函数及其执行
windows
caimouse2 小时前
Reactos 第 9 章 设备驱动 — 9.8 设备驱动模块的装载
windows
caimouse2 小时前
Reactos 第 9 章 设备驱动 — 9.2 一个“老式“驱动模块的实例
windows
caimouse2 小时前
Reactos 第 9 章 设备驱动 — 9.4 内核劳务线程
开发语言·windows
星栈独行2 小时前
Rust + Makepad 应用怎么打包发布:Windows、macOS、Linux 全平台交付
windows·程序人生·macos·ui·rust
辣香牛肉面2 小时前
Windows PDF转换工具箱
windows·pdf
daly5202 小时前
PyCharm怎么下载?2026最新版PyCharm安装教程(Windows/macOS/Linux)
windows·macos·pycharm
西凉的悲伤2 小时前
redis-windows 安装 redis 到 windows 电脑
java·windows·redis·redis-windows