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

Chào mọi người.


Sau một hồi tìm hiểu về việc khởi chạy chương trình trên windows bằng administrator để sữ dụng được nhiều đặc quyền để thay đổi file hệ thống trên windows hơn, và mình đã tìm ra đoạn code này được chia sẽ bởi laptrinhvb.net nên mình mạn phép sao chép bài viết này về chia sẽ lại cho những anh em chưa tìm hiểu nhiều về điều trên để hiểu rỏ hơn.

[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

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

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 mọi người thành công với đoạn code trên.

Post a Comment

✔ Bình luận có dấu, lịch sự và đúng chủ đề
❌ Không spam link, quảng cáo, từ ngữ phản cảm
❌ Không hỏi link tải, crack, nội dung vi phạm
⚠ Bình luận vi phạm sẽ bị xóa mà không báo trước

Thêm hình ảnh: [img] link hình ảnh [/img]
Thêm video youtube: [youtube] link video [/youtube]
Thêm code: [code] Đoạn code đã mã hóa [/code]

أحدث أقدم