2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Rust で Windows のアクセントカラーを取得する

Last updated at Posted at 2024-12-20

はじめに

Tuari などで GUI アプリケーションを作っていると、どこかでテーマカラーに対応したくなる時がある。
ユーザーは任意の色を「個人設定」-> 「アクセントカラー」として設定するが、これらをカスタムで取得しようとすると Windows 内の情報にアクセスする必要が出てくる。
ということで、今回はその色情報を取得するためだけの小ネタ。

image.png

参考

参考はこちらの Tauri のやりとりにて。

依存ライブラリのインストール

このアクセントカラーにアクセスするには Windows レジストリにアクセスする必要がある。
ということで、そのためのライブラリ winreg を追加する。

cargo add winreg

実装

Windows レジストリにアクセスしつつ、それをパースしていく。
結果として、Vec<u8> として RGB 色配列を返す形。

main.rs
use winreg::enums::HKEY_CURRENT_USER;
use winreg::RegKey;

fn get_windows_accent_color() -> Vec<u8> {
    let mut color: Vec<u8> = vec![0, 0, 0];
    let hkcu =
        match RegKey::predef(HKEY_CURRENT_USER).open_subkey(
                "SOFTWARE\\Microsoft\\Windows\\DWM") {
            Ok(key) => key,
            Err(_) => return color,
        };

    let c = match hkcu.get_value::<u32, _>("AccentColor") {
        Ok(value) => value,
        Err(_) => return color,
    };

    color[0] = (c & 0xff) as u8;
    color[1] = ((c >> 8) & 0xff) as u8;
    color[2] = ((c >> 16) & 0xff) as u8;

    color
}

これを使って実行すると次の様に取得できる。

main.rs
fn main() {
    let color = get_windows_accent_color();
    println!(
        "Windows accent color (HEX) :: #{:02x}{:02x}{:02x}",
        color[0], color[1], color[2]
    );
    println!(
        "Windows accent color (RGB) :: Red: {}, Green: {}, Blue: {}",
        color[0], color[1], color[2]
    );
}
結果
Windows accent color (HEX) :: #d13438
Windows accent color (RGB) :: Red: 209, Green: 52, Blue: 56

試しに Google の色変換機に入力してみる。

image.png

ちゃんと取れてる!

さいごに

Windows レジストリのどこにあるのかというのも知れたのでよかったが、何気に Windows レジストリにアクセスする方法は初めてやってみたので、その方法を知れたのも良かった。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?