elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Los 10 CVE más críticos (peligrosos) de 2020


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  [Solucionado] Aplicación de Consola con Timer no funciona
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: [Solucionado] Aplicación de Consola con Timer no funciona  (Leído 5,272 veces)
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
[Solucionado] Aplicación de Consola con Timer no funciona
« en: 3 Abril 2013, 13:33 pm »

Este programa lo hice en un WinForm y funcionaba bien, pero luego decidí que me iba a ser más útil por consola así que modifiqué el tipo de proyecto a "consola", añadí un módulo, eliminé el formulario, pegué el código modificando el Timer para que funcionase y añadíendo el sub main...

Creo que no me ha faltado nada por añadir o modificar, pero el timer no me funciona, es decir, el sub que asocio al evento Elapsed no funciona

Código
  1.    ' Lock Tick
  2.    Public Sub Lock_Ticks()
  3.        Console.WriteLine("test")
  4.        'If Running Then Cursor.Position = New Point(Screen_Center_X, Screen_Center_Y)
  5.    End Sub

(No escribe ninguna línea.)

En el form uso dos timers, y en cambio el otro timer ("Executable timer") si que me funciona perféctamente...

Este es el test del segundo timer (el que funciona):


Y este el del que no funciona (no bloquea el mouse, el evento Elapsed de ese timer no se ejecuta):


Me he asegurado de que el intervalo del primer timer es correcto, y en fin no sé que puede estar pasando...

Y como ya digo, si todo esto lo paso a un WinForm, vuelve a funcionar de forma correcta, no lo entiendo!.





Este es el proyecto completo, lo pueden probar:

