NEWS

[VB.NET] Hướng dẫn lấy thông tin tài khoản đăng nhập windows và khởi động lại ứng dụng ở chế độ Administrator

[VB.NET] Hướng dẫn lấy thông tin tài khoản đăng nhập windows và khởi động lại ứng dụng ở chế độ Administrator
Đăng bởi: Thảo Meo - Lượt xem: 1004 13:35:58, 01/02/2024VB.NET   In bài viết

Xin chào các bạn, bài viết hôm nay mình tiếp tục hướng dẫn các bạn cách lấy tên tài khoản user đăng nhập trên Windows bằng ngôn ngữ VB.NET, và cách khởi động lại ứng dụng với chế độ Admin.

[VB.NET] How to get user logined in Winform throught Run app as Administrator

Thông thường, các bạn sử dụng lệnh dưới đây để lấy thông tin tài khoản đang đăng nhập vào windows.

Imports System.Security.Principal

Module Module1
    Sub Main()
        Dim userName As String = System.Security.Principal.WindowsIdentity.GetCurrent().Name
        Console.WriteLine("User Name: " & userName)
        Console.ReadLine()
    End Sub
End Module

Giống như hình ảnh, các bạn thấy mình đang đăng nhập vào Windows bằng tài khoản Guest.

Khi sử dụng lên trên nếu ứng dụng chúng ta chạy chế độ bình thường thì nó sẽ trả về kết quả là: Guest

Nhưng nếu bạn chạy app "Run As Administrator" thì nó lại trả về kết quả là "Administrator"

Nhưng mình muốn ở đây là, cho dù chạy thế nào vẫn phải trả đúng tên tài khoản mình đang login vào windows.

Giải pháp:

Mình sẽ sử dụng lệnh query user trên CMD, để lấy thông tin user session đang Active vào C#.

query_user_cmd

Source code VB.NET:

Imports System.Management
Imports System.Text.RegularExpressions

Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim currentUser = GetCurrentUserLoginedWindows()
        MessageBox.Show(currentUser)


    End Sub

    Public Function GetCurrentUserLoginedWindows() As String
        Dim queryPath As String = String.Empty

        If Environment.Is64BitOperatingSystem AndAlso Not Environment.Is64BitProcess Then
            queryPath = System.IO.Path.Combine(Environment.GetEnvironmentVariable("windir"), "Sysnative", "query.exe")
        Else
            queryPath = System.IO.Path.Combine(Environment.GetEnvironmentVariable("windir"), "System32", "query.exe")
        End If

        Dim startInfo As New ProcessStartInfo(queryPath)
        startInfo.Arguments = "user"
        startInfo.CreateNoWindow = True
        startInfo.RedirectStandardError = True
        startInfo.RedirectStandardOutput = True
        startInfo.UseShellExecute = False
        startInfo.WindowStyle = ProcessWindowStyle.Hidden

        Using p As New Process With {
            .StartInfo = startInfo,
            .EnableRaisingEvents = True
        }
            p.Start()
            p.WaitForExit()
            Dim result As String = p.StandardOutput.ReadToEnd()
            Dim dataTable As New DataTable()
            Dim lines As String() = result.Split({Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)

            Dim column = 0
            For Each line As String In lines
                Dim pattern As String = "\s{2,}"
                Dim columns As String() = Regex.Split(line.Trim(), pattern)
                If column = 0 Then
                    For Each col As String In columns
                        dataTable.Columns.Add(col)
                    Next
                    column = column + 1
                Else
                    Dim row As DataRow = dataTable.NewRow()
                    For i As Integer = 0 To Math.Min(dataTable.Columns.Count - 1, columns.Length - 1)
                        row(i) = columns(i)
                    Next
                    dataTable.Rows.Add(row)
                End If
            Next

            Return dataTable.AsEnumerable().Where(Function(x) x.Field(Of String)("STATE") = "Active").FirstOrDefault()("USERNAME").ToString().Replace(">", "")
        End Using
    End Function

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim args = Environment.GetCommandLineArgs()
        Dim psi = New ProcessStartInfo() With {
            .FileName = args(0),
            .UseShellExecute = True,
            .Verb = "runas"
        }



        Process.Start(psi)
        Environment.Exit(0)
    End Sub
End Class

Ở trong source code này mình cũng đã tích hợp cách chạy lại ứng dụng dưới quyền Administrator.

Thanks for watching!

 

DOWNLOAD SOURCE

THÔNG TIN TÁC GIẢ

BÀI VIẾT LIÊN QUAN

[VB.NET] Hướng dẫn lấy thông tin tài khoản đăng nhập windows và khởi động lại ứng dụng ở chế độ Administrator
Đăng bởi: Thảo Meo - Lượt xem: 1004 13:35:58, 01/02/2024VB.NET   In bài viết

CÁC BÀI CÙNG CHỦ ĐỀ

Đọc tiếp