Qusiera saber si alguien me puede orientar con una duda que tengo que
consiste en que necesito que cuando yo creoi un textbox este tenga
asociado un determinado codigo en su evento key press de manera que no
tenga que estar copiando y pegando el codigo cada que creo este tipo
de componentes, si alguno pudise facilitarme un ejemplo se los
agradeceria.
Lo �nico que tienes que hacer es crearte una nueva clase que herede de la
clase TextBox, y sobrescribir el m�todo OnKeyPress, o el que necesites, tal
y como muestra el siguiente ejemplo:
Public Class TextBoxEx
Inherits TextBox
Protected Overrides Sub OnKeyPress(ByVal e As KeyPressEventArgs)
' Escribe aqu� tu c�digo fuente
'
' ....
' Obtenemos el nombre del control que ha provocado el evento
'
MessageBox.Show("Nombre del control: " & Me.Name)
' Llamamos al m�todo de la clase base
MyBase.OnKeyPress(e)
End Sub
End Class
Una vez generado tu proyecto, en lugar de insertar en el formulario el
cl�sico control TextBox, inserta un control de la clase TextBoxEx.
Un saludo
--
Enrique Mart�nez
[MS MVP - VB]
Hola SoftJaén:
Gracias por tu pronta respuesta, ya la puse en practica y funciono de
maravilla.
Saludos.
y estaba haciendo un hipervox... en realidad hice un ocx para vb6 con muchas
opciones que me sirvio mucho luego en .net estaba haciendo uno pero no lo
termine porque luego nos dieron una suite de controles.
pero aqui te dejo el codigo del control, talves te sirven algunas
propiedades para el que queires hacer...
TipoDeDatos *** Principal Atractivo ***
BackColorDeshabilitado
BackColorSeleccionado
Decimales
FormatoDeSalida
FormatoPersonalizado
NegativoEnRojo
PasarAlCompletar
PasarElFoco
PegarDesdeElPortapapeles
UsarFlechas
'de aqui comienza el codigo...
Imports System.Globalization
Public Class HiperVOX
Inherits System.Windows.Forms.TextBox
Private bolPasarElFoco As Boolean = True 'ya
Private bolSeleccionarTexto As Boolean = True
Private bolPasarAlCompletar As Boolean = True
Private bolUsarFlechas As Boolean = True 'ya
Private bolPegarDesdePortapapeles As Boolean
Private bolNegativoEnRojo As Boolean = True
Private bolEsNumerico As Boolean = False
Private intDecimales As Integer = 2 '�a
Private strFormatoPersonalizado As String 'ya, pero falta que lo ponga
Private colDeshabilitado As Color = Color.DarkGray 'ya
Private colSeleccionado As Color = Color.PaleGreen 'ya
Private colBackColor As Color = Me.BackColor
Private colFont As Color = Me.ForeColor
Private intTipoDato As TiposDeDatos
Private intFormato As Formatos
Private strTexto As String = ""
Private charMiles As Char =
NumberFormatInfo.CurrentInfo.CurrencyGroupSeparator
Private charDecimal As Char =
NumberFormatInfo.CurrentInfo.NumberDecimalSeparator
Private intPosicion As Integer
'Que tipos de datos soportara el control
Public Enum TiposDeDatos
EntradaLibre
NumPositivos
NumPositivosConDecimales
NumCualquieraConDecimales
NumCualquieraSinDecimales
TextoSinCaracteres
TextoNombrePropio
TextoNombrePropioPuro
End Enum
'Que tipos de formato que soportara el control
Public Enum Formatos
NoUsarFormato
Millares
Decimales
Moneda
Personalizado
End Enum
' char DecimalPoint =
NumberFormatInfo.CurrentInfo.NumberDecimalSeparator[0];
'// caracter del punto decimal
'char GroupSeparator =
NumberFormatInfo.CurrentInfo.NumberGroupSeparator[0];
'// caracter para separar miles (ej: ",")
'string Prefix = NumberFormatInfo.CurrentInfo.CurrencySymbol;
'// signo de dinero (ej: "$")
#Region " C�digo generado por el Dise�ador de Windows Forms "
Public Sub New()
MyBase.New()
'El Dise�ador de Windows Forms requiere esta llamada.
InitializeComponent()
'Agregar cualquier inicializaci�n despu�s de la llamada a
InitializeComponent()
End Sub
'UserControl1 reemplaza a Dispose para limpiar la lista de componentes.
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing Then
If Not (components Is Nothing) Then
components.Dispose()
End If
End If
MyBase.Dispose(disposing)
End Sub
'Requerido por el Dise�ador de Windows Forms
Private components As System.ComponentModel.IContainer
'NOTA: el Dise�ador de Windows Forms requiere el siguiente procedimiento
'Puede modificarse utilizando el Dise�ador de Windows Forms.
'No lo modifique con el editor de c�digo.
<System.Diagnostics.DebuggerStepThrough()> Private Sub
InitializeComponent()
'
'HiperVOX
'
'Me.Text = ""
Me.Name = "HiperVOX"
End Sub
#End Region
'propiedad que nos indica que tipo de dato recibira el control
Property TipoDeDato() As TiposDeDatos
Get
Return intTipoDato
End Get
Set(ByVal Value As TiposDeDatos)
intTipoDato = Value
Select Case Value
Case TiposDeDatos.EntradaLibre,
TiposDeDatos.TextoNombrePropio, TiposDeDatos.TextoSinCaracteres,
TiposDeDatos.TextoNombrePropioPuro
EsNumerico = False
Case Else
EsNumerico = True
End Select
End Set
End Property
'propiedad pasa saber si al presionar enter pasara el foco
Property PasarElFoco() As Boolean
Get
Return bolPasarElFoco
End Get
Set(ByVal Value As Boolean)
bolPasarElFoco = Value
End Set
End Property
'propiedad que nos indica si podemos pasar al siguiente control al usar
las flecha
Property UsarFlechas() As Boolean
Get
Return bolUsarFlechas
End Get
Set(ByVal Value As Boolean)
bolUsarFlechas = Value
End Set
End Property
'propiedad que nos indica si podemos pasar al siguiente control al usar
las flecha
Property NegativoEnRojo() As Boolean
Get
Return bolNegativoEnRojo
End Get
Set(ByVal Value As Boolean)
bolNegativoEnRojo = Value
End Set
End Property
'propiedad que indica hasta cuantos decimales recibira el control
Property Decimales() As Integer
Get
Return intDecimales
End Get
Set(ByVal Value As Integer)
intDecimales = Value
End Set
End Property
'propiedad que sirve para indicarle el formato de salida del control
Property FormatoDeSalida() As Formatos
Get
Return intFormato
End Get
Set(ByVal Value As Formatos)
intFormato = Value
End Set
End Property
'propiedad para indicarle al control si pasamos el foco al siguiente
control al llegar al maximo de caracteres
Property PasarAlCompletar() As Boolean
Get
Return bolPasarAlCompletar
End Get
Set(ByVal Value As Boolean)
bolPasarAlCompletar = Value
End Set
End Property
'propiedad para indicarle al control si pasamos el foco al siguiente
control al llegar al maximo de caracteres
Property PegarDesdePortapapeles() As Boolean
Get
Return bolPegarDesdePortapapeles
End Get
Set(ByVal Value As Boolean)
bolPegarDesdePortapapeles = Value
End Set
End Property
'propiedad para si al entrar al control debe seleccionar el texto
Property SeleccionarTexto() As Boolean
Get
Return bolSeleccionarTexto
End Get
Set(ByVal Value As Boolean)
bolSeleccionarTexto = Value
End Set
End Property
'propiedad que sirver para indicarle el formato de salida del control
Private Shadows Property EsNumerico() As Boolean
Get
Return bolEsNumerico
End Get
Set(ByVal Value As Boolean)
bolEsNumerico = Value
End Set
End Property
'propiedad para si al entrar al control debe seleccionar el texto
Property FormatoPersonalizado() As String
Get
Return strFormatoPersonalizado
End Get
Set(ByVal Value As String)
strFormatoPersonalizado = Value
End Set
End Property
' propiedad para indicarle que color va tener el control cuando este
seleccionado
Property BackColorSeleccionado() As Color
' Retrieves the value of the private variable colBColor.
Get
Return colSeleccionado
End Get
' Stores the selected value in the private variable colBColor, and
' updates the backcolor of the label control lblDisplay.
Set(ByVal Value As Color)
colSeleccionado = Value
'Me.BackColor = colSeleccionado
End Set
End Property
' propiedad para indicarle que color va tener el control cuando este
seleccionado
Property BackColorDeshabilitado() As Color
' Retrieves the value of the private variable colBColor.
Get
Return colDeshabilitado
End Get
' Stores the selected value in the private variable colBColor, and
' updates the backcolor of the label control lblDisplay.
Set(ByVal Value As Color)
colDeshabilitado = Value
If Me.Enabled Then
Me.BackColor = colBackColor
Else
Me.BackColor = colDeshabilitado
End If
End Set
End Property
' propiedad para indicarle que color de fondo normalmente
Private Shadows Property BackColor() As Color
' Retrieves the value of the private variable colBColor.
Get
Return colBackColor
End Get
' Stores the selected value in the private variable colBColor, and
' updates the backcolor of the label control lblDisplay.
Set(ByVal Value As Color)
colBackColor = Value
End Set
End Property
' propiedad para indicarle que color de font
Private Shadows Property ColorFont() As Color
' Retrieves the value of the private variable colBColor.
Get
Return colFont
End Get
' Stores the selected value in the private variable colBColor, and
' updates the backcolor of the label control lblDisplay.
Set(ByVal Value As Color)
colFont = Value
End Set
End Property
'propiedad que sirver para indicarle el formato de salida del control
Private Shadows Property SeparadorMiles() As Char
Get
Return charMiles
End Get
Set(ByVal Value As Char)
charMiles = Value
End Set
End Property
'propiedad que sirver para indicarle el formato de salida del control
Private Shadows Property PuntoDecimal() As Char
Get
Return charDecimal
End Get
Set(ByVal Value As Char)
charDecimal = Value
End Set
End Property
Private Sub HiperVOX_GotFocus(ByVal sender As Object, ByVal e As
System.EventArgs) Handles MyBase.GotFocus
colBackColor = Me.BackColor
Me.BackColor = colSeleccionado
If Not bolPegarDesdePortapapeles Then
Clipboard.SetDataObject("", False)
End If
If bolSeleccionarTexto Then
Me.SelectAll()
End If
End Sub
Private Sub HiperVOX_LostFocus(ByVal sender As Object, ByVal e As
System.EventArgs) Handles MyBase.LostFocus
Dim strText, strCantidad As String
Dim i As Integer
Dim Caracter As Char
Try
Me.BackColor = colBackColor
strText = Me.Text.Trim
If bolEsNumerico Then
If strText.Length = 0 Or Me.Text = "-" Then
strText = 0
End If
Select Case intFormato
Case Formatos.Moneda 'solo formatea tipo moneda la que
encuentre
Me.Text = Format(strText, "Currency")
Case Formatos.Millares 'solo formate tipo #,##0.00
Me.Text = Format(Convert.ToDecimal(strText),
"#,##0")
Case Formatos.Decimales 'solo formatea tipo ###0.00
Me.Text = Format(Convert.ToDecimal(strText),
"#,##0.00")
Case Formatos.Personalizado 'solo formatea tipo ###0.00
If strFormatoPersonalizado.Length < 3 Then
strFormatoPersonalizado = "##0.00"
For i = strText.Length To 1 Step -1
Caracter = Convert.ToChar(strText.Substring(i -
1, 1))
If IsNumeric(Caracter & strCantidad) And
Caracter <> " " Then
strCantidad = Caracter & strCantidad
End If
Next
Me.Text = Format(Convert.ToDecimal(strCantidad),
strFormatoPersonalizado)
End Select
End If
Catch ex As Exception
Debug.WriteLine("********************************************************************")
Debug.WriteLine("---- Error en control.LostFocus")
Debug.WriteLine(ex.Message)
Debug.WriteLine("--------------------------------------------------------------------")
End Try
End Sub
Private Sub HiperVOX_KeyDown(ByVal sender As Object, ByVal e As
System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
If e.KeyCode = Keys.Up Then
If bolUsarFlechas Then
Me.FindForm.SelectNextControl(sender, False, False, True,
True)
End If
ElseIf e.KeyCode = Keys.Down Then
If bolUsarFlechas Then
Me.FindForm.SelectNextControl(sender, True, False, True,
True)
End If
End If
End Sub
Private Sub HiperVOX_KeyPress(ByVal sender As Object, ByVal e As
System.Windows.Forms.KeyPressEventArgs) Handles MyBase.KeyPress
Dim Caracter As Char
Try
'revisar si presion la tecla backespace
If Asc(e.KeyChar) = Keys.Back Then
e.Handled = False
Exit Sub
End If
'revisar si toca la tecla enter
If e.KeyChar = Chr(Keys.Enter) Then
If Me.bolPasarElFoco Then 'si desea pasar el foco al
presionar enter
e.Handled = True
Me.FindForm.SelectNextControl(sender, True, False, True,
True)
End If
End If
'convertir el caracter escrito en el texbox a caracter
Caracter = Convert.ToChar(e.KeyChar)
Select Case intTipoDato
Case TiposDeDatos.EntradaLibre
Exit Sub
'**************************************************************************************
'solo deja ingresar digitos, sin punto decimal y sin el
signo negativo
Case TiposDeDatos.NumPositivos
'si la tecla no corresponde se sale
If Not ("0123456789").IndexOf(Caracter) >= 0 Then
e.Handled = True
Exit Sub
End If
'**************************************************************************************
'solo permitir ingresar positivos y el punto decimal
Case TiposDeDatos.NumPositivosConDecimales
'cambiar el punto por la coma
If charDecimal = "," Then
If e.KeyChar = "."c Then
SendKeys.Send(",")
e.Handled = True
End If
End If
'si la tecla no corresponde se sale
If Not ("0123456789" & charDecimal).IndexOf(Caracter) >=
0 Then
e.Handled = True
Exit Sub
End If
'revisar que no meta dos veces el simbolo decimal
If Caracter = charDecimal Then 'es el simbolo decimal
???
'no dejar que meta el punto decimal en un lugar que
sobrepase lo permitido
If Me.Text.Length - Me.SelectionStart >
Me.intDecimales Then
e.Handled = True
End If
If Me.Text.IndexOf(charDecimal) >= 0 Then
e.Handled = True
End If
Exit Sub
Else 'como es un numero entonces revisamos que...
'no deje meter mas decimales de los permitidos
If (Me.Text).IndexOf(charDecimal) >= 0 Then ' esta
el punto decimal???
'si esta posicionado despues del punto......
If Me.SelectionStart >
(Me.Text).IndexOf(charDecimal) Then
'no dejar meter el numero si el cupo de
decimales ya esta lleno...
If Me.Text.Length -
(Me.Text).IndexOf(charDecimal) > Me.intDecimales Then
e.Handled = True
Exit Sub
End If
End If
End If
End If
'*************************************************************************************
'dejar ingresar los digitos, el simbolo decimal y hasta
el simbolo negativo
Case TiposDeDatos.NumCualquieraConDecimales
'cambiar el punto por la coma
If charDecimal = "," Then
If e.KeyChar = "."c Then
SendKeys.Send(",")
e.Handled = True
End If
End If
'si la tecla no corresponde se sale
If Not ("0123456789-" & charDecimal).IndexOf(Caracter)
>= 0 Then
e.Handled = True
Exit Sub
End If
'revisar que no meta dos veces el simbolo decimal
If Caracter = charDecimal Then
'no dejar que meta el punto decimal en un lugar que
sobrepase lo permitido
If Me.Text.Length - Me.SelectionStart >
Me.intDecimales Then
e.Handled = True
End If
'aqui dice que no acepta el simbolo decimal otra vez
If Me.Text.IndexOf(charDecimal) >= 0 Then
e.Handled = True
End If
Exit Sub
End If
'no dejar que meta un numero detras del signo decimal
If Me.SelectionStart = 0 And
Me.Text.IndexOf("-").ToString = 0 Then
e.Handled = True
Exit Sub
End If
'revisar que no meta dos veces el signo menos
If Caracter = "-" Then
If Me.Text.IndexOf("-") >= 0 Then
e.Handled = True
Else
e.Handled = True
MyBase.Text = "-" & MyBase.Text
If Me.Text.Length = 1 Then
Me.SelectionStart = 1
Else
Me.intPosicion = Me.SelectionStart
End If
End If
Exit Sub
End If
'como es un numero entonces revisamos que...
'no deje meter mas decimales de los permitidos
If (Me.Text).IndexOf(charDecimal) >= 0 Then ' esta el
punto decimal???
'si esta posicionado despues del punto......
If Me.SelectionStart >
(Me.Text).IndexOf(charDecimal) Then
'no dejar meter el numero si el cupo de
decimales ya esta lleno...
If Me.Text.Length -
(Me.Text).IndexOf(charDecimal) > Me.intDecimales Then
e.Handled = True
Exit Sub
End If
End If
End If
'**************************************************************************************
'numeros positivos y negativos pero sin decimales
Case TiposDeDatos.NumCualquieraSinDecimales
'si la tecla no corresponde se sale
If Not ("0123456789-").IndexOf(Caracter) >= 0 Then
e.Handled = True
Exit Sub
End If
'no dejar que meta un numero detras del signo decimal
If Me.SelectionStart = 0 And
Me.Text.IndexOf("-").ToString = 0 Then
e.Handled = True
End If
'revisar que no meta dos veces el signo menos
If Caracter = "-" Then
'MessageBox.Show("menos")
If Me.Text.IndexOf("-") >= 0 Then
e.Handled = True
Else
e.Handled = True
MyBase.Text = "-" & MyBase.Text
If Me.Text.Length = 1 Then
Me.SelectionStart = 1
Else
Me.intPosicion = Me.SelectionStart
End If
End If
Exit Sub
End If
'**************************************************************************************
'solo deja escribir letras de la A-Z a-z
Case TiposDeDatos.TextoSinCaracteres,
TiposDeDatos.TextoNombrePropioPuro
If Not Char.IsLetter(Caracter) And Not
Char.IsSeparator(Caracter) And Caracter <> "'" Then
e.Handled = True
End If
End Select
Catch ex As Exception
Debug.WriteLine("********************************************************************")
Debug.WriteLine("---- Error en control.keypress")
Debug.WriteLine(ex.Message)
Debug.WriteLine("--------------------------------------------------------------------")
End Try
End Sub
Private Sub HiperVOX_EnabledChanged(ByVal sender As Object, ByVal e As
System.EventArgs) Handles MyBase.EnabledChanged
If Me.Enabled Then
Me.BackColor = colBackColor
Else
Me.BackColor = colDeshabilitado
End If
End Sub
Private Sub HiperVOX_TextChanged(ByVal sender As Object, ByVal e As
System.EventArgs) Handles MyBase.TextChanged
If Me.bolPasarAlCompletar Then
If Me.Text.Length = Me.MaxLength Then
Me.FindForm.SelectNextControl(sender, True, False, True,
True)
End If
End If
If (Me.intTipoDato = TiposDeDatos.TextoNombrePropio Or
Me.intTipoDato = TiposDeDatos.TextoNombrePropioPuro) And Me.CharacterCasing
= CharacterCasing.Normal Then
Dim intPosicion1 As Integer = Me.SelectionStart
With Me
.Text = StrConv(.Text, VbStrConv.ProperCase)
.SelectionStart = intPosicion1
End With
End If
If intPosicion > 0 Then
Me.SelectionStart = intPosicion + 1
intPosicion = 0
End If
If Me.NegativoEnRojo Then
If DarNumero() < 0 Then
Me.ForeColor = Color.Red
Else
Me.ForeColor = Me.colFont
End If
End If
End Sub
Public Function DarNumero() As Decimal
Dim strCantidad, strText As String
Dim Caracter As Char
Dim i As Integer
Try
strCantidad = ""
strText = Me.Text.Trim
If strText.Length = 0 Then
Return 0
Exit Function
End If
If strText = "-" Then
Return 0
Exit Function
End If
Select Case Me.FormatoDeSalida
Case Formatos.Decimales
strCantidad = Format(Convert.ToDecimal(strText),
"##0.00") * 1
Case Formatos.Millares
strCantidad = Format(Convert.ToDecimal(strText),
"#,##0.00") * 1
Case Formatos.Moneda
strCantidad = Format(strText, "Currency") * 1
Case Formatos.Personalizado
'Debug.WriteLine("Personalizado antes " & strText & " --
" & strFormatoPersonalizado)
For i = strText.Length To 1 Step -1
Caracter = Convert.ToChar(strText.Substring(i - 1,
1))
If IsNumeric(Caracter & strCantidad) And Caracter <>
" " Then
strCantidad = Caracter & strCantidad
End If
Next
Case Else
Caracter = Convert.ToChar(strText.Substring(i, 1))
If Caracter = "-" Then
strCantidad = "-"
End If
For i = 0 To strText.Length - 1
Caracter = Convert.ToChar(strText.Substring(i, 1))
If Char.IsDigit(Caracter) Or Caracter = charDecimal
Then
strCantidad = strCantidad & Caracter
' Debug.WriteLine(Caracter & " " & strCantidad)
End If
Next
End Select
DarNumero = Convert.ToDecimal(strCantidad)
Return DarNumero
Catch ex As Exception
Debug.WriteLine("********************************************************************")
Debug.WriteLine("---- Error en control. Funcion DarNumero")
Debug.WriteLine(ex.Message)
Debug.WriteLine("--------------------------------------------------------------------")
End Try
End Function
Public Function DarComillas() As String
Try
If Me.Text.Length = 0 Then DarComillas = ""
DarComillas = Replace(Me.Text.Trim, "'", "''")
DarComillas = "'" & DarComillas & "'"
Catch ex As Exception
DarComillas = strTexto
End Try
End Function
End Class
"SoftJa�n" <grupo_n...@softjaen.es> escribi� en el mensaje de
noticias:eLLng2VY...@TK2MSFTNGP02.phx.gbl...
> __________ Informaci�n de ESET Smart Security, versi�n de la base de
> firmas de virus 4601 (20091112) __________
>
> ESET Smart Security ha comprobado este mensaje.
>
> http://www.eset.com
>
>
>
__________ Informaci�n de ESET Smart Security, versi�n de la base de firmas de virus 4601 (20091112) __________
ESET Smart Security ha comprobado este mensaje.
Hola
Lord Voldemort, tambien te agradesco el que hayas compartido tu codigo
y creo que me va aser de mucha utilidad.
Saludos.
Y que suite de controles es ?
--
Un Saludo, V�ctor Koch
"Lord Voldemort" <lordvol...@ggggmaillll.com> escribi� en el mensaje
news:81751A18-9562-4852...@microsoft.com...
saludos
"Victor Koch" <v i c t o r (arroba)correo(punto)waldbott(punto)com(punto)ar>
escribi� en el mensaje de noticias:uG6iULIZ...@TK2MSFTNGP05.phx.gbl...
> firmas de virus 4605 (20091113) __________
>
> ESET Smart Security ha comprobado este mensaje.
>
> http://www.eset.com
>
>
>
__________ Informaci�n de ESET Smart Security, versi�n de la base de firmas de virus 4605 (20091113) __________