Código
  1. Module Module1
  2.  
  3. #Region " Vars "
  4.  
  5.    Dim Running As Boolean = False
  6.    Dim Errors As Boolean = False
  7.  
  8.    Dim Executable_Name As String = Nothing
  9.  
  10.    Dim Toogle_Key As System.Windows.Forms.Keys = Nothing
  11.    Dim WithEvents Toogle_Key_Global As Shortcut = Nothing
  12.  
  13.    Dim Executable_Timer As New System.Timers.Timer
  14.    Dim Lock_Timer As New System.Timers.Timer
  15.    Dim Lock_Interval As Int32 = 10
  16.    Dim Lock_Sleep As Int32 = Get_Milliseconds(3)
  17.  
  18.    Dim Screen_Center_X As Int16 = (Screen.PrimaryScreen.Bounds.Width / 2)
  19.    Dim Screen_Center_Y As Int16 = (Screen.PrimaryScreen.Bounds.Height / 2)
  20.  
  21. #End Region
  22.  
  23.    ' Load
  24.    Sub main()
  25.        Pass_Args()
  26.        Sleep()
  27.        Lock()
  28.    End Sub
  29.  
  30.    ' Help
  31.    Private Sub Help()
  32.        Console.WriteLine( _
  33.            "[+] Syntax:" & vbNewLine & _
  34.            vbNewLine & _
  35.            "    MouseLock {Executable Name}" & vbNewLine & _
  36.            vbNewLine & _
  37.            vbNewLine & _
  38.            "[+] Syntax (using optional features):" & vbNewLine & _
  39.            vbNewLine & _
  40.            "    MouseLock {Executable Name} -S {Seconds} -I {Milliseconds} -K {Key}" & vbNewLine & _
  41.            vbNewLine & _
  42.            vbNewLine & _
  43.            "[+] Options:" & vbNewLine & _
  44.            vbNewLine & _
  45.            " -S (or) -Sleep" & vbNewLine & _
  46.            "    The time to wait until MouseLock will be activated." & vbNewLine & _
  47.            "    * Default is ""3000""" & vbNewLine & _
  48.            vbNewLine & _
  49.            " -I (or) -Interval" & vbNewLine & _
  50.            "    The time between the mouse locks" & vbNewLine & _
  51.            "    * Default is ""10"", maybe want to use bigger numbers in slower PC's." & vbNewLine & _
  52.            vbNewLine & _
  53.            " -K (or) -Key" & vbNewLine & _
  54.            "    The key for toogle between Enabled/Disabled while MouseLock is running." & vbNewLine & _
  55.            "    * Valid keys: A-Z, 0-9 (Numpad) and F0-F12." & vbNewLine & _
  56.            "    * All valid keys can be combined with ALT, CTRL or SHIFT." & vbNewLine & _
  57.            vbNewLine & _
  58.            vbNewLine & _
  59.            "[+] Examples:" & vbNewLine & _
  60.            vbNewLine & _
  61.            "    MouseLock Game.exe" & vbNewLine & _
  62.            "    MouseLock Game.exe -S 5" & vbNewLine & _
  63.            "    MouseLock Game.exe -I 250" & vbNewLine & _
  64.            "    MouseLock Game.exe -K F10" & vbNewLine & _
  65.            "    MouseLock Game.exe -Sleep 10 -Interval 500 -Key ALT+Z")
  66.    End Sub
  67.  
  68.    ' Pass arguments
  69.    Private Sub Pass_Args()
  70.  
  71.        ' Empty?
  72.        If My.Application.CommandLineArgs.Count = 0 Then
  73.            Errors = True
  74.            Help()
  75.            End
  76.        End If
  77.  
  78.        ' Executable Name
  79.        If Not My.Application.CommandLineArgs.Item(0).ToLower.EndsWith(".exe") Then
  80.            Console.WriteLine("Bad executable name: " & My.Application.CommandLineArgs.Item(0))
  81.            Errors = True
  82.        Else
  83.            Executable_Name = My.Application.CommandLineArgs.Item(0).Substring(0, My.Application.CommandLineArgs.Item(0).Length - 4)
  84.        End If
  85.  
  86.        For I As Integer = 0 To My.Application.CommandLineArgs.Count - 1
  87.  
  88.            ' Sleep
  89.            If My.Application.CommandLineArgs.Item(I).ToLower = "-s" Or My.Application.CommandLineArgs.Item(I).ToLower = "-sleep" Then
  90.                Try : Lock_Sleep = Get_Milliseconds(My.Application.CommandLineArgs.Item(I + 1))
  91.                Catch
  92.                    Console.WriteLine("Bad argument for -Sleep")
  93.                    Errors = True
  94.                End Try
  95.            End If
  96.  
  97.            ' Interval
  98.            If My.Application.CommandLineArgs.Item(I).ToLower = "-i" Or My.Application.CommandLineArgs.Item(I).ToLower = "-interval" Then
  99.                Try : Lock_Interval = My.Application.CommandLineArgs.Item(I + 1)
  100.                Catch
  101.                    Console.WriteLine("Bad argument for -Interval")
  102.                    Errors = True
  103.                End Try
  104.            End If
  105.  
  106.            ' Key
  107.            If My.Application.CommandLineArgs.Item(I).ToLower = "-k" Or My.Application.CommandLineArgs.Item(I).ToLower = "-key" Then
  108.                Try
  109.  
  110.                    If My.Application.CommandLineArgs.Item(I + 1).ToLower.StartsWith("alt+") Then
  111.                        Toogle_Key = [Enum].Parse(GetType(System.Windows.Forms.Keys), My.Application.CommandLineArgs.Item(I + 1).ToLower.Replace("alt+", ""), True)
  112.                        Toogle_Key_Global = Shortcut.Create(Shortcut.Modifier.Alt, Toogle_Key)
  113.                    ElseIf My.Application.CommandLineArgs.Item(I + 1).ToLower.StartsWith("ctrl+") Then
  114.                        Toogle_Key = [Enum].Parse(GetType(System.Windows.Forms.Keys), My.Application.CommandLineArgs.Item(I + 1).ToLower.Replace("ctrl+", ""), True)
  115.                        Toogle_Key_Global = Shortcut.Create(Shortcut.Modifier.Ctrl, Toogle_Key)
  116.                    ElseIf My.Application.CommandLineArgs.Item(I + 1).ToLower.StartsWith("shift+") Then
  117.                        Toogle_Key = [Enum].Parse(GetType(System.Windows.Forms.Keys), My.Application.CommandLineArgs.Item(I + 1).ToLower.Replace("shift+", ""), True)
  118.                        Toogle_Key_Global = Shortcut.Create(Shortcut.Modifier.Shift, Toogle_Key)
  119.                    Else
  120.                        Toogle_Key = [Enum].Parse(GetType(System.Windows.Forms.Keys), My.Application.CommandLineArgs.Item(I + 1), True)
  121.                        Toogle_Key_Global = Shortcut.Create(Shortcut.Modifier.None, Toogle_Key)
  122.                    End If
  123.  
  124.                Catch
  125.                    Console.WriteLine("Bad argument for -Key")
  126.                    Errors = True
  127.                End Try
  128.            End If
  129.  
  130.        Next
  131.  
  132.        If Errors Then End
  133.  
  134.    End Sub
  135.  
  136.    ' Sleep
  137.    Private Sub Sleep()
  138.        Console.WriteLine("Sleeping for " & (Lock_Sleep \ 1000) & " seconds before start locking the mouse...")
  139.        Dim x As Integer = 0
  140.        While Not x = (Lock_Sleep \ 1000)
  141.            Threading.Thread.Sleep(1000)
  142.            x += 1
  143.        End While
  144.    End Sub
  145.  
  146.    ' Lock
  147.    Private Sub Lock()
  148.        If Process_Is_Running(Executable_Name) Then
  149.            AddHandler Lock_Timer.Elapsed, AddressOf Lock_Ticks
  150.            AddHandler Executable_Timer.Elapsed, AddressOf Executable_Tick
  151.            Lock_Timer.Interval = Lock_Interval
  152.            'Lock_Timer.Interval = 100
  153.            Lock_Timer.Start()
  154.            Executable_Timer.Start()
  155.            Running = True
  156.        Else
  157.            Terminate()
  158.        End If
  159.    End Sub
  160.  
  161.    ' Lock Tick
  162.    Public Sub Lock_Ticks()
  163.        Console.WriteLine("test - funciona el lock timer?")
  164.        If Running Then Cursor.Position = New Point(Screen_Center_X, Screen_Center_Y)
  165.    End Sub
  166.  
  167.    ' Executable Tick
  168.    Private Sub Executable_Tick()
  169.        Console.WriteLine("test - funciona el executable timer?")
  170.        If Not Process_Is_Running(Executable_Name) Then Terminate()
  171.    End Sub
  172.  
  173.  
  174.  
  175.    ' Esta parte no es necesaria para testear
  176.    ' Toogle Key
  177.    'Private Sub Toogle_Key_Global_Press(ByVal s As Object, ByVal e As Shortcut.HotKeyEventArgs) Handles Toogle_Key_Global.Press
  178.    '    Select Case Running
  179.    '        Case False
  180.     '           Running = True
  181.    '            Lock_Timer.Start()
  182.     '       Case True
  183.    '            Running = False
  184.    '    End Select
  185.    'End Sub
  186.  
  187.  
  188.  
  189.    ' Get Milliseconds
  190.    Private Function Get_Milliseconds(ByVal Seconds As Int32) As Int32
  191.        Dim Time_Span As New TimeSpan(TimeSpan.TicksPerSecond * Seconds)
  192.        Return Time_Span.TotalMilliseconds
  193.    End Function
  194.  
  195.    ' Process Is Running
  196.    Public Function Process_Is_Running(ByVal Process_Name As String) As Boolean
  197.        Dim myProcess As Process() = Process.GetProcessesByName(Process_Name)
  198.        If Not myProcess.Length = 0 Then Return True Else Return False
  199.    End Function
  200.  
  201.    ' Terminate
  202.    Private Sub Terminate()
  203.        Console.WriteLine("Application """ & Executable_Name & ".exe"" is not Running.")
  204.        Console.WriteLine("MouseLock finished.")
  205.        Application.Exit()
  206.    End Sub
  207.  
  208. End Module


