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);
}
相关推荐
fegggye1 天前
PyO3 Class 详解 - 在 Python 中使用 Rust 类
pytorch·rust
巴拉巴拉~~2 天前
Flutter 通用轮播图组件 BannerWidget:自动播放 + 指示器 + 全场景适配
windows·flutter·microsoft
双河子思2 天前
Windows API 积累
windows
云上漫步者2 天前
深度实战:Rust交叉编译适配OpenHarmony PC——unicode_width完整适配案例
开发语言·后端·rust·harmonyos
OliverH-yishuihan2 天前
在 Windows 上安装 Linux
linux·运维·windows
想你依然心痛2 天前
AI赋能编程语言挑战赛:从Python到Rust,我用AI大模型重塑开发效率
人工智能·python·rust
淼淼7632 天前
工厂方法模式
开发语言·c++·windows·qt·工厂方法模式
ForteScarlet2 天前
如何解决 Kotlin/Native 在 Windows 下 main 函数的 args 乱码?
开发语言·windows·kotlin
WTCLLB2 天前
Windows命令和工具名称
windows
YCOSA20252 天前
雨晨 Windows 11 企业版 26H1 轻装版 28020.1362
windows