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);
}
相关推荐
q***318919 小时前
数据库操作与数据管理——Rust 与 SQLite 的集成
数据库·rust·sqlite
liuhuapeng030420 小时前
GetMapping自动截取List<String>字符
数据结构·windows·list
魏 无羡1 天前
windows 安装mysql(多个版本同时安装)
windows·mysql·adb
百锦再1 天前
第11章 泛型、trait与生命周期
android·网络·人工智能·python·golang·rust·go
芳草萋萋鹦鹉洲哦1 天前
【Windows】tauri+rust运行打包工具链安装
开发语言·windows·rust
会跑的兔子1 天前
Android 16 Kotlin协程 第二部分
android·windows·kotlin
hhhh明1 天前
quest2+alvr+steamvr
linux·windows·quest2
s9123601011 天前
【Rust】m2 mac 编译linux 、aarch、win 程序
rust
Source.Liu1 天前
【ISO8601库】日期时间解析器测试套件详解(tests.rs)
rust·time·iso8601
alwaysrun1 天前
Rust中数组简介
rust·数组·array·切片