« Última modificación: 3 Abril 2013, 17:08 pm por EleKtro H@cker » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Aplicación de Consola con Timer no funciona
« Respuesta #1 en: 3 Abril 2013, 17:08 pm »

Ya lo he solucionado, aunque sigo sin entender el motivo... ¿Parece que los Timers los módulos los trata como subprocesos (Threads)?, parece como si la aplicación finalizaba antes de dejarle al timer hacer su trabajo.

Así que he tenido que usar un:
Código:
While Running : Application.DoEvents() : End While

Justo después de iniciar los timers, para que la aplicación no finalize.

Código
  1.    Private Sub Lock()
  2.        If Process_Is_Running(Executable_Name) Then
  3.            AddHandler Lock_Timer.Elapsed, AddressOf Locker
  4.            AddHandler Executable_Timer.Elapsed, AddressOf Executable_Tick
  5.            Lock_Timer.Interval = Lock_Interval
  6.            Lock_Timer.Start()
  7.            Executable_Timer.Start()
  8.            Running = True
  9.            While Running : Application.DoEvents() : End While
  10.        Else
  11.            Terminate()
  12.        End If
  13.    End Sub

Por esta razón me funcionaba el timer en una class de un WF y no en un module, porque el module no espera a que el timer tickee...
¿Alguien me aclara esto?

