elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.
 
Inicio Ayuda Buscar Ingresar Registrarse
29 Mayo 2012, 03:16  


Tema destacado: Grupo de Facebook de elhacker.net

+  Foro de elhacker.net
|-+  Programación
| |-+  Programación Visual Basic (Moderadores: LeandroA, seba123neo, raul338)
| | |-+  duda acerca de los servicios :P
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: duda acerca de los servicios :P  (Leído 986 veces)
RHL


Desconectado Desconectado

Mensajes: 968


mental


Ver Perfil
duda acerca de los servicios :P
« en: 13 Agosto 2011, 21:23 »

buenas cree este tema relacionado a este :P

http://foro.elhacker.net/analisis_y_diseno_de_malware/manejar_sevicios_desde_vb-t123518.0.html

tengo una duda de como crear un servicio e visto que estan las funciones pero creo que me estoy equivocando en algo :P o no funciona en win 7 ???

todo el codigo de vb lo agrego a un modulo y despues llamo a la funcion "main" luego en esa funcion agrego la funcion "ServiceInstall" que creo que en los paremtros me quivoco noce :P yo escribo el nombre de la PC o es el nombre del usuario del que se esta ocupando? luego el segundo parametro es el nombre del servicio no :P y el tercero la ruta del EXE yo escribo la ruta del notepad :P
bueno si hay alguien que enseñe como funciona el codigo gracias  ;D


En línea
[ Thunder | CLS ]

Desconectado Desconectado

Mensajes: 135


CrAcKiNg 4 PaSsIoN


Ver Perfil WWW
Re: duda acerca de los servicios :P
« Respuesta #1 en: 15 Agosto 2011, 17:47 »

En que te falla y que error te devuelve?
El prototipo de la funcion es:

Código
ServiceInstall(ComputerName As String, ServiceName As String, Path As String)

