Asking for administrator privileges - VB#24 ~ VBTheory™ Tutorials

Friday, October 24, 2014

Asking for administrator privileges - VB#24


Code:
IsAdmin function:
    Private Function IsAdministrator() As Boolean
        Try
            Dim user As WindowsIdentity = WindowsIdentity.GetCurrent()
            Dim principal As WindowsPrincipal = New WindowsPrincipal(user)
            Return principal.IsInRole(WindowsBuiltInRole.Administrator)
        Catch ex As Exception
            Return False
        End Try
    End Function

Checking if the app has privileges:
	If (IsAdministrator()) Then
		MessageBox.Show("the application is running as admin")
	Else
		MessageBox.Show("the application is not running as admin")
	End If

Restarting the app as admin:
	If (IsAdministrator()) Then Return

	If (MessageBox.Show("do you want to restart the application to get admin privileges?", "", MessageBoxButtons.YesNo) = DialogResult.Yes) Then
		Dim p As New Process()
		p.StartInfo.FileName = Application.ExecutablePath
		p.StartInfo.Verb = "runas"
		p.Start()
		Process.GetCurrentProcess().Kill()
	End If



Share