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

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] 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

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

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#.
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

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.
Chúc các bạn thành công với thủ thuật trên.

DOWNLOAD SOURCE CODE


PASSWORD UNZIP: HUNG.PRO.VN

PASSWORD UNZIP: HUNG.PRO.VN
Chúc Mọi Người Thành Công Với Thủ Thuật Trên.
Nếu mọi người có vướng mắc gì mình chia sẽ trên trang có thể gửi liên hê cho mình tại đây nhé.
Cảm ơn mọi người đã quan tâm.

No comments:

All Right Reserved © 2015 By Hung Pro VN