I need to get elevated credentials (to start a service) in a VB6 application, but only if the user needs to restart the service (I.e. I don't want to get elevated credentials whenever the application is started, only when the user selects restart). How can I do this in VB6?
One solution is to use the COM elevation moniker http://msdn.microsoft.com/en-us/library/ms679687(VS.85).aspx.
This link should be useful if your target is VB6 http://www.vbforums.com/showthread.php?t=459643.
You'll need to call into the WinAPI - CoImpersonateClient, or LogonUser.
Just remember to lower your privileges afterwards, and be DARN careful what you do when elevated (e.g. don't do ANYthing with user input).
Another option, which I believe is preferable (if available), is to use a COM+ configured object. You can have the COM+ subsystem manage credentials, and just limit access to call the object as necessary. This has the benefit of creating and ACTUAL trust boundary between low-privileged code and high-privileged code.
Fairly easy, but the preferred way involves a new elevated process. This example uses itself run with a switch to know to perform the Service Start instead of normal operations:
VERSION 5.00
Begin VB.Form Form1
BorderStyle = 1 'Fixed Single
Caption = "Form1"
ClientHeight = 3060
ClientLeft = 45
ClientTop = 345
ClientWidth = 4560
LinkTopic = "Form1"
MaxButton = 0 'False
MinButton = 0 'False
ScaleHeight = 3060
ScaleWidth = 4560
StartUpPosition = 3 'Windows Default
Begin VB.CommandButton Command1
Caption = "Start Service"
Height = 495
Left = 1448
TabIndex = 0
Top = 1283
Width = 1665
End
End
Attribute VB_Name = "Form1"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Option Explicit
Private Const BCM_SETSHIELD As Long = &H160C&
Private Declare Function SendMessage Lib "user32" _
Alias "SendMessageA" ( _
ByVal hWnd As Long, _
ByVal wMsg As Long, _
ByVal wParam As Long, _
lParam As Any) As Long
Private Declare Function ShellExecute Lib "shell32.dll" _
Alias "ShellExecuteA" ( _
ByVal hWnd As Long, _
ByVal lpOperation As String, _
ByVal lpFile As String, _
ByVal lpParameters As String, _
ByVal lpDirectory As String, _
ByVal nShowCmd As Long) As Long
Private Sub Command1_Click()
ShellExecute hWnd, "runas", App.EXEName & ".exe", "-start", CurDir$(), vbNormalFocus
End Sub
Private Sub Form_Load()
If UCase$(Trim$(Command$())) = "-START" Then
Caption = "Starting Service"
Command1.Visible = False
'Service starting functionality goes here.
Else
Caption = "Service Starter"
'For Shield to work you must have a Common Controls v. 6
'manifest and call InitCommonControls before loading
'this form (i.e. preferably from Sub Main).
SendMessage Command1.hWnd, BCM_SETSHIELD, 0&, 1&
Command1.Visible = True
End If
End Sub