Category Archives: VB.NET

How To: Make the Service Starts Automatically After Install

The Following Code should be added on the Project Installer

Imports System.ServiceProcess

Protected Overrides Sub OnCommitted(ByVal savedState As System.Collections.IDictionary)


Dim myController As New ServiceController(“yourServiceName”)



End Sub


Stop and Application from the code knowing the Name

The Following Lines Loops on all running processes and find my application by name and stop it

Dim p As System.Diagnostics.Process
For Each p In System.Diagnostics.Process.GetProcesses(path)
If p.ProcessName.StartsWith(“my application name”) Then
End If

Convert String to SecureString

The following lines Convert Normal String to a Secure String 

            Dim passwordPre As String = “my_password”
            Dim passwordChars As Char() = passwordPre.ToCharArray()
            Dim password As New SecureString()
            For Each c As Char In passwordChars

Change the Windows Service Type to be Interactive with Descktop While Setup

The Following Code Should be added to the Service installer after the install is Committed:

    Protected Overrides Sub OnCommitted(ByVal savedState As System.Collections.IDictionary)

        Dim myController As New ServiceController(“yourServiceName”)

        ‘ Here is where we set the bit on the value in the registry. 
        ‘ Grab the subkey to our service 
        Dim ckey As RegistryKey = Registry.LocalMachine.OpenSubKey(“SYSTEM\CurrentControlSet\Services\ yourServiceName”, True)
        ‘ Good to always do error checking! 
        If ckey IsNot Nothing Then
            ‘ Ok now lets make sure the “Type” value is there, and then do our bitwise operation on it. 
            If ckey.GetValue(“Type”) IsNot Nothing Then
                ckey.SetValue(“Type”, (CInt(ckey.GetValue(“Type”)) Or 256))
            End If
        End If

    End Sub

Create User and add it to Administrators Group While Setup a Windows Service

The Following Code is to Create User and add it to Administrator Group while setting up your windows Service.
it should be added to the Service installer Section

    Public Overloads Overrides Sub Install(ByVal stateSaver As System.Collections.IDictionary)

        ‘Create User and add it to Administrator Group
            Dim AD As New DirectoryEntry(“WinNT://” & Environment.MachineName & “,computer”)
            Dim NewUser As DirectoryEntry = AD.Children.Add(“UserName”, “user”)
            NewUser.Invoke(“SetPassword”, New Object() {“Password”})
            NewUser.Invoke(“Put”, New Object() {“Description”, “User Description”})
            Dim grp As DirectoryEntry

            grp = AD.Children.Find(“Administrators”, “group”)
            If grp IsNot Nothing Then
                grp.Invoke(“Add”, New Object() {NewUser.Path.ToString()})
            End If

        Catch ex As Exception

        End Try
    End Sub