Search code examples
vb.netwindowsuser-accounts

Get curent windows profile in vb 2013


I'm writing a little vb application. I need to know the Windows user name account that is logged in. I found this:

Function GetUserName() As String
    If TypeOf My.User.CurrentPrincipal Is 
      Security.Principal.WindowsPrincipal Then
        ' The application is using Windows authentication.
        ' The name format is DOMAIN\USERNAME.
        Dim parts() As String = Split(My.User.Name, "\")
        Dim username As String = parts(1)
        Return username
    Else
        ' The application is using custom authentication.
        Return My.User.Name
    End If
End Function

Is working good but he give me the user that execute the process,so if i start the application with the administration credential this function will give me the administration user. I need the Windows user not the user that execute the process, how can i do?

Thanks !!!


Solution

  • This will give you the user name of the user who logged in to windows. " Not the one who starts the program"

    You need to Import System.Management for this.

    Imports System.Management
    
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    
        Dim Coll As ManagementObjectCollection
        Dim LogonName As String
        Dim GetName As New ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem")
        Coll = GetName.[Get]()
        LogonName = DirectCast(Coll.Cast(Of ManagementBaseObject)().First()("UserName"), String)
        Dim CleanName() As String = Split(LogonName, "\")
        Label1.Text = CleanName(1)
    
    End Sub