Foro de elhacker.net

Programación => .NET (C#, VB.NET, ASP) => Mensaje iniciado por: _CrisiS_ en 6 Diciembre 2017, 00:32 am



Título: Control de Hora en Form
Publicado por: _CrisiS_ en 6 Diciembre 2017, 00:32 am
Hola soy algo nuevo programando en net. y tengo la necesidad de agregar un "textboxt" o un "control" para la hora "probe el DateTimePicker, pero solo me agrega el calendario para la fecha yo busco algo para seleccionar la hora" ,  con flechas al costado aumentar o disminuir la hora como en la foto que adjunto:
(https://www.lawebdelprogramador.com/usr/325000/325494/5a262390301df-fotovbnet.jpg)
Como veran en la imagen, pude lograrlo con este codigo pero con ese codigo solo me figura el control al momento de correr la aplicacion, yo lo quiero ver desde la ventana de diseño para poder cambiar su ubicacion y no salir en un formulario en una ubicacion estandar
Código:
Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Drawing
Imports System.Text
Imports System.Windows.Forms
 
 
Public Class PRUEBA
 
    Public Sub New()
        InitializeTimePicker()
 
    End Sub
    Private timePicker As DateTimePicker
 
 
    Private Sub InitializeTimePicker()
        timePicker = New DateTimePicker()
        timePicker.Format = DateTimePickerFormat.Time
        timePicker.ShowUpDown = True
        timePicker.Location = New Point(10, 10)
        timePicker.Width = 100
        Controls.Add(timePicker)
 
    End Sub
 
    <STAThread()> _
    Shared Sub Main()
        Application.EnableVisualStyles()
        Application.Run(New Form1())
 
    End Sub
End Class


Título: Re: Control de Hora en Form
Publicado por: Eleкtro en 6 Diciembre 2017, 10:42 am
Como veran en la imagen, pude lograrlo con este codigo pero con ese codigo solo me figura el control al momento de correr la aplicacion, yo lo quiero ver desde la ventana de diseño para poder cambiar su ubicacion y no salir en un formulario en una ubicacion estandar

En el código que has mostrado, lo que estás haciendo es añadir un control al Form en tiempo de ejecución, evidentemente no lo puedes manipular en tiempo de diseño.

Para hacer lo que quieres, necesitas crear un control de usuario desde cero (heredando la clase UserControl), o bien extender un control por defecto. Esto último se hace declarando una clase que herede del control que quieres modificar/extender, en este caso DateTimePicker. Tu código adaptado quedaría más o menos de la siguiente manera:

Código
  1. Imports System
  2. Imports System.ComponentModel
  3. Imports System.Diagnostics
  4. Imports System.Runtime.InteropServices
  5. Imports System.Windows.Forms
  6.  
  7. <ClassInterface(ClassInterfaceType.AutoDispatch)>
  8. <ComVisible(True)>
  9. <DefaultBindingProperty("Value")>
  10. <DefaultEvent("ValueChanged")>
  11. <DefaultProperty("Value")>
  12. Public Class TimePicker : Inherits DateTimePicker
  13.  
  14.    <Bindable(True)>
  15.    <Browsable(True)>
  16.    <EditorBrowsable(EditorBrowsableState.Always)>
  17.    <RefreshProperties(RefreshProperties.All)>
  18.    Public Overloads Property Value As TimeSpan
  19.        Get
  20.            Return MyBase.Value.TimeOfDay
  21.        End Get
  22.        Set(value As TimeSpan)
  23.            MyBase.Value = DateTime.Today + value
  24.        End Set
  25.    End Property
  26.  
  27.    Public Sub New()
  28.        Me.Format = DateTimePickerFormat.Time
  29.        Me.ShowUpDown = True
  30.        Me.Value = TimeSpan.Zero ' Me.Value = MyBase.Value.TimeOfDay
  31.        ' Me.Width = 100
  32.    End Sub
  33.  
  34. End Class

Cuando hayas compilado esa clase por primera vez (y solo despues de haberla compilado) te aparecerá un control con nombre "TimePicker" arriba del todo junto a los demás controles que puedes arrastrar al Form.



Si quieres un control más personalizado, esto de aquí abajo lo acabo de hacer hoy (no lo he testeado en profundidad)...

Es un código muy simple, este código es practicamente lo mismo que el anterior que mostré, solo que denota una mejor representación del tiempo ya que no se puede representar una fecha en este control, tiene las propiedades de calendario eliminadas, y el formato personalizado de representación de fecha y hora (propiedad CustomFormat) está "bloqueado" a formato de 24 horas.

ElektroTimePicker.vb
Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 06-December-2017
  4. ' ***********************************************************************
  5.  
  6. #Region " Public Members Summary "
  7.  
  8. #Region " Constructors "
  9.  
  10. ' New()
  11.  
  12. #End Region
  13.  
  14. #Region " Properties "
  15.  
  16. ' Value As TimeSpan
  17.  
  18. #End Region
  19.  
  20. #End Region
  21.  
  22. #Region " Option Statements "
  23.  
  24. Option Strict On
  25. Option Explicit On
  26. Option Infer Off
  27.  
  28. #End Region
  29.  
  30. #Region " Imports "
  31.  
  32. Imports System
  33. Imports System.ComponentModel
  34. Imports System.Diagnostics
  35. Imports System.Drawing
  36. Imports System.Runtime.InteropServices
  37. Imports System.Windows.Forms
  38. Imports System.Windows.Forms.Design
  39.  
  40. ' Imports ElektroKit.UserControls.Designers
  41.  
  42. #End Region
  43.  
  44. #Region " ElektroTimePicker "
  45.  
  46. ' Namespace ElektroKit.UserControls
  47.  
  48.    ''' ----------------------------------------------------------------------------------------------------
  49.    ''' <summary>
  50.    ''' Represents a control that allows the user to select an hour,
  51.    ''' and to display the time with a specified format.
  52.    ''' </summary>
  53.    ''' ----------------------------------------------------------------------------------------------------
  54.    <DisplayName("ElektroTimePicker")>
  55.    <Description("A extended DateTimePicker control that only displays the time.")>
  56.    <DesignTimeVisible(True)>
  57.    <DesignerCategory("UserControl")>
  58.    <ToolboxBitmap(GetType(DateTimePicker), "DateTimePicker.bmp")>
  59.    <ToolboxItemFilter("System.Windows.Forms", ToolboxItemFilterType.Require)>
  60.    <ClassInterface(ClassInterfaceType.AutoDispatch)>
  61.    <ComVisible(True)>
  62.    <DefaultBindingProperty("Value")>
  63.    <DefaultEvent("ValueChanged")>
  64.    <DefaultProperty("Value")>
  65.    <Designer(GetType(ElektroTimePickerDesigner))>
  66.    Public Class ElektroTimePicker : Inherits DateTimePicker
  67.  
  68. #Region " Properties "
  69.  
  70.        ''' ----------------------------------------------------------------------------------------------------
  71.        ''' <summary>
  72.        ''' Gets or sets the time value assigned to the control.
  73.        ''' </summary>
  74.        ''' ----------------------------------------------------------------------------------------------------
  75.        ''' <value>
  76.        ''' The time value assigned to the control.
  77.        ''' </value>
  78.        ''' ----------------------------------------------------------------------------------------------------
  79.        <Bindable(True)>
  80.        <Browsable(True)>
  81.        <EditorBrowsable(EditorBrowsableState.Always)>
  82.        <RefreshProperties(RefreshProperties.All)>
  83.        Public Overloads Property Value As TimeSpan
  84.            Get
  85.                Return MyBase.Value.TimeOfDay
  86.            End Get
  87.            Set(value As TimeSpan)
  88.                MyBase.Value = DateTime.Today + value
  89.            End Set
  90.        End Property
  91.  
  92. #End Region
  93.  
  94. #Region " Constructors "
  95.  
  96.        ''' ----------------------------------------------------------------------------------------------------
  97.        ''' <summary>
  98.        ''' Initializes a new instance of the <see cref="ElektroTimePicker"/> class.
  99.        ''' </summary>
  100.        ''' ----------------------------------------------------------------------------------------------------
  101.        Public Sub New()
  102.            Me.CustomFormat = "HH:mm:ss" ' 24-hour format.
  103.            Me.Format = DateTimePickerFormat.Custom
  104.            Me.ShowUpDown = True
  105.            Me.Value = TimeSpan.Zero
  106.            ' Me.Value = MyBase.Value.TimeOfDay
  107.  
  108.            Me.Width = Me.MinimumSize.Width
  109.            Me.AdjustControlWidth()
  110.        End Sub
  111.  
  112. #End Region
  113.  
  114. #Region " Event Invocators "
  115.  
  116.        ''' ----------------------------------------------------------------------------------------------------
  117.        ''' <summary>
  118.        ''' Raises the <see cref="ElektroTimePicker.FontChanged"/> event.
  119.        ''' </summary>
  120.        ''' ----------------------------------------------------------------------------------------------------
  121.        ''' <param name="e">
  122.        ''' An <see cref="EventArgs"/> that contains the event data.
  123.        ''' </param>
  124.        ''' ----------------------------------------------------------------------------------------------------
  125.        Protected Overrides Sub OnFontChanged(ByVal e As EventArgs)
  126.            If (Me.DesignMode) Then
  127.                Me.AdjustControlWidth()
  128.            End If
  129.  
  130.            MyBase.OnFontChanged(e)
  131.        End Sub
  132.  
  133. #End Region
  134.  
  135. #Region " Overridable Methods "
  136.  
  137.        ''' ----------------------------------------------------------------------------------------------------
  138.        ''' <summary>
  139.        ''' Grows the control width to fit the text displayed.
  140.        ''' </summary>
  141.        ''' ----------------------------------------------------------------------------------------------------
  142.        Protected Overridable Sub AdjustControlWidth()
  143.            Using g As Graphics = Me.CreateGraphics()
  144.                Dim textSize As SizeF = g.MeasureString(Me.Text, Me.Font)
  145.  
  146.                If (textSize.Width > Me.Width) Then
  147.                    Me.Width = CInt(Math.Ceiling(Size.Width)) * 2
  148.                End If
  149.            End Using
  150.        End Sub
  151.  
  152. #End Region
  153.  
  154.    End Class
  155.  
  156. ' End Namespace
  157.  
  158. #End Region

+

ElektroTimePickerDesigner.vb
Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 06-December-2017
  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 " Imports "
  15.  
  16. Imports System
  17. Imports System.Collections
  18. Imports System.Diagnostics
  19. Imports System.Windows.Forms.Design
  20.  
  21. #End Region
  22.  
  23. #Region " ElektroTimePickerDesigner "
  24.  
  25. ' Namespace ElektroKit.UserControls.Designers
  26.  
  27.    ''' ----------------------------------------------------------------------------------------------------
  28.    ''' <summary>
  29.    ''' Extends the design mode behavior of a <see cref="ElektroTimePicker"/> control.
  30.    ''' </summary>
  31.    ''' ----------------------------------------------------------------------------------------------------
  32.    ''' <seealso cref="ElektroTimePicker"/>
  33.    ''' ----------------------------------------------------------------------------------------------------
  34.    <DebuggerStepThrough>
  35.    Public NotInheritable Class ElektroTimePickerDesigner : Inherits ControlDesigner
  36.  
  37.        ''' ----------------------------------------------------------------------------------------------------
  38.        ''' <summary>
  39.        ''' Provides design-time support for the <see cref="ElektroTimePicker"/> control.
  40.        ''' </summary>
  41.        ''' ----------------------------------------------------------------------------------------------------
  42.        ''' <param name="properties">
  43.        ''' Ab <see cref="IDictionary"/> that contains the properties for the class of the component.
  44.        ''' </param>
  45.        ''' ----------------------------------------------------------------------------------------------------
  46.        Protected Overrides Sub PreFilterProperties(ByVal properties As IDictionary)
  47.  
  48.            MyBase.PreFilterAttributes(properties)
  49.  
  50.            Dim propertyNames As String() = {
  51.                "CalendarFont",
  52.                "CalendarForeColor",
  53.                "CalendarMonthBackground",
  54.                "CalendarTitleBackColor",
  55.                "CalendarTitleForeColor",
  56.                "CalendarTrailingForeColor",
  57.                "CustomFormat",
  58.                "DropDownAlign",
  59.                "Format",
  60.                "MaxDate",
  61.                "MinDate",
  62.                "ShowUpDown"
  63.            }
  64.  
  65.            For Each propertyName As String In propertyNames
  66.                properties.Remove(propertyName)
  67.            Next
  68.  
  69.        End Sub
  70.  
  71.    End Class
  72.  
  73. ' End Namespace
  74.  
  75. #End Region

Saludos