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

 

 


Tema destacado: ¿Eres nuevo? ¿Tienes dudas acerca del funcionamiento de la comunidad? Lee las Reglas Generales


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  ayuda con textbox (Solucionado)
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] 2 Ir Abajo Respuesta Imprimir
Autor Tema: ayuda con textbox (Solucionado)  (Leído 9,390 veces)
nolasco281


Desconectado Desconectado

Mensajes: 319


Ver Perfil
ayuda con textbox (Solucionado)
« en: 21 Abril 2014, 00:38 am »

Hola como están.

Mi siguiente duda estoy tratado de hacer algo en un textbox que tenga un texto predeterminado pero que este se vea claro, de la siguiente forma.



Como ven en user name y cuando se de click se quite ese texto y pueda ingresar datos.
Estaba leyendo MSDN pero son demasiadas funciones las que tiene me llevara un tiempo leerlas todas.

Espero puedan ayudarme gracias y saludos

PD: estoy trabajando en VB


« Última modificación: 22 Abril 2014, 22:51 pm por nolasco281 » En línea

Lo que se puede imaginar... se puede programar.
ivancea96


Desconectado Desconectado

Mensajes: 3.412


ASMático


Ver Perfil WWW
Re: ayuda con textbox
« Respuesta #1 en: 21 Abril 2014, 01:22 am »

Bueno yo en C++ aún no hice este tipo de formularios, pero te digo:

Ese texto es el "Placeholder".

MSDN-Textbox.placeholdertext


En línea

eferion


Desconectado Desconectado

Mensajes: 1.248


Ver Perfil
Re: ayuda con textbox
« Respuesta #2 en: 21 Abril 2014, 09:19 am »

Bueno yo en C++ aún no hice este tipo de formularios, pero te digo:

Ese texto es el "Placeholder".

MSDN-Textbox.placeholdertext

Eso es si está trabajando con XAML, que no creo que sea el caso.

Por la pinta de ese formulario, yo diría que está trabajando con los controles nativos de .NET... lo que no queda claro es con qué versión.

En este caso, una opción sencilla es controlar los eventos de "foco" del control.

Lo suyo es crear una clase que derive de "TextBox" y controle los eventos de "foco", de tal forma que:

* si el control pierde el foco y no tiene contenido, se escriba ese texto en el fondo ( puedes empezar por hacer una versión sencilla escribiendo el contenido en su propiedad "Text" y cambiar el color de la fuente por un gris ).

* al recibir el foco el control, si su contenido es éste que tiene por defecto, se borre su contenido, permitiéndole al usuario una entrada limpia.

Este comportamiento es muy básico y se puede perfeccionar, por supuesto, pero como base sirve.
En línea

nolasco281


Desconectado Desconectado

Mensajes: 319


Ver Perfil
Re: ayuda con textbox
« Respuesta #3 en: 21 Abril 2014, 13:31 pm »

Mil gracias por contestar como siempre la los que se toman la molestia de contestar y alos que pasan por si pueden ayudar.

Bueno he estado investigando y viendo algunos videos

este es el codigo que tengo y lo estoy haciendo en una clase

Código
  1. Public Class MarcaDeAgua
  2.    Iterator TextBox
  3.  
  4.    Dim MarcaDeAguatxt As String = "Por defecto"
  5.    Dim MarcaDeAguaclr As Color = Color.LightGray
  6.  
  7.    Public Property MarcaDeAguaText() As String
  8.        Get
  9.            Return MarcaDeAguatxt
  10.        End Get
  11.        Set(value As String)
  12.            MarcaDeAguatxt = value
  13.        End Set
  14.    End Property
  15.  
  16.    Public Property MarcaDeAguaColor() As Color
  17.        Get
  18.            Return MarcaDeAguaclr
  19.        End Get
  20.        Set(value As Color)
  21.            MarcaDeAguaclr = value
  22.        End Set
  23.    End Property
  24.  
  25.    Private Sub MarcaDeAgua_Click(ByVal sender As Object, ByVal e As System.EventArgs)
  26.        If Me.Text = MarcaDeAguatxt Then
  27.            Me.SelectionStar = 0
  28.        End If
  29.    End Sub
  30.  
  31.    Private Sub MarcaDeAguaTextBox_KeyDown(ByVal sender As Object, ByVal e As System.EventArgs)
  32.        If e.KeyCode = 8 Then
  33.            If Me.Text. = MarcaDeAguatxt then
  34.                If Me.SelectionStar = Me.Text.Length Then
  35.                    Me.SelectionStar = 0
  36.                End If
  37.            End If
  38.    End Sub
  39.  
  40.    Private Sub MarcaDeAguaTextBox_KeyUp(ByVal sender As Object, ByVal e As System.EventArgs)
  41.        If Me.Text.Contains(MarcaDeAguatxt) Then
  42.            Me.Text = Remplace(Me.Text, MarcaDeAguatxt, "")
  43.            Me.SelectionStar() = Me.MarcaDeAguaText.Length
  44.        End If
  45.    End Sub
  46.  
  47.    Private Sub MarcaDeAguaTextBox_ParentChange(ByVal sender As Object, ByVal e As System.EventArgs)
  48.        Me.SelectionStar() = 0
  49.    End Sub
  50.  
  51.    Private Sub MarcaDeAguaTextBox_TextChange(ByVal sender As Object, ByVal e As System.EventArgs)
  52.        If Me.Text = MarcaDeAguatxt Then
  53.            Me.Font = New Font(Me.Font, FontStyle.Italic)
  54.            Me.ForeColor = MarcaDeAguaclr
  55.        Else
  56.            Me.Font = New Font((Me.Font, FontStyle.Style)
  57.            Me.ForeColor = Color.Black
  58.        End If
  59.        If Me.Text = "" Then
  60.            Me.Text = MarcaDeAguatxt
  61.        End If
  62.    End Sub
  63. End Class

La idea es de aca pero no me sale.
https://www.youtube.com/watch?v=2sziyeOS8Ko

Aca una imagen de lo que tengo



disculpen si se ve mal estoy a la carrera

saludos y muchas gracias de nuevo
En línea

Lo que se puede imaginar... se puede programar.
eferion


Desconectado Desconectado

Mensajes: 1.248


Ver Perfil
Re: ayuda con textbox
« Respuesta #4 en: 21 Abril 2014, 13:38 pm »

Con ese código estás haciendo que la marca de agua aparezca siempre que no haya texto en el control... es un tratamiento más refinado pero da más problemas.

En teoría con la gestión del foco te debería servir... además no tendrías que lidiar con las pulsaciones del teclado... con la opción "pegar" del menú contextual... etc.

Si quieres seguir con tu idea de que sea sensible al contenido del TextBox en edición quizás sería más sencillo "pintar" la marca de agua en el evento OnPaint en vez de pasarla al Text... la ventaja que consigues es que no saltan eventos cada vez que pones / quitas la marca de agua y no tienes que preocuparte por la posición del "caret".
En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.809



Ver Perfil
Re: ayuda con textbox
« Respuesta #5 en: 21 Abril 2014, 23:33 pm »

Código
  1.    ' Set Control Hint
  2.    ' ( By Elektro )
  3.  
  4.    ''' <summary>
  5.    ''' Indicates the Textbox Hint.
  6.    ''' </summary>
  7.    Private ReadOnly TextBoxHint As String = "I'm a control hint."
  8.  
  9.    ''' <summary>
  10.    ''' Handles the Hint event of the TextBox control.
  11.    ''' </summary>
  12.    ''' <param name="sender">The source of the event.</param>
  13.    ''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  14.    Private Sub TextBox_Leave(ByVal sender As Object, ByVal e As EventArgs) Handles _
  15.    TextBox1.Leave, TextBox1.HandleCreated
  16.  
  17.        Select Case CStr(sender.Text)
  18.  
  19.            Case Is = TextBoxHint
  20.                sender.text = String.Empty
  21.  
  22.            Case Is = String.Empty
  23.                sender.text = TextBoxHint
  24.  
  25.        End Select
  26.  
  27.    End Sub
  28.  
  29.    ''' <summary>
  30.    ''' Handles the Enter event of the TextBox control.
  31.    ''' </summary>
  32.    ''' <param name="sender">The source of the event.</param>
  33.    ''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  34.    Private Sub TextBox_Enter(ByVal sender As Object, ByVal e As EventArgs) Handles _
  35.    TextBox1.Enter
  36.  
  37.        Select Case CStr(sender.Text)
  38.  
  39.            Case Is = TextBoxHint
  40.                sender.text = String.Empty
  41.  
  42.        End Select
  43.  
  44.    End Sub

O usando API's:

Código
  1.    ' Set Control Hint
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    ' SetControlHint(TextBox1, "I'm a text hint.")
  6.  
  7.    ''' <summary>
  8.    ''' Messages to send to an Edit control, such a TextBox.
  9.    ''' </summary>
  10.    Private Enum EditControlMessages As Integer
  11.  
  12.        ''' <summary>
  13.        ''' Sets the textual cue, or tip, that is displayed by the edit control to prompt the user for information.
  14.        ''' http://msdn.microsoft.com/en-us/library/windows/desktop/bb761639%28v=vs.85%29.aspx
  15.        ''' </summary>
  16.        SetCueBanner = &H1501I
  17.  
  18.    End Enum
  19.  
  20.    ''' <summary>
  21.    ''' Sends the specified message to a window or windows.
  22.    ''' The SendMessage function calls the window procedure for the specified window
  23.    ''' and does not return until the window procedure has processed the message.
  24.    ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms644950%28v=vs.85%29.aspx
  25.    ''' </summary>
  26.    ''' <param name="hWnd">
  27.    ''' A handle to the Control whose will receive the message.
  28.    ''' </param>
  29.    ''' <param name="msg">
  30.    ''' The message to be sent.
  31.    ''' </param>
  32.    ''' <param name="wParam">
  33.    ''' Additional message-specific information.
  34.    ''' </param>
  35.    ''' <param name="lParam">
  36.    ''' Additional message-specific information.
  37.    ''' </param>
  38.    ''' <returns>
  39.    ''' The return value specifies the result of the message processing; it depends on the message sent.
  40.    ''' </returns>
  41.    <System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint:="SendMessage",
  42.    CharSet:=System.Runtime.InteropServices.CharSet.Auto)>
  43.    Private Shared Function SendEditControlMessage(
  44.            ByVal hWnd As IntPtr,
  45.            ByVal msg As EditControlMessages,
  46.            ByVal wParam As IntPtr,
  47.            <System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)>
  48.            ByVal lParam As String
  49.    ) As UInteger
  50.    End Function
  51.  
  52.    ''' <summary>
  53.    ''' Sets a text hint for an edit control such a TextBox.
  54.    ''' </summary>
  55.    ''' <param name="Control">Indicates the control.</param>
  56.    ''' <param name="Hint">Indicates the text hint.</param>
  57.    ''' <returns><c>true</c> if operation succeeds, <c>false</c> otherwise.</returns>
  58.    Private Function SetControlHint(ByVal [Control] As Control,
  59.                                    ByVal Hint As String) As Boolean
  60.  
  61.        Return SendEditControlMessage([Control].Handle, EditControlMessages.SetCueBanner, IntPtr.Zero, Hint)
  62.  
  63.    End Function

Saludos.
En línea

nolasco281


Desconectado Desconectado

Mensajes: 319


Ver Perfil
Re: ayuda con textbox
« Respuesta #6 en: 22 Abril 2014, 02:29 am »

Gracias por responder a todos estoy probando lo que me comento eferion y ahi voy solo me falta probar lo de Eleкtro muchas gracias de nuevo saludos a todos.
En línea

Lo que se puede imaginar... se puede programar.
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.809



Ver Perfil
Re: ayuda con textbox
« Respuesta #7 en: 22 Abril 2014, 05:30 am »

Esto lo acabo de escribir para reemplazar a los dos métodos que te proporcioné antes y extender su funcionalidad,
es un ayudante (una helper class) bastante personalizable para asignar/eliminar hints/watermarks a los controles.

EDITO: Código Actualizado
Código
  1. ' ***********************************************************************
  2. ' Author           : Elektro
  3. ' Last Modified On : 04-22-2014
  4. ' ***********************************************************************
  5. ' <copyright file="ControlHintHelper.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Imports "
  11.  
  12. Imports System.Reflection
  13.  
  14. #End Region
  15.  
  16. ''' <summary>
  17. ''' Helper Class that manages text-hints for Edit controls.
  18. ''' </summary>
  19. Friend NotInheritable Class ControlHintHelper
  20.  
  21. #Region " Object members "
  22.  
  23.    ''' <summary>
  24.    ''' Collection of currentlly handled controls and it's text-hint properties.
  25.    ''' </summary>
  26.    Public Shared ControlHints As New Dictionary(Of Control, HintProperties)
  27.  
  28.    ''' <summary>
  29.    ''' Collection of currentlly handled controls and it's default property values.
  30.    ''' </summary>
  31.    Private Shared ControlHintsDefaults As New Dictionary(Of Control, HintProperties)
  32.  
  33. #End Region
  34.  
  35. #Region " Properties "
  36.  
  37.    ''' <summary>
  38.    ''' Determines a text-hint and it's personalization properties.
  39.    ''' </summary>
  40.    Public Class HintProperties
  41.  
  42.        ''' <summary>
  43.        ''' Gets or sets the text-hint type.
  44.        ''' </summary>
  45.        ''' <value>The Hint type.</value>
  46.        Public Property HintType As HintType = ControlHintHelper.HintType.Normal
  47.  
  48.        ''' <summary>
  49.        ''' Gets or sets the text-hint.
  50.        ''' </summary>
  51.        ''' <value>The hint-text.</value>
  52.        Public Property Text As String = String.Empty
  53.  
  54.        ''' <summary>
  55.        ''' Gets or sets the text-hint font.
  56.        ''' </summary>
  57.        ''' <value>The text font.</value>
  58.        Public Property Font As Font = Nothing
  59.  
  60.        ''' <summary>
  61.        ''' Gets or sets the text-hint color.
  62.        ''' </summary>
  63.        ''' <value>The text color.</value>
  64.        Public Property ForeColor As Color = Color.Empty
  65.  
  66.    End Class
  67.  
  68. #End Region
  69.  
  70. #Region " Enums "
  71.  
  72.    ''' <summary>
  73.    ''' Specifies the posssible Hint types.
  74.    ''' </summary>
  75.    Public Enum HintType As Integer
  76.  
  77.        ''' <summary>
  78.        ''' The Hint is removed when the Control gets focus.
  79.        ''' </summary>
  80.        Normal = 0
  81.  
  82.        ''' <summary>
  83.        ''' The Hint is not removed when the Control gets focus.
  84.        ''' </summary>
  85.        Persistent = 1
  86.  
  87.    End Enum
  88.  
  89. #End Region
  90.  
  91. #Region " Constructors "
  92.  
  93.    ''' <summary>
  94.    ''' Prevents a default instance of the <see cref="ControlHintHelper" /> class from being created.
  95.    ''' </summary>
  96.    Private Sub New()
  97.    End Sub
  98.  
  99. #End Region
  100.  
  101. #Region " Public Methods "
  102.  
  103.    ''' <summary>
  104.    ''' Sets a new text-hint for an specific control.
  105.    ''' </summary>
  106.    ''' <param name="Control">Indicates the control.</param>
  107.    ''' <param name="HintProperties">TheIndicates the text-hint properties.</param>
  108.    ''' <exception cref="Exception">Text hint can't be null or empty.</exception>
  109.    Public Shared Sub SetHint(ByVal [Control] As Control,
  110.                              ByVal [HintProperties] As HintProperties)
  111.  
  112.        ' Ensure and fix empty hint properties.
  113.        With [HintProperties]
  114.  
  115.            If String.IsNullOrEmpty(.Text) Then
  116.                Throw New Exception("Text hint can't be null or empty.")
  117.                Exit Sub
  118.            End If
  119.  
  120.            If .Font Is Nothing Then
  121.                .Font = GetPropertyValue([Control], "Font")
  122.            End If
  123.  
  124.            If .ForeColor = Color.Empty Then
  125.                .ForeColor = GetPropertyValue([Control], "ForeColor")
  126.            End If
  127.  
  128.        End With
  129.  
  130.        ' Set the default control property values to restore them when needed.
  131.        Dim Deaults As New HintProperties
  132.        With Deaults
  133.            .Text = String.Empty
  134.            .Font = GetPropertyValue([Control], "Font")
  135.            .ForeColor = GetPropertyValue([Control], "ForeColor")
  136.        End With
  137.  
  138.        ' Ready to handle the Control.
  139.        Select Case ControlHints.ContainsKey([Control])
  140.  
  141.            Case True ' Control-hint is already set and handled.
  142.                ' Just replace the new hint properties in the collection.
  143.                ControlHints([Control]) = [HintProperties]
  144.  
  145.            Case False ' Control-hint is not set.
  146.  
  147.                ' Add the hint properties into collections.
  148.                ControlHints.Add([Control], [HintProperties])
  149.                ControlHintsDefaults.Add([Control], Deaults)
  150.  
  151.                With [Control]
  152.  
  153.                    ' Remove previouslly handled events (if any).
  154.                    RemoveHandler .HandleCreated, AddressOf Control_HandleCreated
  155.                    RemoveHandler .Enter, AddressOf Control_Enter
  156.                    RemoveHandler .Leave, AddressOf Control_Leave
  157.                    RemoveHandler .Disposed, AddressOf Control_Disposed
  158.                    RemoveHandler .MouseDown, AddressOf Control_MouseDown
  159.                    RemoveHandler .KeyDown, AddressOf Control_KeyDown
  160.  
  161.                    ' Start handling the control events.
  162.                    AddHandler .HandleCreated, AddressOf Control_HandleCreated
  163.                    AddHandler .Enter, AddressOf Control_Enter
  164.                    AddHandler .Leave, AddressOf Control_Leave
  165.                    AddHandler .Disposed, AddressOf Control_Disposed
  166.                    AddHandler .MouseDown, AddressOf Control_MouseDown
  167.                    AddHandler .KeyDown, AddressOf Control_KeyDown
  168.  
  169.                End With
  170.  
  171.        End Select
  172.  
  173.    End Sub
  174.  
  175.    ''' <summary>
  176.    ''' Sets a new text-hint for various controls.
  177.    ''' </summary>
  178.    ''' <param name="Controls">Indicates the controls.</param>
  179.    ''' <param name="HintProperties">TheIndicates the text-hint properties.</param>
  180.    Public Shared Sub SetHint(ByVal Controls As Control(),
  181.                              ByVal [HintProperties] As HintProperties)
  182.  
  183.        For Each [Control] As Control In Controls
  184.            SetHint([Control], [HintProperties])
  185.        Next [Control]
  186.  
  187.    End Sub
  188.  
  189.    ''' <summary>
  190.    ''' Removes a text-hint from a control.
  191.    ''' </summary>
  192.    ''' <param name="Control">Indicates the control.</param>
  193.    Public Shared Sub RemoveHint(ByVal [Control] As Control)
  194.  
  195.        Select Case ControlHints.ContainsKey([Control])
  196.  
  197.            Case True ' Control-hint is already set.
  198.  
  199.                ' Remove events from event handlers.
  200.                With [Control]
  201.                    RemoveHandler .HandleCreated, AddressOf Control_HandleCreated
  202.                    RemoveHandler .Enter, AddressOf Control_Enter
  203.                    RemoveHandler .Leave, AddressOf Control_Leave
  204.                    RemoveHandler .Disposed, AddressOf Control_Disposed
  205.                    RemoveHandler .MouseDown, AddressOf Control_MouseDown
  206.                    RemoveHandler .KeyDown, AddressOf Control_KeyDown
  207.                End With
  208.  
  209.                If Not [Control].IsDisposed Then ' If the Control is not disposed then...
  210.  
  211.                    If [Control].Text.Trim = ControlHints([Control]).Text.Trim Then
  212.                        ' Restore it's default property values and clear the control text.
  213.                        RestoreProperties([Control], ControlHintsDefaults([Control]))
  214.                    Else
  215.                        ' Restore it's default property values and skip the control text.
  216.                        RestoreProperties([Control], ControlHintsDefaults([Control]), SkipProperties:={"Text"})
  217.                    End If
  218.  
  219.                End If
  220.  
  221.                ' Remove the control-hints from hints collections.
  222.                ControlHints.Remove([Control])
  223.                ControlHintsDefaults.Remove([Control])
  224.  
  225.        End Select
  226.  
  227.    End Sub
  228.  
  229.    ''' <summary>
  230.    ''' Removes a text-hint from a control.
  231.    ''' </summary>
  232.    ''' <param name="Controls">Indicates the controls.</param>
  233.    Public Shared Sub RemoveHint(ByVal Controls As Control())
  234.  
  235.        For Each [Control] As Control In Controls
  236.            RemoveHint([Control])
  237.        Next [Control]
  238.  
  239.    End Sub
  240.  
  241. #End Region
  242.  
  243. #Region " Private Methods "
  244.  
  245.    ''' <summary>
  246.    ''' Gets the property value of an specific control through reflection.
  247.    ''' </summary>
  248.    ''' <param name="Control">Indicates the Control.</param>
  249.    ''' <param name="PropertyName">Indicates the name of the property to get it's value.</param>
  250.    ''' <returns>If the property is not found on the Control, the return value is 'Nothing',
  251.    ''' Otherwise, the return value is the Control's property value.</returns>
  252.    Private Shared Function GetPropertyValue(ByVal [Control] As Control,
  253.                                             ByVal PropertyName As String) As Object
  254.  
  255.        Dim Prop As PropertyInfo = [Control].GetType.GetProperty(PropertyName)
  256.  
  257.        Select Case Prop Is Nothing
  258.  
  259.            Case True
  260.                Return Nothing
  261.  
  262.            Case Else
  263.                Return Prop.GetValue([Control], Nothing)
  264.  
  265.        End Select
  266.  
  267.    End Function
  268.  
  269.    ''' <summary>
  270.    ''' Sets the properties of an specific control.
  271.    ''' </summary>
  272.    ''' <param name="Control">Indicates the Control.</param>
  273.    ''' <param name="HintProperties">Indicates the properties to set it's values.</param>
  274.    ''' <param name="SkipProperties">Indicates the properties to skip.</param>
  275.    Private Shared Sub SetProperties(ByVal [Control] As Object,
  276.                                     ByVal HintProperties As HintProperties,
  277.                                     Optional ByVal SkipProperties As String() = Nothing)
  278.  
  279.        ' Get the control type.
  280.        Dim ControlType As Type = [Control].GetType
  281.        Dim ExcludeProperties As String() = If(SkipProperties Is Nothing, {""}, SkipProperties)
  282.  
  283.        ' Loop through the 'HintProperties' properties to determine whether exist all the needed properties in the Control.
  284.        For Each HintProperty As PropertyInfo In HintProperties.GetType.GetProperties
  285.  
  286.            Dim ControlProperty As PropertyInfo = ControlType.GetProperty(HintProperty.Name)
  287.  
  288.            If Not ControlProperty Is Nothing AndAlso Not ExcludeProperties.Contains(ControlProperty.Name) Then
  289.                ControlProperty.SetValue([Control], HintProperty.GetValue(HintProperties, Nothing), Nothing)
  290.            End If
  291.  
  292.        Next HintProperty
  293.  
  294.    End Sub
  295.  
  296.    ''' <summary>
  297.    ''' Restores the properties of an specific control.
  298.    ''' </summary>
  299.    ''' <param name="Control">Indicates the Control.</param>
  300.    ''' <param name="DefaultProperties">Indicates the properties to reset it's values.</param>
  301.    ''' <param name="SkipProperties">Indicates the properties to skip.</param>
  302.    Private Shared Sub RestoreProperties(ByVal [Control] As Object,
  303.                                         ByVal DefaultProperties As HintProperties,
  304.                                         Optional ByVal SkipProperties As String() = Nothing)
  305.  
  306.        Dim ExcludeProperties As String() = If(SkipProperties Is Nothing, {""}, SkipProperties)
  307.  
  308.        ' Get the control type.
  309.        Dim ControlType As Type = [Control].GetType
  310.  
  311.        ' Loop through the 'DefaultProperties' properties to determine whether exist all the needed properties in the Control.
  312.        For Each DefaultProperty As PropertyInfo In DefaultProperties.GetType.GetProperties.Reverse
  313.  
  314.            Dim ControlProperty As PropertyInfo = ControlType.GetProperty(DefaultProperty.Name)
  315.  
  316.            If Not ControlProperty Is Nothing AndAlso Not ExcludeProperties.Contains(ControlProperty.Name) Then
  317.                ControlProperty.SetValue([Control], DefaultProperty.GetValue(DefaultProperties, Nothing), Nothing)
  318.            End If
  319.  
  320.        Next DefaultProperty
  321.  
  322.    End Sub
  323.  
  324. #End Region
  325.  
  326. #Region "Event Handlers "
  327.  
  328.    ''' <summary>
  329.    ''' Handles the HandleCreated event of the Control.
  330.    ''' </summary>
  331.    ''' <param name="sender">The source of the event.</param>
  332.    ''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  333.    Private Shared Sub Control_HandleCreated(ByVal sender As Object, ByVal e As EventArgs)
  334.  
  335.        Dim [Control] As Control = DirectCast(sender, Control)
  336.        Dim [HintProperties] As HintProperties = ControlHints([Control])
  337.  
  338.        SetProperties([Control], [HintProperties])
  339.  
  340.    End Sub
  341.  
  342.    ''' <summary>
  343.    ''' Handles the Enter event of the Control.
  344.    ''' </summary>
  345.    ''' <param name="sender">The source of the event.</param>
  346.    ''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  347.    Private Shared Sub Control_Enter(ByVal sender As Object, ByVal e As EventArgs)
  348.  
  349.        Dim [Control] As Control = DirectCast(sender, Control)
  350.        Dim [HintProperties] As HintProperties = ControlHints([Control])
  351.  
  352.        Select Case [HintProperties].HintType
  353.  
  354.            Case HintType.Normal
  355.                If [Control].Text.Trim = [HintProperties].Text.Trim Then ' Restore it's default values.
  356.                    RestoreProperties([Control], ControlHintsDefaults([Control]))
  357.                End If
  358.  
  359.        End Select
  360.  
  361.    End Sub
  362.  
  363.    ''' <summary>
  364.    ''' Handles the Leave event of the control.
  365.    ''' </summary>
  366.    ''' <param name="sender">The source of the event.</param>
  367.    ''' <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  368.    Private Shared Sub Control_Leave(ByVal sender As Object, ByVal e As EventArgs)
  369.  
  370.        Dim [Control] As Control = DirectCast(sender, Control)
  371.        Dim [HintProperties] As HintProperties = ControlHints([Control])
  372.  
  373.        Select Case [HintProperties].HintType
  374.  
  375.            Case HintType.Normal
  376.                Select Case [Control].Text.Trim
  377.  
  378.                    Case Is = [HintProperties].Text.Trim ' Restore it's default values.
  379.                        RestoreProperties([Control], ControlHintsDefaults(sender))
  380.  
  381.                    Case Is = String.Empty ' Set the hint values.
  382.                        SetProperties([Control], [HintProperties])
  383.  
  384.                End Select
  385.  
  386.            Case HintType.Persistent
  387.                Select Case [Control].Text.Trim
  388.  
  389.                    Case Is = String.Empty ' Set the hint values.
  390.                        SetProperties([Control], [HintProperties])
  391.  
  392.                End Select
  393.  
  394.        End Select
  395.  
  396.    End Sub
  397.  
  398.    ''' <summary>
  399.    ''' Handles the MouseDown event of the control.
  400.    ''' </summary>
  401.    ''' <param name="sender">The source of the event.</param>
  402.    ''' <param name="e">The <see cref="MouseEventArgs" /> instance containing the event data.</param>
  403.    Private Shared Sub Control_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs)
  404.  
  405.        Dim [Control] As Control = DirectCast(sender, Control)
  406.        Dim [HintProperties] As HintProperties = ControlHints([Control])
  407.  
  408.        Select Case [HintProperties].HintType
  409.  
  410.            Case HintType.Persistent
  411.  
  412.                If [Control].Text.Trim = [HintProperties].Text.Trim Then
  413.  
  414.                    ' Get the 'Select' Control's Method (if exist).
  415.                    Dim Method = sender.GetType.GetMethod("Select",
  416.                                                          BindingFlags.Public Or BindingFlags.Instance Or BindingFlags.InvokeMethod,
  417.                                                          Nothing,
  418.                                                          {GetType(Integer), GetType(Integer)},
  419.                                                          Nothing)
  420.  
  421.                    If Not Method Is Nothing Then ' Select the zero length.
  422.                        Method.Invoke(sender, {0I, 0I})
  423.                    End If
  424.  
  425.                End If
  426.  
  427.        End Select
  428.  
  429.    End Sub
  430.  
  431.    ''' <summary>
  432.    ''' Handles the KeyDown event of the Control.
  433.    ''' </summary>
  434.    ''' <param name="sender">The source of the event.</param>
  435.    ''' <param name="e">The <see cref="KeyEventArgs"/> instance containing the event data.</param>
  436.    Private Shared Sub Control_KeyDown(sender As Object, e As KeyEventArgs)
  437.  
  438.  
  439.        Dim [Control] As Control = DirectCast(sender, Control)
  440.        Dim [HintProperties] As HintProperties = ControlHints([Control])
  441.  
  442.        Select Case [HintProperties].HintType
  443.  
  444.            Case HintType.Persistent
  445.                Select Case [Control].Text.Trim
  446.  
  447.                    Case Is = [HintProperties].Text.Trim ' Restore the control values.
  448.                        RestoreProperties([Control], ControlHintsDefaults([Control]))
  449.  
  450.                    Case Is = String.Empty
  451.                        RestoreProperties([Control], ControlHintsDefaults([Control]), SkipProperties:={"Text"})
  452.  
  453.                End Select
  454.  
  455.            Case HintType.Normal
  456.                Select Case [Control].Text.Trim
  457.  
  458.                    Case Is = String.Empty ' Restore the control values.
  459.                        RestoreProperties([Control], ControlHintsDefaults([Control]))
  460.  
  461.                    Case Else
  462.                        ' Do nothing.
  463.  
  464.                End Select
  465.  
  466.        End Select
  467.  
  468.    End Sub
  469.  
  470.    ''' <summary>
  471.    ''' Handles the Disposed event of the control.
  472.    ''' </summary>
  473.    ''' <param name="sender">The source of the event.</param>
  474.    ''' <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  475.    Private Shared Sub Control_Disposed(ByVal sender As Object, ByVal e As EventArgs)
  476.  
  477.        RemoveHint(DirectCast(sender, Control))
  478.  
  479.    End Sub
  480.  
  481. #End Region
  482.  
  483. End Class

Ejemplo de uso:

Código
  1. Public Class Form1
  2.  
  3.    ''' <summary>
  4.    ''' Initializes a new instance of the <see cref="Form1"/> class.
  5.    ''' </summary>
  6.    Public Sub New()
  7.  
  8.        ' This call is required by the designer.
  9.        InitializeComponent()
  10.  
  11.        ControlHintHelper.SetHint(TextBox1, New ControlHintHelper.HintProperties With {
  12.                                            .HintType = ControlHintHelper.HintType.Persistent,
  13.                                            .Text = "I'm a persistent hint.",
  14.                                            .ForeColor = Color.Gray})
  15.  
  16.        ControlHintHelper.SetHint({TextBox2, TextBox3}, New ControlHintHelper.HintProperties With {
  17.                                                            .Text = "I've set this hint on multiple controls at once!",
  18.                                                            .ForeColor = Color.Gray})
  19.  
  20.        ControlHintHelper.SetHint(RichTextBox1, New ControlHintHelper.HintProperties With {
  21.                                                    .Text = "Write something here...",
  22.                                                    .Font = New Font("lucida console", 15),
  23.                                                    .ForeColor = Color.YellowGreen})
  24.  
  25.    End Sub
  26.  
  27.  
  28.    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
  29.        ControlHintHelper.RemoveHint(TextBox1)
  30.        ControlHintHelper.RemoveHint({RichTextBox1})
  31.    End Sub
  32.  
  33. End Class
« Última modificación: 22 Abril 2014, 09:25 am por Eleкtro » En línea

nolasco281


Desconectado Desconectado

Mensajes: 319


Ver Perfil
Re: ayuda con textbox
« Respuesta #8 en: 22 Abril 2014, 11:29 am »

Hola primera mente.

Como siempre digo hay que agradecer a el grupo de personas que se toman el tiempo de ver y aun más a los que se toman el tiempo de ayudar a otro.

Muchas gracias.

Dicho esto estoy ya estudiando el código que tuviste la gentileza de compartir y tratando de entender muchas cosas que desconozco, también trate de probar lo que me comento eferion de la gestiones de foco probé une ejemplo que está en msdn y no me funciono no sé si será por la versión del VB pero me tiraba errores por todos lados.

Nota: La gestión de foco si no me equivoco hacia relación al Gotfocus y LostFocus si no me equivoco.

Con el código que comparte Eleкtro solo tienen que crear una clase y funciona de maravilla.
Acá la prueba y como el mismo menciona muy muy modificable.



Solo me falta agradecer de nuevo y para los curiosos esto va genial ya que hay poca información en cuanto a las marcas de agua

Saludos a todos y un  ;-) para todos los que ayudan a los demás. Cuídense.

PD: pueden recomendarme alguna pagina o libro que trate este tipo cosas se que parece meramente estetica pero aveces no lo son. Saludos.
« Última modificación: 22 Abril 2014, 11:47 am por nolasco281 » En línea

Lo que se puede imaginar... se puede programar.
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.809



Ver Perfil
Re: ayuda con textbox
« Respuesta #9 en: 22 Abril 2014, 12:47 pm »

Dicho esto estoy ya estudiando el código que tuviste la gentileza de compartir y tratando de entender muchas cosas que desconozco

El código podría ser MUCHO más sencillo ...muchisimo más, pero decidí usar Reflection para compatibilizar la propiedad TextAlign con otros controles de los que carecen de dicha propiedad y otros usan una enumeración distinta (de todas formas la propiedad al final decidí eliminar del código porque me estaba dando por culo al intentar restaurar el valor original del control al suscribirme al evento KeyDown del Textbox y quedaba un efecto muy feo xD), y también para los controles que no tuvieran propiedades como Font, Forecolor, etc...

A raíz de usar Reflection lo bueno es que los métodos SetProperties y RestoreProperties son bastante dinámicos y para extender la funcionalidad de la Class en general solo deberías añadir más nombres de propedades en la (sub)Class "HintProperties", y usar el parámetro SkipProperties al llamar a los métodos SetProperties/RestoreProperties  (en caso de que sea necesario omitir alguna propiedad).

Eso sí, no le añadí ningún Error-Handling (try/catch) ya que creo haber tenido todos los posibles conflictos en cuenta, mientras la Class se use con controles nativos de .NET framework no debería saltar ninguna excepción (espero que no).

¿Información sobre watermarks en controles?, no sabría decirte... tampoco yo creo que existe mucha documentación al respecto, puedes buscar y estudiar otros sources aquí: http://www.google.com/search?q=codeproject+control+watermark&ie=utf-8&oe=utf-8&lr=lang_en#lr=lang_en&q=codeproject+control+watermark&safe=active&tbs=lr:lang_1en hay varios métodos para hacerlo (por ejemplo, con Brushes)

Saludos!
En línea

Páginas: [1] 2 Ir Arriba Respuesta Imprimir 

Ir a:  

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