El primer parametro es el nombre de la PC (Segun la MSDN - http://msdn.microsoft.com/en-us/library/ms684323(v=vs.85).aspx):
The name of the target computer. If the pointer is NULL or points to an empty string, the function connects to the service control manager on the local computer.

El segundo y el tercer parametro estan relacionados con "CreateService" (http://msdn.microsoft.com/en-us/library/ms682450(v=vs.85).aspx). Por lo que estuve viendo en la implementacion de la funcion, se utiliza el mismo parametro de funcion "ServiceName" para los parametros de API "lpServiceName" y "lpDisplayName" que no necesariamente tienen que ser iguales...bueno, es solo una aclaracion.
Saludos


En línea

-[ CrAcKiNg 4 PaSsIoN ]-
Mi GoogleSite dedicado a la Programación y al Cracking
http://sites.google.com/site/thundercrackslatinos/Home
RHL


Desconectado Desconectado

Mensajes: 968


mental


Ver Perfil
Re: duda acerca de los servicios :P
« Respuesta #2 en: 15 Agosto 2011, 19:14 »

pues yo queria saber como usar las funciones osea como instalar digamos el notepad como servicio :P
yo e investigado un poco pero no logro hacerlo :/


(e hecho una copia del notepad al C )
Código
Sub Main()
Dim ComputerN As String
Dim LenC As Long
 
ComputerN = Space(MAX_COMPUTERNAME_LENGTH)
LenC = MAX_COMPUTERNAME_LENGTH + 1
GetComputerName ComputerN, LenC
ComputerN = Left$(ComputerN, LenC)
 
ServiceInstall ComputerN, "NOTEPAD", "C:\NOTEPAD.exe"
 
   'ServiceStop "", "ipodservice"
   'ServiceStart "", "ipodservice"
   'ServicePause "", "ipodservice"
   'ServiceInstall "", "ipodservice",
   'ServiceUnInstall "", "ipodservice"
   'MsgBox ServiceStatus("", "ipodservice")
End Sub

y cuando llamo a la funcion de instalar el servicio no me instala nada :/ yo uso window 7 noce si eso puede afectar aunq en la msdn dice que desde 98 creo :P en adelanet :P es mas e puesto esta linea despues de la llamada a la API createservice

Código
If Err.LastDllError <> 0 Then Debug.Print Error(Err.LastDllError)

para saber cual es el error y me devuelve esto:

"Error definido por la aplicación o el objeto"

:P
En línea
RHL


Desconectado Desconectado

Mensajes: 968


mental


Ver Perfil
Re: duda acerca de los servicios :P
« Respuesta #3 en: 2 Septiembre 2011, 05:24 »

:P sale buenas e logrado instalar un servicio :P
con este codigo:


Código
Public Function Service_Install(SVC_NAME As String, SVC_DESC As String) As Boolean
   Dim lHManager           As Long
   Dim lHService           As Long
   Dim lResult             As Long
   Dim tStatus             As SERVICE_STATUS
   Dim sSvcPath            As String
   Dim sAccount            As String
 
On Error GoTo Handler
   sSvcPath = App.Path + "\" & SVC_NAME
   sAccount = "LocalSystem"
   lHManager = OpenSCManager(vbNullString, vbNullString, SC_MANAGER_CREATE_SERVICE)
   lResult = CreateService(lHManager, SVC_NAME, SVC_DESC, SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_DEMAND_START, SERVICE_ERROR_NORMAL, sSvcPath, vbNullString, vbNullString, vbNullString, sAccount, vbNullString)
   If Not lResult = 0 Then
       Service_Install = True
   Else
       GoTo Handler
   End If
   CloseServiceHandle lHManager
On Error GoTo 0
Exit Function
 
Handler:
   If Not lHManager = 0 Then CloseServiceHandle lHManager
End Function
 
 
Public Function Service_StartUp(SVC_NAME As String, svcStartType As eServiceStartType) As Boolean
   Dim lHManager           As Long
   Dim lHService           As Long
   Dim lResult             As Long
 
On Error GoTo Handler
   lHManager = OpenSCManager(vbNullString, vbNullString, SC_MANAGER_CONNECT)
   lHService = OpenService(lHManager, SVC_NAME, SERVICE_CHANGE_CONFIG)
   lResult = ChangeServiceConfig(lHService, SERVICE_NO_CHANGE, svcStartType, SERVICE_NO_CHANGE, vbNullString, vbNullString, 0&, vbNullString, vbNullString, vbNullString, vbNullString)
   If Not lResult = 0 Then Service_StartUp = True
   CloseServiceHandle lHService
   CloseServiceHandle lHManager
On Error GoTo 0
Exit Function
 
Handler:
   If Not lHService = 0 Then CloseServiceHandle lHService
   If Not lHManager = 0 Then CloseServiceHandle lHManager
End Function
 

y lo utilizo asi:


Código
If Service_Install(App.EXEName & ".exe", "EJEMPLO SERVICIO") Then
   Debug.Print Service_StartUp(App.EXEName & ".exe", START_AUTO)
Else
   Debug.Print "SVC NOT"
End If
 

compilo el proyecto y lo ejecuto, me instala el servicio el proceso de programa aparece como un proceso normal en el admin de tareas, en la pestaña de servicios lo encuentro instalado:


pero al parecer no esta iniciado ( claro no tiene la funcion para ser iniciado ) luego lo inicio manualmente y me dice esto:


y luego apago y vuelvo a encender y no esta iniciado el servicio
alguien me puede ayudar? :( :P


 pero ahora el problema es que no me inicia el servicio :P
En línea
Elemental Code


Desconectado Desconectado

Mensajes: 499


Im beyond the system


Ver Perfil
Re: duda acerca de los servicios :P
« Respuesta #4 en: 2 Septiembre 2011, 22:30 »

que programa estas poniendo como servicio.?
Cualquier programa se puede poner como servicio?
En línea

raul338
Moderador
***
Conectado Conectado

Mensajes: 2.371


La sonrisa es la mejor forma de afrontar las cosas


Ver Perfil WWW
Re: duda acerca de los servicios :P
« Respuesta #5 en: 3 Septiembre 2011, 01:07 »

Cualquier programa se puede, pero al iniciarlo el programa debe "terminar" la llamada devolviendo un código antes de un tiempo determinado, como hacerlo, no sé :xD
En línea

RHL


Desconectado Desconectado

Mensajes: 968


mental


Ver Perfil
Re: duda acerca de los servicios :P
« Respuesta #6 en: 3 Septiembre 2011, 02:24 »

que programa estas poniendo como servicio.?
Cualquier programa se puede poner como servicio?

bueno yo hice un programa sin interfas ( form ) porque lei en algun sitio no recuerdo bien que los servicios no deben de tener GUI :P entonces hice un medio hook para detectar los pendrive :P y me pasa ese problema :P

Cualquier programa se puede, pero al iniciarlo el programa debe "terminar" la llamada devolviendo un código antes de un tiempo determinado, como hacerlo, no sé :xD

pues ahora que lo dices raul338 cuando inicio el servicio instalado con codigo el programa creado para iniciar el servicio se cuelga :P
debe ser eso que dices :P y luego hice un programa normal que crea 100 archivos de texto en una X carpeta ( todo eso esta en el sub main del modulo porque no les agrego form ) luego de comprobar que se crearon los 100 archivos termina el sub main del modulo y finaliza el programa y el otro programa que llamo a la funcion para inciar el servicio noce cuelga :P
bueno espero que alguien si pueda

« Última modificación: 3 Septiembre 2011, 03:14 por Raul100 » En línea
BlackZeroX (Astaroth)
Wiki

Desconectado Desconectado

Mensajes: 2.831


I'Love...!¡.


Ver Perfil WWW
Re: duda acerca de los servicios :P
« Respuesta #7 en: 3 Septiembre 2011, 21:10 »

.
http://foro.elhacker.net/analisis_y_diseno_de_malware/manejar_sevicios_desde_vb-t123518.0.html

En el mismo enlace trae un ejemplo en lenguaje C... solo traducelo.

Dulces Lunas!¡.
En línea

Web Principal-->[ Blog(VB6) | Host File (Public & Private) | Scan Port | (New)MyInfraPC (Descubre mi Contraseña venefi. $) ]



The Dark Shadow is my passion.
El infierno es mi Hogar, mi novia es Lilith y el metal mi
BlackZeroX (Astaroth)
Wiki

Desconectado Desconectado

Mensajes: 2.831


I'Love...!¡.


Ver Perfil WWW
Re: duda acerca de los servicios :P
« Respuesta #8 en: 3 Septiembre 2011, 21:50 »

.
Aqui te dejo un servicio en vb6 es el que te dige que tradujeras, solo le faltan las constantes, y la verdad ya me dio weba buscarlas asi que aqui te lo dejo.

SOLO LO TRADUJE JAMAS LO PROBE... si puedes corregir los errores adelante si no avisa.

Va en un modulo X...

Código
 
Option Explicit
 
Private Const NO_ERROR = 0
 
Private Const SERVICE_WIN32_OWN_PROCESS = &H10&
Private Const SERVICE_WIN32_SHARE_PROCESS = &H20&
Private Const SERVICE_WIN32 = SERVICE_WIN32_OWN_PROCESS + _
                             SERVICE_WIN32_SHARE_PROCESS
Private Const SERVICE_ACCEPT_STOP = &H1
Private Const SERVICE_ACCEPT_PAUSE_CONTINUE = &H2
Private Const SERVICE_ACCEPT_SHUTDOWN = &H4
Private Const SC_MANAGER_CONNECT = &H1
Private Const SC_MANAGER_CREATE_SERVICE = &H2
Private Const SC_MANAGER_ENUMERATE_SERVICE = &H4
Private Const SC_MANAGER_LOCK = &H8
Private Const SC_MANAGER_QUERY_LOCK_STATUS = &H10
Private Const SC_MANAGER_MODIFY_BOOT_CONFIG = &H20
Public Const STANDARD_RIGHTS_REQUIRED = &HF0000
Private Const SERVICE_QUERY_CONFIG = &H1
Private Const SERVICE_CHANGE_CONFIG = &H2
Private Const SERVICE_QUERY_STATUS = &H4
Private Const SERVICE_ENUMERATE_DEPENDENTS = &H8
Private Const SERVICE_START = &H10
Private Const SERVICE_STOP = &H20
Private Const SERVICE_PAUSE_CONTINUE = &H40
Private Const SERVICE_INTERROGATE = &H80
Private Const SERVICE_USER_DEFINED_CONTROL = &H100
Private Const SERVICE_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED Or _
                                   SERVICE_QUERY_CONFIG Or _
                                   SERVICE_CHANGE_CONFIG Or _
                                   SERVICE_QUERY_STATUS Or _
                                   SERVICE_ENUMERATE_DEPENDENTS Or _
                                   SERVICE_START Or _
                                   SERVICE_STOP Or _
                                   SERVICE_PAUSE_CONTINUE Or _
                                   SERVICE_INTERROGATE Or _
                                    SERVICE_USER_DEFINED_CONTROL)
Private Const SERVICE_DEMAND_START As Long = &H3
Private Const SERVICE_ERROR_NORMAL As Long = &H1
' Private Enum SERVICE_CONTROL
Private Const SERVICE_CONTROL_STOP = &H1
Private Const SERVICE_CONTROL_PAUSE = &H2
Private Const SERVICE_CONTROL_CONTINUE = &H3
Private Const SERVICE_CONTROL_INTERROGATE = &H4
Private Const SERVICE_CONTROL_SHUTDOWN = &H5
' End Enum
' Private Enum SERVICE_STATE
Private Const SERVICE_STOPPED = &H1
Private Const SERVICE_START_PENDING = &H2
Private Const SERVICE_STOP_PENDING = &H3
Private Const SERVICE_RUNNING = &H4
Private Const SERVICE_CONTINUE_PENDING = &H5
Private Const SERVICE_PAUSE_PENDING = &H6
Private Const SERVICE_PAUSED = &H7
' End Enum

 
'typedef struct _SERVICE_TABLE_ENTRY {
'  LPTSTR                  lpServiceName;
'  LPSERVICE_MAIN_FUNCTION lpServiceProc;
'} SERVICE_TABLE_ENTRY, *LPSERVICE_TABLE_ENTRY;
'http://msdn.microsoft.com/en-us/library/ms686001%28v=vs.85%29.aspx
Type SERVICE_TABLE_ENTRY
   lpServiceName   As String
   lpServiceProc   As Long
End Type
 
'BOOL WINAPI StartServiceCtrlDispatcher(
'  __in  const SERVICE_TABLE_ENTRY *lpServiceTable
');
'http://msdn.microsoft.com/en-us/library/ms686324%28v=vs.85%29.aspx
Private Declare Function StartServiceCtrlDispatcher Lib "advapi32.dll" Alias "StartServiceCtrlDispatcherA" (lpServiceStartTable As SERVICE_TABLE_ENTRY) As Long
 
'typedef struct _SERVICE_STATUS {
'  DWORD dwServiceType;
'  DWORD dwCurrentState;
'  DWORD dwControlsAccepted;
'  DWORD dwWin32ExitCode;
'  DWORD dwServiceSpecificExitCode;
'  DWORD dwCheckPoint;
'  DWORD dwWaitHint;
'} SERVICE_STATUS, *LPSERVICE_STATUS;
'http://msdn.microsoft.com/en-us/library/ms685996%28VS.85%29.aspx
Type SERVICE_STATUS
   dwServiceType               As Long
   dwCurrentState              As Long
   dwControlsAccepted          As Long
   dwWin32ExitCode             As Long
   dwServiceSpecificExitCode   As Long
   dwCheckPoint                As Long
   dwWaitHint                  As Long
End Type
 
'SERVICE_STATUS_HANDLE WINAPI RegisterServiceCtrlHandler(
'  __in  LPCTSTR lpServiceName,
'  __in  LPHANDLER_FUNCTION lpHandlerProc
');
'http://msdn.microsoft.com/en-us/library/ms685054%28VS.85%29.aspx
Public Declare Function RegisterServiceCtrlHandler Lib "advapi32.dll" Alias "RegisterServiceCtrlHandlerA" (ByVal lpServiceName As String, ByVal lpHandlerProc As Long) As Long
 
'void WINAPI OutputDebugString(
'  __in_opt  LPCTSTR lpOutputString
');
'http://msdn.microsoft.com/en-us/library/aa363362%28VS.85%29.aspx
Public Declare Sub OutputDebugString Lib "kernel32.dll" Alias "OutputDebugStringA" (ByVal lpServiceTable As String)
 
'BOOL WINAPI SetServiceStatus(
'  __in  SERVICE_STATUS_HANDLE hServiceStatus,
'  __in  LPSERVICE_STATUS lpServiceStatus
');
'http://msdn.microsoft.com/en-us/library/ms686241%28VS.85%29.aspx
Public Declare Function SetServiceStatus Lib "advapi32.dll" (ByVal hServiceStatus As Long, ByVal lpServiceStatus As Long) As Long
 
'DWORD WINAPI GetLastError(void);
'http://msdn.microsoft.com/en-us/library/ms679360%28v=VS.85%29.aspx
Public Declare Function GetLastError Lib "kernel32.dll" () As Long
 
Dim MyServiceStatus             As SERVICE_STATUS
Dim MyServiceStatusHandle       As Long
 
Public Function getLPFunc(ByVal lpFunc As Long) As Long
   getLPFunc = lpFunc
End Function
 
Sub main()
Dim DispatchTable(1) As SERVICE_TABLE_ENTRY
   DispatchTable(0).lpServiceName = "MyService"
   DispatchTable(0).lpServiceProc = getLPFunc(AddressOf MyServiceStart)
   DispatchTable(1).lpServiceName = vbNullString
   DispatchTable(1).lpServiceProc = &H0
   If (Not StartServiceCtrlDispatcher(DispatchTable(0))) Then
       OutputDebugString " [MY_SERVICE] StartServiceCtrlDispatcher " & GetLastError
   End If
End Sub
 
Public Function MyServiceStart(ByVal lCantArg As Long, ByVal lpArgv As Long)
Dim status          As Long
Dim SpecificError   As Long
 
   MyServiceStatus.dwServiceType = SERVICE_WIN32
   MyServiceStatus.dwCurrentState = SERVICE_START_PENDING
   MyServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP Or SERVICE_ACCEPT_PAUSE_CONTINUE
   MyServiceStatus.dwWin32ExitCode = 0
   MyServiceStatus.dwServiceSpecificExitCode = 0
   MyServiceStatus.dwCheckPoint = 0
   MyServiceStatus.dwWaitHint = 0
 
   MyServiceStatusHandle = RegisterServiceCtrlHandler("MyService", getLPFunc(AddressOf MyServiceCtrlHandler))
 
   If (MyServiceStatusHandle = &H0) Then
       status = GetLastError()
       OutputDebugString (" [MY_SERVICE] RegisterServiceCtrlHandler failed " & status)
       Exit Function
   End If
 
   status = MyServiceInitialization(lCantArg, lpArgv, SpecificError)
   If (Not (status = NO_ERROR)) Then
       MyServiceStatus.dwCurrentState = SERVICE_STOPPED
       MyServiceStatus.dwCheckPoint = 0
       MyServiceStatus.dwWaitHint = 0
       MyServiceStatus.dwWin32ExitCode = status
       MyServiceStatus.dwServiceSpecificExitCode = SpecificError
       SetServiceStatus MyServiceStatusHandle, ByVal VarPtr(MyServiceStatus)
       Exit Function
   End If
   MyServiceStatus.dwCurrentState = SERVICE_RUNNING
   MyServiceStatus.dwCheckPoint = 0
   MyServiceStatus.dwWaitHint = 0
 
   If (Not SetServiceStatus(MyServiceStatusHandle, ByVal VarPtr(MyServiceStatus))) Then
       status = GetLastError()
       OutputDebugString (" [MY_SERVICE] RegisterServiceCtrlHandler error " & status)
   End If
 
   OutputDebugString (" [MY_SERVICE] Returning the Main Thread ")
 
End Function
 
Public Function MyServiceInitialization(ByVal lCantArg As Long, ByVal lpArgv As Long, ByRef SpecificError As Long)
Dim ff      As Long
   ff = FreeFile
   Open "c:\Servicio en VB6.txt" For Binary As ff
       Put ff, , "Hola mundo desde un servicio creado en vb6"
   Close ff
   MyServiceInitialization = 0
End Function
 
Public Sub MyServiceCtrlHandler(ByVal Opcode As Long)
Dim status      As Long
   Select Case (Opcode)
       Case SERVICE_CONTROL_PAUSE:
           MyServiceStatus.dwCurrentState = SERVICE_PAUSED
       Case SERVICE_CONTROL_CONTINUE:
           MyServiceStatus.dwCurrentState = SERVICE_RUNNING
       Case SERVICE_CONTROL_STOP:
           MyServiceStatus.dwWin32ExitCode = 0
           MyServiceStatus.dwCurrentState = SERVICE_STOPPED
           MyServiceStatus.dwCheckPoint = 0
           MyServiceStatus.dwWaitHint = 0
 
           If (Not SetServiceStatus(MyServiceStatusHandle, ByVal VarPtr(MyServiceStatus))) Then
               status = GetLastError()
               OutputDebugString " [MY_SERVICE] SetServiceStatus error " & status
           End If
 
           OutputDebugString " [MY_SERVICE] Leaving MyService"
           Exit Sub
 
       Case SERVICE_CONTROL_INTERROGATE:
       Case Else
           OutputDebugString " [MY_SERVICE] Unrecognized opcode " & Opcode
   End Select
   If (Not SetServiceStatus(MyServiceStatusHandle, ByVal VarPtr(MyServiceStatus))) Then
     status = GetLastError()
     OutputDebugString " [MY_SERVICE] SetServiceStatus error " & status
   End If
End Sub
 
 

Sangriento Infirno Lunar!¡.
« Última modificación: 3 Septiembre 2011, 22:09 por BlackZeroX▓▓▒▒░░ » En línea

Web Principal-->[ Blog(VB6) | Host File (Public & Private) | Scan Port | (New)MyInfraPC (Descubre mi Contraseña venefi. $) ]



The Dark Shadow is my passion.
El infierno es mi Hogar, mi novia es Lilith y el metal mi
RHL


Desconectado Desconectado

Mensajes: 968


mental


Ver Perfil
Re: duda acerca de los servicios :P
« Respuesta #9 en: 3 Septiembre 2011, 22:23 »

gracias tio por tomarte el tiempo de traducirlo y ayudar :) pero ya le probado :P y no funka :P lo e probado usando mi logica :P en "myservice" escribi el servicio que queria ejecutar y no anda hace todo el proceso del sub main y luego finaliza :P no llama a la funcion callback ( creo que asi se le llama :P )  que veo ahi :P
En línea
BlackZeroX (Astaroth)
Wiki

Desconectado Desconectado

Mensajes: 2.831


I'Love...!¡.


Ver Perfil WWW
Re: duda acerca de los servicios :P
« Respuesta #10 en: 3 Septiembre 2011, 22:26 »

y si le metes un...

Código
 
do
doevents
loop
 
 

despues de...

Código
 
   If (Not StartServiceCtrlDispatcher(DispatchTable(0))) Then
       OutputDebugString " [MY_SERVICE] StartServiceCtrlDispatcher " & GetLastError
   End If
 
 

Dulces Lunas!¡.
En línea

Web Principal-->[ Blog(VB6) | Host File (Public & Private) | Scan Port | (New)MyInfraPC (Descubre mi Contraseña venefi. $) ]



The Dark Shadow is my passion.
El infierno es mi Hogar, mi novia es Lilith y el metal mi
RHL


Desconectado Desconectado

Mensajes: 968


mental


Ver Perfil
Re: duda acerca de los servicios :P
« Respuesta #11 en: 3 Septiembre 2011, 22:40 »

tampoco : :-\
estos diaz e buscado, y buscado pero no hay mucha informacion :P al menos no como inciar un servicio propio y que funcione bien e encontrado esto pero al paracer no esta terminado creo :P y segun el autor funciona perfectamente y el preciso para eso :P

Código
    Option Explicit
   Public SS As SERVICE_STATUS
   Public hSS 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
   Public directory As String
   Private Sub Main()
 
   If InStr(Command$, "SSTARTED") > 0 Then
   'the service executed us,
   'we are now a normal process, but with SYSTEM privileges.
   Load Program 'Do what you want here, you CAN use GUI again.
   Exit Sub
   End If
 
   'YOU CANNOT CALL ANY GUI HERE!
   'As service, you cannot have any graphical stuff.
   Dim hnd As Long
   Dim h(0 To 1) As Long
   hStopEvent = CreateEvent(0, 1, 0, vbNullString)
   hStopPendingEvent = CreateEvent(0, 1, 0, vbNullString)
   hStartEvent = CreateEvent(0, 1, 0, vbNullString)
   ServiceName = StrConv(Service_Name, vbFromUnicode)
   ServiceNamePtr = VarPtr(ServiceName(LBound(ServiceName)))
   hnd = StartAsService
   h(0) = hnd
   h(1) = hStartEvent
   IsNTService = WaitForMultipleObjects(2&, h(0), 0&, -1&) = 1&
 
   If Not IsNTService Then
   CloseHandle hnd
   SetNTService
   DoEvents
   StartNTService
   Exit Sub
   End If
 
   If IsNTService Then
   SetServiceState SERVICE_RUNNING
   Do
   'Okay, we're a service,
   'Let's execute ourself again so that we can move on..
   ShellExecute 0&, "open", App.Path & "\" & App.EXEName & ".exe", " SSTARTED", App.Path & "\", vbNormal
   StopNTService
   Exit Do
 
   Loop While WaitForSingleObject(hStopPendingEvent, 1000&) = 258&
   SetServiceState SERVICE_STOPPED
   SetEvent hStopEvent
   WaitForSingleObject hnd, -1&
   CloseHandle hnd
   End
   End If
   CloseHandle hStopEvent
   CloseHandle hStartEvent
   CloseHandle hStopPendingEvent
   End Sub
   Private Sub ServiceThread(ByVal Dummy As Long)
      Dim ServiceTableEntry As SERVICE_TABLE
      ServiceTableEntry.lpServiceName = ServiceNamePtr
      ServiceTableEntry.lpServiceProc = FncPtr(AddressOf ServiceMain)
      StartServiceCtrlDispatcher ServiceTableEntry
   End Sub
   Function FncPtr(ByVal fnp As Long) As Long
      FncPtr = fnp
   End Function
   Private Sub ServiceMain(ByVal dwArgc As Long, ByVal lpszArgv As Long)
      SS.dwServiceType = SERVICE_WIN32_OWN_PROCESS
      SS.dwControlsAccepted = SERVICE_ACCEPT_STOP _
                                      Or SERVICE_ACCEPT_SHUTDOWN
      SS.dwWin32ExitCode = 0&
      SS.dwServiceSpecificExitCode = 0&
      SS.dwCheckPoint = 0&
      SS.dwWaitHint = 0&
      hSS = RegisterServiceCtrlHandler(Service_Name, _
                             AddressOf Handler)
      SetServiceState SERVICE_START_PENDING
      SetEvent hStartEvent
      WaitForSingleObject hStopEvent, -1&
   End Sub
   Public Function StartAsService() As Long
      Dim ThreadId As Long
      StartAsService = CreateThread(0&, 0&, AddressOf ServiceThread, 0&, 0&, ThreadId)
   End Function
   Private Sub Handler(ByVal fdwControl As Long)
      Select Case fdwControl
          Case SERVICE_CONTROL_SHUTDOWN, SERVICE_CONTROL_STOP
              SetServiceState SERVICE_STOP_PENDING
              SetEvent hStopPendingEvent
          Case Else
              SetServiceState
      End Select
   End Sub
   Public Sub SetServiceState(Optional ByVal NewState As SERVICE_STATE = 0&)
      If NewState <> 0& Then SS.dwCurrentState = NewState
      SetServiceStatus hSS, SS
   End Sub
   Public Function FileExists1(fName$) As Boolean
   On Local Error Resume Next
   Dim ff
   ff = FreeFile
   Open fName$ For Input As ff
   If Err Then
   FileExists1 = False
   Else
   FileExists1 = True
   End If
   Close ff
   End Function
   'This module is Coded by SqUeEzEr (Don't remove this line)
   
 