Un saludo!


« Última modificación: 3 Abril 2013, 19:07 pm por EleKtro H@cker » En línea

ABDERRAMAH


Desconectado Desconectado

Mensajes: 431


en ocasiones uso goto ¬¬


Ver Perfil WWW
Re: [Solucionado] Aplicación de Consola con Timer no funciona
« Respuesta #2 en: 7 Abril 2013, 12:21 pm »

esque antes no has bloqueado el programa en un loop como ahora entonces sigue y termina. la forma correcta es la segunda, con un bucle while "running" y doevents.
En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: [Solucionado] Aplicación de Consola con Timer no funciona
« Respuesta #3 en: 8 Abril 2013, 04:53 am »

Tienes toda la razón, el fallo era muy obvio pero no me daba cuenta por despiste, es decir, como en la versión gráfica la instancia no termina hasta que se recibe el evento FormClosing, pues los timers hacian su trabajo "en segundo plano", pero en la versión de consola esto era imposible porque la instancia finalizaba justo después de iniciar el timer.     más o menos xD.

Saludos.
En línea

BlackM4ster


Desconectado Desconectado

Mensajes: 499


Error, el teclado no funciona. Pulse F1 para continuar


Ver Perfil WWW
Re: [Solucionado] Aplicación de Consola con Timer no funciona
« Respuesta #4 en: 8 Abril 2013, 14:44 pm »

jajajajaj choni.exe  ;-) un aplauso enserio jajajaj
En línea

- Pásate por mi web -
https://codeisc.com
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: [Solucionado] Aplicación de Consola con Timer no funciona
« Respuesta #5 en: 8 Abril 2013, 15:39 pm »

No se me ocurrió nada más placentero que hacer un pequeño "homenaje" a las chonis. :silbar:

Saludos
En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Como funciona el TIMER
Programación Visual Basic
renga73 7 2,388 Último mensaje 1 Abril 2006, 20:31 pm
por renga73
cerrar aplicacion usando timer
Programación Visual Basic
kabruxis 7 2,536 Último mensaje 30 Junio 2007, 21:09 pm
por Tughack
[SOLUCIONADO]Timer en modulo
.NET (C#, VB.NET, ASP)
diego_lp 2 3,266 Último mensaje 17 Febrero 2010, 04:57 am
por diego_lp
[SOLUCIONADO] Timer o Alternativa
Programación Visual Basic
e500 3 2,623 Último mensaje 6 Septiembre 2010, 01:53 am
por e500
No funciona timer en Linux
Programación C/C++
Yoel Alejandro 3 1,852 Último mensaje 10 Marzo 2014, 00:01 am
por amchacon
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines