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

 

 


Tema destacado: Únete al Grupo Steam elhacker.NET


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  Poner un contador en visual basic 2013 y ver la ip
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Poner un contador en visual basic 2013 y ver la ip  (Leído 3,466 veces)
Piyulta

Desconectado Desconectado

Mensajes: 4


Ver Perfil
Poner un contador en visual basic 2013 y ver la ip
« en: 17 Enero 2017, 05:23 am »

Hola quiero saber como poner en un label el tiempo en horas ej: (48:00:00) sin que este
se reinicie cuando se cierra el programa, es decir, imaginemos que el usuario abre el programa y al momento de eso el contador salga en un label con las horas, minutos y segundos hasta llegar a (00:00:00) y cuando eso pase, que el programa se elimine.

También quiero saber como hacer para que al momento de iniciar el programa en un label
aparezca la IP del usuario, he buscado pero no encuentro nada aparte no entiendo mucho ya que soy nuevo en esto.

Utilizo visual basic 2013, eso es lo único que me esta faltando para terminar mi proyecto, pero no se como hacerlo, si me pueden ayudar se los agradeceria  :D


En línea

engel lex
Moderador Global
***
Desconectado Desconectado

Mensajes: 15.514



Ver Perfil
Re: Poner un contador en visual basic 2013 y ver la ip
« Respuesta #1 en: 17 Enero 2017, 05:27 am »

para la ip tienes que leer alguna pagina web que te la proporcione si quieres la ip publica, para mantener el contador, tendrás que guardar el tiempo en un archivo y leerlo cuando abras el programa


En línea

El problema con la sociedad actualmente radica en que todos creen que tienen el derecho de tener una opinión, y que esa opinión sea validada por todos, cuando lo correcto es que todos tengan derecho a una opinión, siempre y cuando esa opinión pueda ser ignorada, cuestionada, e incluso ser sujeta a burla, particularmente cuando no tiene sentido alguno.
Piyulta

Desconectado Desconectado

Mensajes: 4


Ver Perfil
Re: Poner un contador en visual basic 2013 y ver la ip
« Respuesta #2 en: 17 Enero 2017, 05:30 am »

Ok perfecto lo de la ip entendido! :), pero eso del contador aun no me queda claro, la verdad es que no entendi, me podrias dar un ejemplo? supongamos que quiero poner el tiempo en el label 8 y como creo el archivo para guardar el tiempo?
En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.777



Ver Perfil
Re: Poner un contador en visual basic 2013 y ver la ip
« Respuesta #3 en: 17 Enero 2017, 08:37 am »

Hola.

Para continuar/proseguir por donde lo dejaste con el tiempo de la cuenta atrás despues de haber terminado la ejecución de tu aplicación, tienes varias opciones, la más sencilla y cómoda sería utilizar la infraestructura My.Settings para almacenar un valor de tipo Double donde le asignarías un valor de inicialización negativo de -1 la primera vez que inicies tu app (a modo de flag/señal), y al finalizar la ejecución de la app le asignarías los milisegundos actuales, entonces, al iniciar de nuevo la app simplemente leerías el último valor establecido y continuarías la cuenta atrás desde ahí.

Esto que acabo de explicar, en un código se vería reflejado más o menos de la siguiente manera:



Código
  1. Public NotInheritable Class Form1 : Inherits Form
  2.  
  3.    Private time As TimeSpan = TimeSpan.FromMinutes(60)
  4.  
  5.    Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) _
  6.    Handles MyBase.Load
  7.  
  8.        Select Case My.Settings.CurrentCountDownMs
  9.  
  10.            Case Is = -1.0R
  11.                ' Esta es la primera vez que se inicia la aplicación, así que lo ignoramos.
  12.  
  13.            Case Is = 0R
  14.                ' El tiempo se acabó.
  15.                Environment.FailFast("Tiempo agotado.")
  16.  
  17.            Case Else
  18.                ' Le asignamos el tiempo guardado al objeto de tipo TimeSpan.
  19.                Me.time = TimeSpan.FromMilliseconds(My.Settings.CurrentCountDownMs)
  20.  
  21.        End Select
  22.  
  23.    End Sub
  24.  
  25.    Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) _
  26.    Handles MyBase.FormClosing
  27.  
  28.        ' Guardamos el tiempo actual al finalizar la aplicación.
  29.        My.Settings.CurrentCountDownMs = Me.time.TotalMilliseconds
  30.  
  31.    End Sub
  32.  
  33. End Class

Nota: Evidéntemente el ejemplo de arriba no incluye la lógica/algoritmo que estés usando para la cuenta atrás, tan solo demuestra la manera en que podrías guardar y leer el valor de la cuenta atrás.

La segunda manera de llevar a cabo esto, la manera que Microsoft recomienda exprésamente en sus directrices de diseño, sería almacenar cualquier valor de la aplicación en una clave de registro. Esto puedes hacerlo de manera sencilla mediante la class Microsoft.Win32.Registry, en Google y MSDN encontrarás toda la información necesaria. Esto en realidad no aporta ninguna ventaja admirable y por eso lo propongo como 2ª opción, puesto que un valor del registro se puede eliminar facilmente, sin embargo, en otras circunstancias podrías tener tus valores estructurados en el registro de Windows facilitando así el acceso y la edición a dichos valores.

La tercera y última forma de hacer esto, la más rudimentaria y por ello también la ménos ventajosa, sería escribir un archivo de texto donde almacenar el valor de "tiempo" y administrar su escritura y lectura por ti mismo, en un archivo de texto plano sin formato, o en un archivo CSV, o con formato Xml, o en un archivo portable de inicialización (archivo.ini)... hay varias formas también.

PD: Nótese que la primera solución con My.Settings, también escribe un archivo de texto plano (Xml), pero siguiendo un patrón de directorios estructurado y todo el embrollo de escritura y lectura es administrado y controlado por .NET Framework.



Respecto a la obtención de la IP, bueno, hay varios aspectos a tener en cuenta así que tu pregunta se podría interpretar de varias formas.

Si quieres obtener la IP pública, entonces creo que algo que te daría un resultado satisfactorio sería establecer una conexión a cualquier servicio gratuito para comprobar la IP, como por ejemplo http://checkip.dyndns.org/

El siguiente código lo he sacado de mi framework de pago ElektroKit para .NET (si te interesa, puedes encontrarlo a la venta de forma exclusiva en Envato)

Código
  1. ''' ----------------------------------------------------------------------------------------------------
  2. ''' <summary>
  3. ''' Gets the public IP address of the current machine.
  4. ''' </summary>
  5. ''' ----------------------------------------------------------------------------------------------------
  6. ''' <example> This is a code example.
  7. ''' <code>
  8. ''' Dim ip As String = GetPublicIp()
  9. ''' </code>
  10. ''' </example>
  11. ''' ----------------------------------------------------------------------------------------------------
  12. ''' <returns>
  13. ''' The IP address.
  14. ''' </returns>
  15. ''' ----------------------------------------------------------------------------------------------------
  16. <DebuggerStepThrough>
  17. Public Shared Function GetPublicIp() As String
  18.  
  19.    Dim req As WebRequest = WebRequest.Create("http://checkip.dyndns.org/")
  20.  
  21.    Using resp As WebResponse = req.GetResponse()
  22.  
  23.        Using sr As New StreamReader(resp.GetResponseStream())
  24.            Dim html As XDocument = XDocument.Parse(sr.ReadToEnd())
  25.            Dim body As String = html.<html>.<body>.Value
  26.            Return body.Substring(body.LastIndexOf(" ")).Trim()
  27.        End Using
  28.  
  29.    End Using
  30.  
  31. End Function

Modo de empleo:
Código
  1. Dim ip As String = GetPublicIp()

Un saludo!
« Última modificación: 17 Enero 2017, 08:58 am por Eleкtro » En línea


Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.777



Ver Perfil
Re: Poner un contador en visual basic 2013 y ver la ip
« Respuesta #4 en: 17 Enero 2017, 09:03 am »

Si a todo esto también necesitas una solución completa para implementar ya sea un cronómetro o una cuenta atrás, aquí tienes una solución que ideé hace tiempo (nuevamente sacada de mi librería de clases ElektroKit):

Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 12-December-2015
  4. ' ***********************************************************************
  5.  
  6. #Region " Public Members Summary "
  7.  
  8. #Region " Constructors "
  9.  
  10. ' New()
  11.  
  12. #End Region
  13.  
  14. #Region " Events "
  15.  
  16. ' TimeUpdated(Object, TimeMeasurerUpdatedEventArgs)
  17.  
  18. #End Region
  19.  
  20. #Region " Properties "
  21.  
  22. ' MaxValue As Double
  23. ' State As TimeMeasurerState
  24. ' UpdateInterval As Integer
  25.  
  26. #End Region
  27.  
  28. #Region " Methods "
  29.  
  30. ' Start(Double)
  31. ' Start(Date, Date)
  32. ' Start(TimeSpan)
  33. ' Pause()
  34. ' Resume()
  35. ' Stop()
  36. ' Dispose()
  37.  
  38. #End Region
  39.  
  40. #End Region
  41.  
  42. #Region " Usage Examples "
  43.  
  44. #End Region
  45.  
  46. #Region " Option Statements "
  47.  
  48. Option Strict On
  49. Option Explicit On
  50. Option Infer Off
  51.  
  52. #End Region
  53.  
  54. #Region " Imports "
  55.  
  56. Imports System.ComponentModel
  57. Imports System.Windows.Forms
  58.  
  59. ' Imports Elektro.Core.DateAndTime.Enums
  60. ' Imports Elektro.Core.DateAndTime.Types.EventArgs
  61. ' Imports Elektro.Core.Types
  62.  
  63. #End Region
  64.  
  65. #Region " Time Measurer "
  66.  
  67. Namespace DateAndTime.Types
  68.  
  69.    ''' ----------------------------------------------------------------------------------------------------
  70.    ''' <summary>
  71.    ''' Measures the elapsed and/or remaining time of a time interval.
  72.    ''' The time measurer can be used as a chronometer or a countdown.
  73.    ''' </summary>
  74.    ''' ----------------------------------------------------------------------------------------------------
  75.    <ImmutableObject(False)>
  76.    Public NotInheritable Class TimeMeasurer :  Implements IDisposable ': Inherits AestheticObject
  77.  
  78. #Region " Private Fields "
  79.  
  80.        ''' ----------------------------------------------------------------------------------------------------
  81.        ''' <summary>
  82.        ''' An <see cref="Stopwatch"/> instance to retrieve the elapsed time. (a chronometer)
  83.        ''' </summary>
  84.        ''' ----------------------------------------------------------------------------------------------------
  85.        Private timeElapsed As Stopwatch
  86.  
  87.        ''' ----------------------------------------------------------------------------------------------------
  88.        ''' <summary>
  89.        ''' A <see cref="TimeSpan"/> instance to retrieve the remaining time. (a countdown)
  90.        ''' </summary>
  91.        ''' ----------------------------------------------------------------------------------------------------
  92.        Private timeRemaining As TimeSpan
  93.  
  94.        ''' ----------------------------------------------------------------------------------------------------
  95.        ''' <summary>
  96.        ''' A <see cref="Timer"/> instance that updates the elapsed and remaining time,
  97.        ''' and also raise <see cref="TimeMeasurer"/> events.
  98.        ''' </summary>
  99.        ''' ----------------------------------------------------------------------------------------------------
  100.        Private WithEvents measureTimer As Timer
  101.  
  102.        ''' ----------------------------------------------------------------------------------------------------
  103.        ''' <summary>
  104.        ''' Flag that indicates wheter this <see cref="TimeMeasurer"/> instance has finished to measure time interval.
  105.        ''' </summary>
  106.        ''' ----------------------------------------------------------------------------------------------------
  107.        Private isFinished As Boolean
  108.  
  109. #End Region
  110.  
  111. #Region " Properties "
  112.  
  113.        ''' ----------------------------------------------------------------------------------------------------
  114.        ''' <summary>
  115.        ''' Gets the maximum time that the <see cref="TimeMeasurer"/> can measure, in milliseconds.
  116.        ''' </summary>
  117.        ''' ----------------------------------------------------------------------------------------------------
  118.        ''' <value>
  119.        ''' The maximum time that the <see cref="TimeMeasurer"/> can measure, in milliseconds.
  120.        ''' </value>
  121.        ''' ----------------------------------------------------------------------------------------------------
  122.        Public Shared ReadOnly Property MaxValue As Double
  123.            <DebuggerStepThrough>
  124.            Get
  125.                Return (TimeSpan.MaxValue.TotalMilliseconds - 1001.0R)
  126.            End Get
  127.        End Property
  128.  
  129.        ''' ----------------------------------------------------------------------------------------------------
  130.        ''' <summary>
  131.        ''' Gets the current state of this <see cref="TimeMeasurer"/> instance.
  132.        ''' </summary>
  133.        ''' ----------------------------------------------------------------------------------------------------
  134.        ''' <value>
  135.        ''' The current state of this <see cref="TimeMeasurer"/> instance.
  136.        ''' </value>
  137.        ''' ----------------------------------------------------------------------------------------------------
  138.        Public ReadOnly Property State As TimeMeasurerState
  139.            <DebuggerStepThrough>
  140.            Get
  141.                If (Me.timeElapsed Is Nothing) OrElse (Me.isFinished) Then
  142.                    Return TimeMeasurerState.Disabled
  143.  
  144.                ElseIf Not Me.timeElapsed.IsRunning Then
  145.                    Return TimeMeasurerState.Paused
  146.  
  147.                Else
  148.                    Return TimeMeasurerState.Enabled
  149.  
  150.                End If
  151.            End Get
  152.        End Property
  153.  
  154.        ''' ----------------------------------------------------------------------------------------------------
  155.        ''' <summary>
  156.        ''' Gets or sets the update interval.
  157.        ''' Maximum value is 1000 (1 second).
  158.        ''' </summary>
  159.        ''' ----------------------------------------------------------------------------------------------------
  160.        ''' <value>
  161.        ''' The update interval.
  162.        ''' </value>
  163.        ''' ----------------------------------------------------------------------------------------------------
  164.        ''' <exception cref="ArgumentException">
  165.        ''' A value smaller than 1000 is required.;value
  166.        ''' </exception>
  167.        Public Property UpdateInterval As Integer
  168.            <DebuggerStepThrough>
  169.            Get
  170.                Return Me.updateIntervalB
  171.            End Get
  172.            <DebuggerStepThrough>
  173.            Set(ByVal value As Integer)
  174.                If (value > 1000) Then
  175.                    Throw New ArgumentException(message:="A value smaller than 1000 is required.", paramName:="value")
  176.                Else
  177.                    Me.updateIntervalB = value
  178.                    If (Me.measureTimer IsNot Nothing) Then
  179.                        Me.measureTimer.Interval = value
  180.                    End If
  181.                End If
  182.            End Set
  183.        End Property
  184.        ''' ----------------------------------------------------------------------------------------------------
  185.        ''' <summary>
  186.        ''' ( Backing field )
  187.        ''' The update interval.
  188.        ''' </summary>
  189.        ''' ----------------------------------------------------------------------------------------------------
  190.        Private updateIntervalB As Integer = 100I
  191.  
  192. #End Region
  193.  
  194. #Region " Events "
  195.  
  196.        ''' ----------------------------------------------------------------------------------------------------
  197.        ''' <summary>
  198.        ''' Occurs when the elapsed/remaining time updates.
  199.        ''' </summary>
  200.        ''' ----------------------------------------------------------------------------------------------------
  201.        Public Event TimeUpdated(ByVal sender As Object, ByVal e As TimeMeasurerUpdatedEventArgs)
  202.  
  203. #End Region
  204.  
  205. #Region " Constructors "
  206.  
  207.        ''' ----------------------------------------------------------------------------------------------------
  208.        ''' <summary>
  209.        ''' Initializes a new instance of the <see cref="TimeMeasurer"/> class.
  210.        ''' </summary>
  211.        ''' ----------------------------------------------------------------------------------------------------
  212.        <DebuggerStepThrough>
  213.        Public Sub New()
  214.        End Sub
  215.  
  216. #End Region
  217.  
  218. #Region " Public Methods "
  219.  
  220.        ''' ----------------------------------------------------------------------------------------------------
  221.        ''' <summary>
  222.        ''' Starts the time interval measurement.
  223.        ''' </summary>
  224.        ''' ----------------------------------------------------------------------------------------------------
  225.        ''' <param name="milliseconds">
  226.        ''' The time interval to measure, in milliseconds.
  227.        ''' </param>
  228.        ''' ----------------------------------------------------------------------------------------------------
  229.        ''' <exception cref="ArgumentOutOfRangeException">
  230.        ''' milliseconds;A value smaller than <see cref="TimeMeasurer.MaxValue"/> is required.
  231.        ''' </exception>
  232.        '''
  233.        ''' <exception cref="ArgumentOutOfRangeException">
  234.        ''' milliseconds;A value greater than 0 is required.
  235.        ''' </exception>
  236.        ''' ----------------------------------------------------------------------------------------------------
  237.        <DebuggerStepThrough>
  238.        Public Sub Start(ByVal milliseconds As Double)
  239.  
  240.            If (milliseconds > TimeMeasurer.MaxValue) Then
  241.                Throw New ArgumentOutOfRangeException(paramName:="milliseconds",
  242.                                                      message:=String.Format("A value smaller than {0} is required.", TimeMeasurer.MaxValue))
  243.  
  244.            ElseIf (milliseconds <= 0) Then
  245.                Throw New ArgumentOutOfRangeException(paramName:="milliseconds",
  246.                                                      message:="A value greater than 0 is required.")
  247.  
  248.            Else
  249.                Me.timeElapsed = New Stopwatch
  250.                Me.timeRemaining = TimeSpan.FromMilliseconds(milliseconds)
  251.                Me.measureTimer = New Timer With
  252.                   {
  253.                     .Tag = milliseconds,
  254.                     .Interval = Me.updateIntervalB,
  255.                     .Enabled = True
  256.                   }
  257.  
  258.                Me.isFinished = False
  259.                Me.timeElapsed.Start()
  260.                Me.measureTimer.Start()
  261.  
  262.            End If
  263.  
  264.        End Sub
  265.  
  266.        ''' ----------------------------------------------------------------------------------------------------
  267.        ''' <summary>
  268.        ''' Starts a time interval measurement given a difference between two dates.
  269.        ''' </summary>
  270.        ''' ----------------------------------------------------------------------------------------------------
  271.        ''' <param name="startDate">
  272.        ''' The starting date.
  273.        ''' </param>
  274.        '''
  275.        ''' <param name="endDate">
  276.        ''' The ending date.
  277.        ''' </param>
  278.        ''' ----------------------------------------------------------------------------------------------------
  279.        <DebuggerStepThrough>
  280.        Public Sub Start(ByVal startDate As Date,
  281.                         ByVal endDate As Date)
  282.  
  283.            Me.Start(endDate.Subtract(startDate).TotalMilliseconds)
  284.  
  285.        End Sub
  286.  
  287.        ''' ----------------------------------------------------------------------------------------------------
  288.        ''' <summary>
  289.        ''' Starts a time interval measurement given a <see cref="TimeSpan"/>.
  290.        ''' </summary>
  291.        ''' ----------------------------------------------------------------------------------------------------
  292.        ''' <param name="time">
  293.        ''' A <see cref="TimeSpan"/> instance that contains the time interval.
  294.        ''' </param>
  295.        ''' ----------------------------------------------------------------------------------------------------
  296.        <DebuggerStepThrough>
  297.        Public Sub Start(ByVal time As TimeSpan)
  298.  
  299.            Me.Start(time.TotalMilliseconds)
  300.  
  301.        End Sub
  302.  
  303.        ''' ----------------------------------------------------------------------------------------------------
  304.        ''' <summary>
  305.        ''' Pauses the time interval measurement.
  306.        ''' </summary>
  307.        ''' ----------------------------------------------------------------------------------------------------
  308.        ''' <exception cref="Exception">
  309.        ''' TimeMeasurer is not running.
  310.        ''' </exception>
  311.        ''' ----------------------------------------------------------------------------------------------------
  312.        <DebuggerStepThrough>
  313.        Public Sub Pause()
  314.  
  315.            If (Me.State <> TimeMeasurerState.Enabled) Then
  316.                Throw New Exception("TimeMeasurer is not running.")
  317.  
  318.            Else
  319.                Me.measureTimer.Stop()
  320.                Me.timeElapsed.Stop()
  321.  
  322.            End If
  323.  
  324.        End Sub
  325.  
  326.        ''' ----------------------------------------------------------------------------------------------------
  327.        ''' <summary>
  328.        ''' Resumes the time interval measurement.
  329.        ''' </summary>
  330.        ''' ----------------------------------------------------------------------------------------------------
  331.        ''' <exception cref="Exception">
  332.        ''' TimeMeasurer is not paused.
  333.        ''' </exception>
  334.        ''' ----------------------------------------------------------------------------------------------------
  335.        <DebuggerStepThrough>
  336.        Public Sub [Resume]()
  337.  
  338.            If (Me.State <> TimeMeasurerState.Paused) Then
  339.                Throw New Exception("TimeMeasurer is not paused.")
  340.  
  341.            Else
  342.                Me.measureTimer.Start()
  343.                Me.timeElapsed.Start()
  344.  
  345.            End If
  346.  
  347.        End Sub
  348.  
  349.        ''' <summary>
  350.        ''' Stops the time interval measurement.
  351.        ''' </summary>
  352.        ''' ----------------------------------------------------------------------------------------------------
  353.        ''' <exception cref="Exception">
  354.        ''' TimeMeasurer is not running.
  355.        ''' </exception>
  356.        ''' ----------------------------------------------------------------------------------------------------
  357.        <DebuggerStepThrough>
  358.        Public Sub [Stop]()
  359.  
  360.            If (Me.State = TimeMeasurerState.Disabled) Then
  361.                Throw New Exception("TimeMeasurer is not running.")
  362.  
  363.            Else
  364.                Me.Reset()
  365.                Me.isFinished = True
  366.  
  367.                Me.measureTimer.Stop()
  368.                Me.timeElapsed.Stop()
  369.  
  370.            End If
  371.  
  372.        End Sub
  373.  
  374. #End Region
  375.  
  376. #Region " Private Methods "
  377.  
  378.        ''' ----------------------------------------------------------------------------------------------------
  379.        ''' <summary>
  380.        ''' Stops Time intervals and resets the elapsed and remaining time to zero.
  381.        ''' </summary>
  382.        ''' ----------------------------------------------------------------------------------------------------
  383.        <DebuggerStepThrough>
  384.        Private Sub Reset()
  385.  
  386.            Me.measureTimer.Stop()
  387.            Me.timeElapsed.Reset()
  388.  
  389.        End Sub
  390.  
  391. #End Region
  392.  
  393. #Region " Event Handlers "
  394.  
  395.        ''' ----------------------------------------------------------------------------------------------------
  396.        ''' <summary>
  397.        ''' Handles the <see cref="Timer.Tick"/> event of the <see cref="MeasureTimer"/> timer.
  398.        ''' </summary>
  399.        ''' ----------------------------------------------------------------------------------------------------
  400.        ''' <param name="sender">
  401.        ''' The source of the event.
  402.        ''' </param>
  403.        '''
  404.        ''' <param name="e">
  405.        ''' The <see cref="EventArgs"/> instance containing the event data.
  406.        ''' </param>
  407.        ''' ----------------------------------------------------------------------------------------------------
  408.        <DebuggerStepThrough>
  409.        Private Sub MeasureTimer_Tick(ByVal sender As Object, ByVal e As Global.System.EventArgs) _
  410.        Handles measureTimer.Tick
  411.  
  412.            Dim timeDiff As TimeSpan = (Me.timeRemaining - Me.timeElapsed.Elapsed)
  413.  
  414.            ' If finished...
  415.            If (timeDiff.TotalMilliseconds <= 0.0R) _
  416.            OrElse (Me.timeElapsed.ElapsedMilliseconds > DirectCast(Me.measureTimer.Tag, Double)) Then
  417.  
  418.                Me.Reset()
  419.                Me.isFinished = True
  420.  
  421.                If (Me.TimeUpdatedEvent IsNot Nothing) Then
  422.                    Dim goal As TimeSpan = TimeSpan.FromMilliseconds(DirectCast(Me.measureTimer.Tag, Double))
  423.                    RaiseEvent TimeUpdated(sender, New TimeMeasurerUpdatedEventArgs(goal, TimeSpan.FromMilliseconds(0.0R), goal))
  424.                End If
  425.  
  426.            Else ' If not finished...
  427.                If (Me.TimeUpdatedEvent IsNot Nothing) Then
  428.                    RaiseEvent TimeUpdated(sender, New TimeMeasurerUpdatedEventArgs(Me.timeElapsed.Elapsed,
  429.                                                                                    timeDiff,
  430.                                                                                    TimeSpan.FromMilliseconds(DirectCast(Me.measureTimer.Tag, Double))))
  431.                End If
  432.  
  433.            End If
  434.  
  435.        End Sub
  436.  
  437. #End Region
  438.  
  439. #Region " IDisposable Implementation "
  440.  
  441.        ''' ----------------------------------------------------------------------------------------------------
  442.        ''' <summary>
  443.        ''' Flag to detect redundant calls when disposing.
  444.        ''' </summary>
  445.        ''' ----------------------------------------------------------------------------------------------------
  446.        Private isDisposed As Boolean = False
  447.  
  448.        ''' ----------------------------------------------------------------------------------------------------
  449.        ''' <summary>
  450.        ''' Releases all the resources used by this instance.
  451.        ''' </summary>
  452.        ''' ----------------------------------------------------------------------------------------------------
  453.        <DebuggerStepThrough>
  454.        Public Sub Dispose() Implements IDisposable.Dispose
  455.            Me.Dispose(isDisposing:=True)
  456.            GC.SuppressFinalize(obj:=Me)
  457.        End Sub
  458.  
  459.        ''' ----------------------------------------------------------------------------------------------------
  460.        ''' <summary>
  461.        ''' Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  462.        ''' Releases unmanaged and, optionally, managed resources.
  463.        ''' </summary>
  464.        ''' ----------------------------------------------------------------------------------------------------
  465.        ''' <param name="isDisposing">
  466.        ''' <see langword="True"/>  to release both managed and unmanaged resources;
  467.        ''' <see langword="False"/> to release only unmanaged resources.
  468.        ''' </param>
  469.        ''' ----------------------------------------------------------------------------------------------------
  470.        <DebuggerStepThrough>
  471.        Private Sub Dispose(ByVal isDisposing As Boolean)
  472.  
  473.            If (Not Me.isDisposed) AndAlso (isDisposing) Then
  474.  
  475.                If (Me.measureTimer IsNot Nothing) Then
  476.                    Me.measureTimer.Stop()
  477.                    Me.measureTimer.Dispose()
  478.                    Me.measureTimer = Nothing
  479.                End If
  480.  
  481.                If (Me.TimeUpdatedEvent IsNot Nothing) Then
  482.                    RemoveHandler Me.TimeUpdated, Me.TimeUpdatedEvent
  483.                End If
  484.  
  485.            End If
  486.  
  487.            Me.isDisposed = True
  488.  
  489.        End Sub
  490.  
  491. #End Region
  492.  
  493.    End Class
  494.  
  495. End Namespace
  496.  
  497. #End Region

+

Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 12-December-2015
  4. ' ***********************************************************************
  5.  
  6. #Region " Option Statements "
  7.  
  8. Option Strict On
  9. Option Explicit On
  10. Option Infer Off
  11.  
  12. #End Region
  13.  
  14. #Region " TimeMeasurer State "
  15.  
  16. Namespace DateAndTime.Enums
  17.  
  18.    ''' ----------------------------------------------------------------------------------------------------
  19.    ''' <summary>
  20.    ''' Specifies the current state of a <see cref="Types.TimeMeasurer"/> instance.
  21.    ''' </summary>
  22.    ''' ----------------------------------------------------------------------------------------------------
  23.    Public Enum TimeMeasurerState As Integer
  24.  
  25.        ''' <summary>
  26.        ''' The <see cref="Types.TimeMeasurer"/> is running.
  27.        ''' </summary>
  28.        Enabled = &H0I
  29.  
  30.        ''' <summary>
  31.        ''' The <see cref="Types.TimeMeasurer"/> is paused.
  32.        ''' </summary>
  33.        Paused = &H1I
  34.  
  35.        ''' <summary>
  36.        ''' The <see cref="Types.TimeMeasurer"/> is fully stopped, it cannot be resumed.
  37.        ''' </summary>
  38.        Disabled = &H2I
  39.  
  40.    End Enum
  41.  
  42. End Namespace
  43.  
  44. #End Region

+

Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 12-December-2015
  4. ' ***********************************************************************
  5.  
  6. #Region " Public Members Summary "
  7.  
  8. #Region " Constructors "
  9.  
  10. ' New(TimeSpan, TimeSpan, TimeSpan)
  11.  
  12. #End Region
  13.  
  14. #Region " Properties "
  15.  
  16. ' Elapsed As TimeSpan
  17. ' Remaining As TimeSpan
  18. ' Goal As TimeSpan
  19.  
  20. #End Region
  21.  
  22. #End Region
  23.  
  24. #Region " Option Statements "
  25.  
  26. Option Strict On
  27. Option Explicit On
  28. Option Infer Off
  29.  
  30. #End Region
  31.  
  32. #Region " Imports "
  33.  
  34. Imports System.ComponentModel
  35. ' Imports Elektro.Core.Types
  36.  
  37. #End Region
  38.  
  39. #Region " TimeMeasurerUpdated EventArgs "
  40.  
  41. Namespace DateAndTime.Types.EventArgs
  42.  
  43.    ''' ----------------------------------------------------------------------------------------------------
  44.    ''' <summary>
  45.    ''' Contains the event-data of a <see cref="TimeMeasurer"/> event.
  46.    ''' </summary>
  47.    ''' ----------------------------------------------------------------------------------------------------
  48.    <ImmutableObject(True)>
  49.    Public NotInheritable Class TimeMeasurerUpdatedEventArgs ' : Inherits AestheticEventArgs
  50.  
  51. #Region " Properties "
  52.  
  53.        ''' ----------------------------------------------------------------------------------------------------
  54.        ''' <summary>
  55.        ''' Gets the elapsed time.
  56.        ''' </summary>
  57.        ''' ----------------------------------------------------------------------------------------------------
  58.        ''' <value>
  59.        ''' The elapsed time.
  60.        ''' </value>
  61.        ''' ----------------------------------------------------------------------------------------------------
  62.        Public ReadOnly Property Elapsed As TimeSpan
  63.            <DebuggerStepThrough>
  64.            Get
  65.                Return Me.elapsedB
  66.            End Get
  67.        End Property
  68.        ''' ----------------------------------------------------------------------------------------------------
  69.        ''' <summary>
  70.        ''' ( Baking Field )
  71.        ''' The elapsed time.
  72.        ''' </summary>
  73.        ''' ----------------------------------------------------------------------------------------------------
  74.        Private ReadOnly elapsedB As TimeSpan
  75.  
  76.        ''' ----------------------------------------------------------------------------------------------------
  77.        ''' <summary>
  78.        ''' Gets the remaining time.
  79.        ''' </summary>
  80.        ''' ----------------------------------------------------------------------------------------------------
  81.        ''' <value>
  82.        ''' The remaining time.
  83.        ''' </value>
  84.        ''' ----------------------------------------------------------------------------------------------------
  85.        Public ReadOnly Property Remaining As TimeSpan
  86.            <DebuggerStepThrough>
  87.            Get
  88.                Return Me.remainingB
  89.            End Get
  90.        End Property
  91.        ''' ----------------------------------------------------------------------------------------------------
  92.        ''' <summary>
  93.        ''' ( Baking Field )
  94.        ''' The remaining time.
  95.        ''' </summary>
  96.        ''' ----------------------------------------------------------------------------------------------------
  97.        Private ReadOnly remainingB As TimeSpan
  98.  
  99.        ''' ----------------------------------------------------------------------------------------------------
  100.        ''' <summary>
  101.        ''' Gets the goal time.
  102.        ''' </summary>
  103.        ''' ----------------------------------------------------------------------------------------------------
  104.        ''' <value>
  105.        ''' The goal time.
  106.        ''' </value>
  107.        ''' ----------------------------------------------------------------------------------------------------
  108.        Public ReadOnly Property Goal As TimeSpan
  109.            <DebuggerStepThrough>
  110.            Get
  111.                Return Me.goalB
  112.            End Get
  113.        End Property
  114.        ''' ----------------------------------------------------------------------------------------------------
  115.        ''' <summary>
  116.        ''' ( Baking Field )
  117.        ''' The goal time.
  118.        ''' </summary>
  119.        ''' ----------------------------------------------------------------------------------------------------
  120.        Private ReadOnly goalB As TimeSpan
  121.  
  122. #End Region
  123.  
  124. #Region " Constructors "
  125.  
  126.        ''' ----------------------------------------------------------------------------------------------------
  127.        ''' <summary>
  128.        ''' Prevents a default instance of the <see cref="TimeMeasurerUpdatedEventArgs"/> class from being created.
  129.        ''' </summary>
  130.        ''' ----------------------------------------------------------------------------------------------------
  131.        <DebuggerNonUserCode>
  132.        Private Sub New()
  133.        End Sub
  134.  
  135.        ''' ----------------------------------------------------------------------------------------------------
  136.        ''' <summary>
  137.        ''' Initializes a new instance of the <see cref="TimeMeasurerUpdatedEventArgs"/> class.
  138.        ''' </summary>
  139.        ''' ----------------------------------------------------------------------------------------------------
  140.        ''' <param name="elapsed">
  141.        ''' The elapsed time.
  142.        ''' </param>
  143.        '''
  144.        ''' <param name="remaining">
  145.        ''' The remaining time.
  146.        ''' </param>
  147.        '''
  148.        ''' <param name="goal">
  149.        ''' The goal time.
  150.        ''' </param>
  151.        ''' ----------------------------------------------------------------------------------------------------
  152.        <DebuggerStepThrough>
  153.        Public Sub New(ByVal elapsed As TimeSpan,
  154.                       ByVal remaining As TimeSpan,
  155.                       ByVal goal As TimeSpan)
  156.  
  157.            Me.elapsedB = elapsed
  158.            Me.remainingB = remaining
  159.            Me.goalB = goal
  160.  
  161.        End Sub
  162.  
  163. #End Region
  164.  
  165.    End Class
  166.  
  167. End Namespace
  168.  
  169. #End Region

Tendrías que editar las classes de arribas un poquito para eliminarle el código sobrante, es decir los espacios de nombres y los imports de la librería y creo que nada más.

El modo de empleo para implementarlo a modo de cuenta atrás, sería más o menos el siguiente:

Código
  1. Public Class Form1 : Inherits Form
  2.  
  3.    ''' ----------------------------------------------------------------------------------------------------
  4.    ''' <summary>
  5.    ''' The <see cref="TimeMeasurer"/> instance that measure time intervals.
  6.    ''' </summary>
  7.    ''' ----------------------------------------------------------------------------------------------------
  8.    Private WithEvents countdown As New TimeMeasurer With {.UpdateInterval = 100}
  9.  
  10.    ' Label used to display the remaining time.
  11.    Private lblCountdown As Label
  12.  
  13.    Private Sub Shown() Handles MyBase.Shown
  14.        Me.lblCountdown = Me.Label2
  15.        Me.countdown.Start(TimeSpan.FromMinutes(1.0R))
  16.    End Sub
  17.  
  18.    ''' ----------------------------------------------------------------------------------------------------
  19.    ''' <summary>
  20.    ''' Handles the <see cref="TimeMeasurer.TimeUpdated"/> event of the countdown instance.
  21.    ''' </summary>
  22.    ''' ----------------------------------------------------------------------------------------------------
  23.    ''' <param name="sender">
  24.    ''' The source of the event.
  25.    ''' </param>
  26.    '''
  27.    ''' <param name="e">
  28.    ''' The <see cref="TimeMeasurerUpdatedEventArgs"/> instance containing the event data.
  29.    ''' </param>
  30.    ''' ----------------------------------------------------------------------------------------------------
  31.    Private Sub Countdown_TimeUpdated(ByVal sender As Object, ByVal e As TimeMeasurerUpdatedEventArgs) _
  32.    Handles countdown.TimeUpdated
  33.  
  34.        ' Measure H:M:S:MS
  35.        Me.lblCountdown.Text = String.Format("{0:00}:{1:00}:{2:00}:{3:000}",
  36.                                             e.Remaining.Hours, e.Remaining.Minutes, e.Remaining.Seconds, e.Remaining.Milliseconds)
  37.  
  38.        If (e.Elapsed.Subtract(e.Remaining) <= e.Goal) Then
  39.            Me.lblCountdown.Text = "Countdown Done!"
  40.        End If
  41.  
  42.    End Sub
  43.  
  44. End Class

Si tienes cualquier duda al respecto del código, tan solo pregunta.

Saludos!.
« Última modificación: 17 Enero 2017, 09:21 am por Eleкtro » En línea


Piyulta

Desconectado Desconectado

Mensajes: 4


Ver Perfil
Re: Poner un contador en visual basic 2013 y ver la ip
« Respuesta #5 en: 18 Enero 2017, 03:09 am »

Gracias!! la ip ya la pude poner jaja, ahora cuando inicia el programa la ip sale perfecto pero..

lo del tiempo aun no lo soluciono, aparte que estuve pensando y es muy fácil de modificar
por el usuario, pero se me ocurrió una idea que podría ser mejo, poner una fecha de caducidad:

EJ: Este programa vencerá el 19/1/17 11:05pm

eso creo que puede ser mas fácil, considerando que al abrir mi programa el usuario solo dispondrá de 48 horas (2 días) para usarlo, alguien me puede ayudar con eso? si necesito agregar alguna referencia? no he podido encontrar un código en google ni tampoco información si debo agregar una referencia, lo que quiero es que esa fecha se muestre en un label

Muchas gracias!!
En línea

engel lex
Moderador Global
***
Desconectado Desconectado

Mensajes: 15.514



Ver Perfil
Re: Poner un contador en visual basic 2013 y ver la ip
« Respuesta #6 en: 18 Enero 2017, 03:13 am »

si no sabes lo básico de programación, no te servirá de mucho la seguridad de tu programa, si alguien con un mínimo conocimiento lo agarra lo explotará XD

tienes que guardar la hora en algún lugar, ya sea un archivo, ya sea un registro, ya sea internet... pero el programa tiene que saber cuando se instaló...
En línea

El problema con la sociedad actualmente radica en que todos creen que tienen el derecho de tener una opinión, y que esa opinión sea validada por todos, cuando lo correcto es que todos tengan derecho a una opinión, siempre y cuando esa opinión pueda ser ignorada, cuestionada, e incluso ser sujeta a burla, particularmente cuando no tiene sentido alguno.
Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines