ayuda con textbox (Solucionado)

Iniciado por nolasco281, 21 Abril 2014, 00:38 AM

0 Miembros y 2 Visitantes están viendo este tema.

nolasco281

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
Lo que se puede imaginar... se puede programar.

ivancea96

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

Ese texto es el "Placeholder".

MSDN-Textbox.placeholdertext

eferion

Cita de: ivancea96 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

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.

nolasco281

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 (cpp) [Seleccionar]
Public Class MarcaDeAgua
    Iterator TextBox

    Dim MarcaDeAguatxt As String = "Por defecto"
    Dim MarcaDeAguaclr As Color = Color.LightGray

    Public Property MarcaDeAguaText() As String
        Get
            Return MarcaDeAguatxt
        End Get
        Set(value As String)
            MarcaDeAguatxt = value
        End Set
    End Property

    Public Property MarcaDeAguaColor() As Color
        Get
            Return MarcaDeAguaclr
        End Get
        Set(value As Color)
            MarcaDeAguaclr = value
        End Set
    End Property

    Private Sub MarcaDeAgua_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        If Me.Text = MarcaDeAguatxt Then
            Me.SelectionStar = 0
        End If
    End Sub

    Private Sub MarcaDeAguaTextBox_KeyDown(ByVal sender As Object, ByVal e As System.EventArgs)
        If e.KeyCode = 8 Then
            If Me.Text. = MarcaDeAguatxt then
                If Me.SelectionStar = Me.Text.Length Then
                    Me.SelectionStar = 0
                End If
            End If
    End Sub

    Private Sub MarcaDeAguaTextBox_KeyUp(ByVal sender As Object, ByVal e As System.EventArgs)
        If Me.Text.Contains(MarcaDeAguatxt) Then
            Me.Text = Remplace(Me.Text, MarcaDeAguatxt, "")
            Me.SelectionStar() = Me.MarcaDeAguaText.Length
        End If
    End Sub

    Private Sub MarcaDeAguaTextBox_ParentChange(ByVal sender As Object, ByVal e As System.EventArgs)
        Me.SelectionStar() = 0
    End Sub

    Private Sub MarcaDeAguaTextBox_TextChange(ByVal sender As Object, ByVal e As System.EventArgs)
        If Me.Text = MarcaDeAguatxt Then
            Me.Font = New Font(Me.Font, FontStyle.Italic)
            Me.ForeColor = MarcaDeAguaclr
        Else
            Me.Font = New Font((Me.Font, FontStyle.Style)
            Me.ForeColor = Color.Black
        End If
        If Me.Text = "" Then
            Me.Text = MarcaDeAguatxt
        End If
    End Sub
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
Lo que se puede imaginar... se puede programar.

eferion

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".

Eleкtro

Código (vbnet) [Seleccionar]
    ' Set Control Hint
    ' ( By Elektro )
     
    ''' <summary>
    ''' Indicates the Textbox Hint.
    ''' </summary>
    Private ReadOnly TextBoxHint As String = "I'm a control hint."

    ''' <summary>
    ''' Handles the Hint event of the TextBox control.
    ''' </summary>
    ''' <param name="sender">The source of the event.</param>
    ''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
    Private Sub TextBox_Leave(ByVal sender As Object, ByVal e As EventArgs) Handles _
    TextBox1.Leave, TextBox1.HandleCreated

        Select Case CStr(sender.Text)

            Case Is = TextBoxHint
                sender.text = String.Empty

            Case Is = String.Empty
                sender.text = TextBoxHint

        End Select

    End Sub

    ''' <summary>
    ''' Handles the Enter event of the TextBox control.
    ''' </summary>
    ''' <param name="sender">The source of the event.</param>
    ''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
    Private Sub TextBox_Enter(ByVal sender As Object, ByVal e As EventArgs) Handles _
    TextBox1.Enter

        Select Case CStr(sender.Text)

            Case Is = TextBoxHint
                sender.text = String.Empty

        End Select

    End Sub


O usando API's:

Código (vbnet) [Seleccionar]
    ' Set Control Hint
    ' ( By Elektro )
    '
    ' Usage Examples:
    ' SetControlHint(TextBox1, "I'm a text hint.")

    ''' <summary>
    ''' Messages to send to an Edit control, such a TextBox.
    ''' </summary>
    Private Enum EditControlMessages As Integer

        ''' <summary>
        ''' Sets the textual cue, or tip, that is displayed by the edit control to prompt the user for information.
        ''' http://msdn.microsoft.com/en-us/library/windows/desktop/bb761639%28v=vs.85%29.aspx
        ''' </summary>
        SetCueBanner = &H1501I

    End Enum

    ''' <summary>
    ''' Sends the specified message to a window or windows.
    ''' The SendMessage function calls the window procedure for the specified window
    ''' and does not return until the window procedure has processed the message.
    ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms644950%28v=vs.85%29.aspx
    ''' </summary>
    ''' <param name="hWnd">
    ''' A handle to the Control whose will receive the message.
    ''' </param>
    ''' <param name="msg">
    ''' The message to be sent.
    ''' </param>
    ''' <param name="wParam">
    ''' Additional message-specific information.
    ''' </param>
    ''' <param name="lParam">
    ''' Additional message-specific information.
    ''' </param>
    ''' <returns>
    ''' The return value specifies the result of the message processing; it depends on the message sent.
    ''' </returns>
    <System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint:="SendMessage",
    CharSet:=System.Runtime.InteropServices.CharSet.Auto)>
    Private Shared Function SendEditControlMessage(
            ByVal hWnd As IntPtr,
            ByVal msg As EditControlMessages,
            ByVal wParam As IntPtr,
            <System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)>
            ByVal lParam As String
    ) As UInteger
    End Function

    ''' <summary>
    ''' Sets a text hint for an edit control such a TextBox.
    ''' </summary>
    ''' <param name="Control">Indicates the control.</param>
    ''' <param name="Hint">Indicates the text hint.</param>
    ''' <returns><c>true</c> if operation succeeds, <c>false</c> otherwise.</returns>
    Private Function SetControlHint(ByVal [Control] As Control,
                                    ByVal Hint As String) As Boolean

        Return SendEditControlMessage([Control].Handle, EditControlMessages.SetCueBanner, IntPtr.Zero, Hint)

    End Function


Saludos.








nolasco281

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.
Lo que se puede imaginar... se puede programar.

Eleкtro

#7
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 (vbnet) [Seleccionar]
' ***********************************************************************
' Author           : Elektro
' Last Modified On : 04-22-2014
' ***********************************************************************
' <copyright file="ControlHintHelper.vb" company="Elektro Studios">
'     Copyright (c) Elektro Studios. All rights reserved.
' </copyright>
' ***********************************************************************

#Region " Imports "

Imports System.Reflection

#End Region

''' <summary>
''' Helper Class that manages text-hints for Edit controls.
''' </summary>
Friend NotInheritable Class ControlHintHelper

#Region " Object members "

    ''' <summary>
    ''' Collection of currentlly handled controls and it's text-hint properties.
    ''' </summary>
    Public Shared ControlHints As New Dictionary(Of Control, HintProperties)

    ''' <summary>
    ''' Collection of currentlly handled controls and it's default property values.
    ''' </summary>
    Private Shared ControlHintsDefaults As New Dictionary(Of Control, HintProperties)

#End Region

#Region " Properties "

    ''' <summary>
    ''' Determines a text-hint and it's personalization properties.
    ''' </summary>
    Public Class HintProperties

        ''' <summary>
        ''' Gets or sets the text-hint type.
        ''' </summary>
        ''' <value>The Hint type.</value>
        Public Property HintType As HintType = ControlHintHelper.HintType.Normal

        ''' <summary>
        ''' Gets or sets the text-hint.
        ''' </summary>
        ''' <value>The hint-text.</value>
        Public Property Text As String = String.Empty

        ''' <summary>
        ''' Gets or sets the text-hint font.
        ''' </summary>
        ''' <value>The text font.</value>
        Public Property Font As Font = Nothing

        ''' <summary>
        ''' Gets or sets the text-hint color.
        ''' </summary>
        ''' <value>The text color.</value>
        Public Property ForeColor As Color = Color.Empty

    End Class

#End Region

#Region " Enums "

    ''' <summary>
    ''' Specifies the posssible Hint types.
    ''' </summary>
    Public Enum HintType As Integer

        ''' <summary>
        ''' The Hint is removed when the Control gets focus.
        ''' </summary>
        Normal = 0

        ''' <summary>
        ''' The Hint is not removed when the Control gets focus.
        ''' </summary>
        Persistent = 1

    End Enum

#End Region

#Region " Constructors "

    ''' <summary>
    ''' Prevents a default instance of the <see cref="ControlHintHelper" /> class from being created.
    ''' </summary>
    Private Sub New()
    End Sub

#End Region

#Region " Public Methods "

    ''' <summary>
    ''' Sets a new text-hint for an specific control.
    ''' </summary>
    ''' <param name="Control">Indicates the control.</param>
    ''' <param name="HintProperties">TheIndicates the text-hint properties.</param>
    ''' <exception cref="Exception">Text hint can't be null or empty.</exception>
    Public Shared Sub SetHint(ByVal [Control] As Control,
                              ByVal [HintProperties] As HintProperties)

        ' Ensure and fix empty hint properties.
        With [HintProperties]

            If String.IsNullOrEmpty(.Text) Then
                Throw New Exception("Text hint can't be null or empty.")
                Exit Sub
            End If

            If .Font Is Nothing Then
                .Font = GetPropertyValue([Control], "Font")
            End If

            If .ForeColor = Color.Empty Then
                .ForeColor = GetPropertyValue([Control], "ForeColor")
            End If

        End With

        ' Set the default control property values to restore them when needed.
        Dim Deaults As New HintProperties
        With Deaults
            .Text = String.Empty
            .Font = GetPropertyValue([Control], "Font")
            .ForeColor = GetPropertyValue([Control], "ForeColor")
        End With

        ' Ready to handle the Control.
        Select Case ControlHints.ContainsKey([Control])

            Case True ' Control-hint is already set and handled.
                ' Just replace the new hint properties in the collection.
                ControlHints([Control]) = [HintProperties]

            Case False ' Control-hint is not set.

                ' Add the hint properties into collections.
                ControlHints.Add([Control], [HintProperties])
                ControlHintsDefaults.Add([Control], Deaults)

                With [Control]

                    ' Remove previouslly handled events (if any).
                    RemoveHandler .HandleCreated, AddressOf Control_HandleCreated
                    RemoveHandler .Enter, AddressOf Control_Enter
                    RemoveHandler .Leave, AddressOf Control_Leave
                    RemoveHandler .Disposed, AddressOf Control_Disposed
                    RemoveHandler .MouseDown, AddressOf Control_MouseDown
                    RemoveHandler .KeyDown, AddressOf Control_KeyDown

                    ' Start handling the control events.
                    AddHandler .HandleCreated, AddressOf Control_HandleCreated
                    AddHandler .Enter, AddressOf Control_Enter
                    AddHandler .Leave, AddressOf Control_Leave
                    AddHandler .Disposed, AddressOf Control_Disposed
                    AddHandler .MouseDown, AddressOf Control_MouseDown
                    AddHandler .KeyDown, AddressOf Control_KeyDown

                End With

        End Select

    End Sub

    ''' <summary>
    ''' Sets a new text-hint for various controls.
    ''' </summary>
    ''' <param name="Controls">Indicates the controls.</param>
    ''' <param name="HintProperties">TheIndicates the text-hint properties.</param>
    Public Shared Sub SetHint(ByVal Controls As Control(),
                              ByVal [HintProperties] As HintProperties)

        For Each [Control] As Control In Controls
            SetHint([Control], [HintProperties])
        Next [Control]

    End Sub

    ''' <summary>
    ''' Removes a text-hint from a control.
    ''' </summary>
    ''' <param name="Control">Indicates the control.</param>
    Public Shared Sub RemoveHint(ByVal [Control] As Control)

        Select Case ControlHints.ContainsKey([Control])

            Case True ' Control-hint is already set.

                ' Remove events from event handlers.
                With [Control]
                    RemoveHandler .HandleCreated, AddressOf Control_HandleCreated
                    RemoveHandler .Enter, AddressOf Control_Enter
                    RemoveHandler .Leave, AddressOf Control_Leave
                    RemoveHandler .Disposed, AddressOf Control_Disposed
                    RemoveHandler .MouseDown, AddressOf Control_MouseDown
                    RemoveHandler .KeyDown, AddressOf Control_KeyDown
                End With

                If Not [Control].IsDisposed Then ' If the Control is not disposed then...

                    If [Control].Text.Trim = ControlHints([Control]).Text.Trim Then
                        ' Restore it's default property values and clear the control text.
                        RestoreProperties([Control], ControlHintsDefaults([Control]))
                    Else
                        ' Restore it's default property values and skip the control text.
                        RestoreProperties([Control], ControlHintsDefaults([Control]), SkipProperties:={"Text"})
                    End If

                End If

                ' Remove the control-hints from hints collections.
                ControlHints.Remove([Control])
                ControlHintsDefaults.Remove([Control])

        End Select

    End Sub

    ''' <summary>
    ''' Removes a text-hint from a control.
    ''' </summary>
    ''' <param name="Controls">Indicates the controls.</param>
    Public Shared Sub RemoveHint(ByVal Controls As Control())

        For Each [Control] As Control In Controls
            RemoveHint([Control])
        Next [Control]

    End Sub

#End Region

#Region " Private Methods "

    ''' <summary>
    ''' Gets the property value of an specific control through reflection.
    ''' </summary>
    ''' <param name="Control">Indicates the Control.</param>
    ''' <param name="PropertyName">Indicates the name of the property to get it's value.</param>
    ''' <returns>If the property is not found on the Control, the return value is 'Nothing',
    ''' Otherwise, the return value is the Control's property value.</returns>
    Private Shared Function GetPropertyValue(ByVal [Control] As Control,
                                             ByVal PropertyName As String) As Object

        Dim Prop As PropertyInfo = [Control].GetType.GetProperty(PropertyName)

        Select Case Prop Is Nothing

            Case True
                Return Nothing

            Case Else
                Return Prop.GetValue([Control], Nothing)

        End Select

    End Function

    ''' <summary>
    ''' Sets the properties of an specific control.
    ''' </summary>
    ''' <param name="Control">Indicates the Control.</param>
    ''' <param name="HintProperties">Indicates the properties to set it's values.</param>
    ''' <param name="SkipProperties">Indicates the properties to skip.</param>
    Private Shared Sub SetProperties(ByVal [Control] As Object,
                                     ByVal HintProperties As HintProperties,
                                     Optional ByVal SkipProperties As String() = Nothing)

        ' Get the control type.
        Dim ControlType As Type = [Control].GetType
        Dim ExcludeProperties As String() = If(SkipProperties Is Nothing, {""}, SkipProperties)

        ' Loop through the 'HintProperties' properties to determine whether exist all the needed properties in the Control.
        For Each HintProperty As PropertyInfo In HintProperties.GetType.GetProperties

            Dim ControlProperty As PropertyInfo = ControlType.GetProperty(HintProperty.Name)

            If Not ControlProperty Is Nothing AndAlso Not ExcludeProperties.Contains(ControlProperty.Name) Then
                ControlProperty.SetValue([Control], HintProperty.GetValue(HintProperties, Nothing), Nothing)
            End If

        Next HintProperty

    End Sub

    ''' <summary>
    ''' Restores the properties of an specific control.
    ''' </summary>
    ''' <param name="Control">Indicates the Control.</param>
    ''' <param name="DefaultProperties">Indicates the properties to reset it's values.</param>
    ''' <param name="SkipProperties">Indicates the properties to skip.</param>
    Private Shared Sub RestoreProperties(ByVal [Control] As Object,
                                         ByVal DefaultProperties As HintProperties,
                                         Optional ByVal SkipProperties As String() = Nothing)

        Dim ExcludeProperties As String() = If(SkipProperties Is Nothing, {""}, SkipProperties)

        ' Get the control type.
        Dim ControlType As Type = [Control].GetType

        ' Loop through the 'DefaultProperties' properties to determine whether exist all the needed properties in the Control.
        For Each DefaultProperty As PropertyInfo In DefaultProperties.GetType.GetProperties.Reverse

            Dim ControlProperty As PropertyInfo = ControlType.GetProperty(DefaultProperty.Name)

            If Not ControlProperty Is Nothing AndAlso Not ExcludeProperties.Contains(ControlProperty.Name) Then
                ControlProperty.SetValue([Control], DefaultProperty.GetValue(DefaultProperties, Nothing), Nothing)
            End If

        Next DefaultProperty

    End Sub

#End Region

#Region "Event Handlers "

    ''' <summary>
    ''' Handles the HandleCreated event of the Control.
    ''' </summary>
    ''' <param name="sender">The source of the event.</param>
    ''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
    Private Shared Sub Control_HandleCreated(ByVal sender As Object, ByVal e As EventArgs)

        Dim [Control] As Control = DirectCast(sender, Control)
        Dim [HintProperties] As HintProperties = ControlHints([Control])

        SetProperties([Control], [HintProperties])

    End Sub

    ''' <summary>
    ''' Handles the Enter event of the Control.
    ''' </summary>
    ''' <param name="sender">The source of the event.</param>
    ''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
    Private Shared Sub Control_Enter(ByVal sender As Object, ByVal e As EventArgs)

        Dim [Control] As Control = DirectCast(sender, Control)
        Dim [HintProperties] As HintProperties = ControlHints([Control])

        Select Case [HintProperties].HintType

            Case HintType.Normal
                If [Control].Text.Trim = [HintProperties].Text.Trim Then ' Restore it's default values.
                    RestoreProperties([Control], ControlHintsDefaults([Control]))
                End If

        End Select

    End Sub

    ''' <summary>
    ''' Handles the Leave event of the control.
    ''' </summary>
    ''' <param name="sender">The source of the event.</param>
    ''' <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
    Private Shared Sub Control_Leave(ByVal sender As Object, ByVal e As EventArgs)

        Dim [Control] As Control = DirectCast(sender, Control)
        Dim [HintProperties] As HintProperties = ControlHints([Control])

        Select Case [HintProperties].HintType

            Case HintType.Normal
                Select Case [Control].Text.Trim

                    Case Is = [HintProperties].Text.Trim ' Restore it's default values.
                        RestoreProperties([Control], ControlHintsDefaults(sender))

                    Case Is = String.Empty ' Set the hint values.
                        SetProperties([Control], [HintProperties])

                End Select

            Case HintType.Persistent
                Select Case [Control].Text.Trim

                    Case Is = String.Empty ' Set the hint values.
                        SetProperties([Control], [HintProperties])

                End Select

        End Select

    End Sub

    ''' <summary>
    ''' Handles the MouseDown event of the control.
    ''' </summary>
    ''' <param name="sender">The source of the event.</param>
    ''' <param name="e">The <see cref="MouseEventArgs" /> instance containing the event data.</param>
    Private Shared Sub Control_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs)

        Dim [Control] As Control = DirectCast(sender, Control)
        Dim [HintProperties] As HintProperties = ControlHints([Control])

        Select Case [HintProperties].HintType

            Case HintType.Persistent

                If [Control].Text.Trim = [HintProperties].Text.Trim Then

                    ' Get the 'Select' Control's Method (if exist).
                    Dim Method = sender.GetType.GetMethod("Select",
                                                          BindingFlags.Public Or BindingFlags.Instance Or BindingFlags.InvokeMethod,
                                                          Nothing,
                                                          {GetType(Integer), GetType(Integer)},
                                                          Nothing)

                    If Not Method Is Nothing Then ' Select the zero length.
                        Method.Invoke(sender, {0I, 0I})
                    End If

                End If

        End Select

    End Sub

    ''' <summary>
    ''' Handles the KeyDown event of the Control.
    ''' </summary>
    ''' <param name="sender">The source of the event.</param>
    ''' <param name="e">The <see cref="KeyEventArgs"/> instance containing the event data.</param>
    Private Shared Sub Control_KeyDown(sender As Object, e As KeyEventArgs)


        Dim [Control] As Control = DirectCast(sender, Control)
        Dim [HintProperties] As HintProperties = ControlHints([Control])

        Select Case [HintProperties].HintType

            Case HintType.Persistent
                Select Case [Control].Text.Trim

                    Case Is = [HintProperties].Text.Trim ' Restore the control values.
                        RestoreProperties([Control], ControlHintsDefaults([Control]))

                    Case Is = String.Empty
                        RestoreProperties([Control], ControlHintsDefaults([Control]), SkipProperties:={"Text"})

                End Select

            Case HintType.Normal
                Select Case [Control].Text.Trim

                    Case Is = String.Empty ' Restore the control values.
                        RestoreProperties([Control], ControlHintsDefaults([Control]))

                    Case Else
                        ' Do nothing.

                End Select

        End Select

    End Sub

    ''' <summary>
    ''' Handles the Disposed event of the control.
    ''' </summary>
    ''' <param name="sender">The source of the event.</param>
    ''' <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
    Private Shared Sub Control_Disposed(ByVal sender As Object, ByVal e As EventArgs)

        RemoveHint(DirectCast(sender, Control))

    End Sub

#End Region

End Class


Ejemplo de uso:

Código (vbnet) [Seleccionar]
Public Class Form1

    ''' <summary>
    ''' Initializes a new instance of the <see cref="Form1"/> class.
    ''' </summary>
    Public Sub New()

        ' This call is required by the designer.
        InitializeComponent()

        ControlHintHelper.SetHint(TextBox1, New ControlHintHelper.HintProperties With {
                                            .HintType = ControlHintHelper.HintType.Persistent,
                                            .Text = "I'm a persistent hint.",
                                            .ForeColor = Color.Gray})

        ControlHintHelper.SetHint({TextBox2, TextBox3}, New ControlHintHelper.HintProperties With {
                                                            .Text = "I've set this hint on multiple controls at once!",
                                                            .ForeColor = Color.Gray})

        ControlHintHelper.SetHint(RichTextBox1, New ControlHintHelper.HintProperties With {
                                                    .Text = "Write something here...",
                                                    .Font = New Font("lucida console", 15),
                                                    .ForeColor = Color.YellowGreen})

    End Sub


    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        ControlHintHelper.RemoveHint(TextBox1)
        ControlHintHelper.RemoveHint({RichTextBox1})
    End Sub

End Class








nolasco281

#8
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.
Lo que se puede imaginar... se puede programar.

Eleкtro

Cita de: nolasco281 en 22 Abril 2014, 11:29 AMDicho 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!