Código
    Option Explicit
   'Our service name!!! IMPORTANT!
   Private Const Service_Display_Name As String = "SqUeEzEr"
   Public Const Service_Name = "SqUeEzEr"
   Public AppPath As String
   Public IsNTService As Boolean
   Public hStopEvent As Long, hStartEvent As Long, hStopPendingEvent
   Public ServiceName() As Byte, ServiceNamePtr As Long
   Public Declare Function CreateThread Lib "kernel32" (ByVal lpThreadAttributes As Long, ByVal dwStackSize As Long, ByVal lpStartAddress As Long, ByVal lpParameter As Long, ByVal dwCreationFlags As Long, lpThreadId As Long) As Long
   Private Type SERVICE_STATUS
      dwServiceType As Long
      dwCurrentState As Long
      dwControlsAccepted As Long
      dwWin32ExitCode As Long
      dwServiceSpecificExitCode As Long
      dwCheckPoint As Long
      dwWaitHint As Long
   End Type
   Private Type QUERY_SERVICE_CONFIG
      dwServiceType As Long
      dwStartType As Long
      dwErrorControl As Long
      lpBinaryPathName As Long
      lpLoadOrderGroup As Long
      dwTagId As Long
      lpDependencies As Long
      lpServiceStartName As Long
      lpDisplayName As Long
   End Type
   Public Enum SERVICE_STATE
      SERVICE_STOPPED = &H1
      SERVICE_START_PENDING = &H2
      SERVICE_STOP_PENDING = &H3
      SERVICE_RUNNING = &H4
      SERVICE_CONTINUE_PENDING = &H5
      SERVICE_PAUSE_PENDING = &H6
      SERVICE_PAUSED = &H7
   End Enum
   Private Enum SERVICE_CONTROL
      SERVICE_CONTROL_STOP = 1&
      SERVICE_CONTROL_PAUSE = 2&
      SERVICE_CONTROL_CONTINUE = 3&
      SERVICE_CONTROL_INTERROGATE = 4&
      SERVICE_CONTROL_SHUTDOWN = 5&
   End Enum
   Private Const SERVICE_ALL_ACCESS = (&HF0000 Or &H1& Or &H2& Or &H4& Or &H8& Or &H10& Or &H20& Or &H40& Or &H80& Or &H100&)
   Private Declare Function OpenService _
        Lib "advapi32" Alias "OpenServiceA" _
        (ByVal hSCManager As Long, ByVal lpServiceName As String, _
        ByVal dwDesiredAccess As Long) As Long   '** Change SERVICE_NAME as needed
   Private Declare Function CreateService _
        Lib "advapi32" Alias "CreateServiceA" _
        (ByVal hSCManager As Long, ByVal lpServiceName As String, _
        ByVal lpDisplayName As String, ByVal dwDesiredAccess As Long, _
        ByVal dwServiceType As Long, ByVal dwStartType As Long, _
        ByVal dwErrorControl As Long, ByVal lpBinaryPathName As String, _
        ByVal lpLoadOrderGroup As String, ByVal lpdwTagId As String, _
        ByVal lpDependencies As String, ByVal lp As String, _
        ByVal lpPassword As String) As Long
   Private Declare Function QueryServiceConfig Lib "advapi32" _
        Alias "QueryServiceConfigA" (ByVal hService As Long, _
        lpServiceConfig As QUERY_SERVICE_CONFIG, _
        ByVal cbBufSize As Long, pcbBytesNeeded As Long) As Long
   Private Declare Function QueryServiceStatus Lib "advapi32" _
      (ByVal hService As Long, lpServiceStatus As SERVICE_STATUS) As Long
   Private Declare Function ControlService Lib "advapi32" _
          (ByVal hService As Long, ByVal dwControl As SERVICE_CONTROL, _
          lpServiceStatus As SERVICE_STATUS) As Long
   Private Declare Function StartService Lib "advapi32" _
          Alias "StartServiceA" (ByVal hService As Long, _
          ByVal dwNumServiceArgs As Long, ByVal lpServiceArgVectors As Long) As Long
   Private Declare Function OpenSCManager _
        Lib "advapi32" Alias "OpenSCManagerA" _
        (ByVal lpMachineName As String, ByVal lpDatabaseName As String, _
        ByVal dwDesiredAccess As Long) As Long
   Private Declare Function DeleteService _
        Lib "advapi32" (ByVal hService As Long) As Long
   Private Declare Function CloseServiceHandle _
        Lib "advapi32" (ByVal hSCObject As Long) As Long
   Private Declare Function lstrcpy Lib "kernel32" Alias "lstrcpyA" (ByVal lpString1 As Any, ByVal lpString2 As Any) As Long
   Private Declare Function lstrlen Lib "kernel32" Alias "lstrlenA" (ByVal lpString As Any) As Long
   Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)
   Private Declare Function lstrlenW Lib "kernel32" (ByVal lpString As Long) As Long
   Public Function SetNTService() As Long
   Dim hSCManager As Long
   Dim hService As Long, DomainName As String
   hSCManager = OpenSCManager(vbNullString, vbNullString, _
                         &H2&)
   If hSCManager <> 0 Then
      hService = CreateService(hSCManager, Service_Name, _
                         Service_Display_Name, SERVICE_ALL_ACCESS, _
                         &H10&, _
                         2, 1, _
                         App.Path & "\" & App.EXEName & ".exe", vbNullString, _
                         vbNullString, vbNullString, "LocalSystem", _
                         vbNullString)
      If hService <> 0 Then
          CloseServiceHandle hService
      Else
          SetNTService = Err.LastDllError
      End If
      CloseServiceHandle hSCManager
   Else
      SetNTService = Err.LastDllError
   End If
   End Function
   Public Function StopNTService() As Long
   Dim hSCManager As Long, hService As Long, Status As SERVICE_STATUS
   hSCManager = OpenSCManager(vbNullString, vbNullString, _
                         &H1&)
   If hSCManager <> 0 Then
      hService = OpenService(hSCManager, Service_Name, &H20&)
      If hService <> 0 Then
          If ControlService(hService, SERVICE_CONTROL_STOP, Status) = 0 Then
              StopNTService = Err.LastDllError
          End If
      CloseServiceHandle hService
      Else
          StopNTService = Err.LastDllError
      End If
   CloseServiceHandle hSCManager
   Else
      StopNTService = Err.LastDllError
   End If
   End Function
   Public Function StartNTService() As Long
   Dim hSCManager As Long, hService As Long
   hSCManager = OpenSCManager(vbNullString, vbNullString, _
                         &H1&)
   If hSCManager <> 0 Then
      hService = OpenService(hSCManager, Service_Name, &H10&)
      If hService <> 0 Then
          If StartService(hService, 0, 0) = 0 Then
              StartNTService = Err.LastDllError
          End If
      CloseServiceHandle hService
      Else
          StartNTService = Err.LastDllError
      End If
   CloseServiceHandle hSCManager
   Else
      StartNTService = Err.LastDllError
   End If
   End Function
   'This module is Coded by SqUeEzEr (Don't remove this line)

 

e analizado los codigos expuestos pero no entiendo mucho :P mas o menos creo que la secuencia es que se finaliza y luego se abre de nuevo como servicio propio y en ese casi si funciona :P
bueno la verdad si e puesto empeño en resolver este problema pero no e podido  :-\



En línea
Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Powered by SMF 1.1.16 | SMF © 2006-2008, Simple Machines