Windows-rs: How to get active user?

Created on 12 Mar 2021  路  4Comments  路  Source: microsoft/windows-rs

Using C# getting a the active user is as simple as Environment.UserName.
How do I do the same thing with windows-rs?

Thank you so much!

question

All 4 comments

The windows-rs crate generates bindings for Windows APIs, so you'll want to track down the Win32 or WinRT API that does what you want and then look that API up in the crate documentation. In this case, you'll want the GetUserNameEx(A/W) function:

https://docs.microsoft.com/en-us/windows/win32/api/secext/nf-secext-getusernameexa
https://microsoft.github.io/windows-docs-rs/doc/bindings/windows/win32/windows_programming/fn.GetUserNameExA.html

There's also a set of WinRT APIs that can be used to get user information:
https://docs.microsoft.com/en-us/uwp/api/Windows.System.User?view=winrt-19041

Here's a snippet that does this with WinRT:

use bindings::windows::{
    foundation::IReference,
    system::{KnownUserProperties, User, UserType},
};
use windows::{HString, Interface};

fn main() -> windows::Result<()> {
    windows::initialize_sta()?;

    let users = User::find_all_async_by_type(UserType::LocalUser)?.get()?;
    assert!(users.size()? >= 1);
    let user = users.get_at(0)?;

    let user_name: IReference<HString> = user
        .get_property_async(KnownUserProperties::account_name()?)?
        .get()?
        .cast()?;
    let user_name = user_name.get_string()?;
    println!("User name: {}", user_name);

    Ok(())
}

Generally it's preferable to actually use the async pattern instead of blocking using get but for this sample it was simpler.

In this case, you can also use the Rust standard library:

fn main() {
    let username = env!("USERNAME");
    println!("{}", username);
}

You all are amazing! Thank you so much!!!!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

rylev picture rylev  路  4Comments

rylev picture rylev  路  5Comments

DJankauskas picture DJankauskas  路  3Comments

AyashiNoCeres picture AyashiNoCeres  路  4Comments

bdbai picture bdbai  路  3Comments