![]() |
![]() |
| Paypal | FTP | CCD | Buscar | Trucos | Trabajo | Foros |
|
|||||||
| Registrarse | FAQ | Miembros | Calendario | Guía de estilo | Buscar | Temas de Hoy | Marcar Foros Como Leídos |
![]() |
|
|
Herramientas | Buscar en Tema | Desplegado |
|
|
|
#1
|
||||
|
||||
|
Aquí si le veo sentido:
Código:
const char* wrongKey = "|°¬!\"#$%&/()='?\\¿¡@´¨+*~{[^}]`<>,;.:-";
//---------------------------------------------------------------------------
// Limpiar Edit ingreso de nombre
void __fastcall TForm1::FormCreate(TObject *Sender)
{
Edit1->Clear();
Edit2->Clear();
Edit3->Clear();
}
//---------------------------------------------------------------------------
// Verificar en escritura
void VerifyKey(TObject *Sender, char &Key)
{
TEdit *ed = static_cast<TEdit*>(Sender);
if((ed->SelStart+ed->SelLength == 0 && isdigit(Key)) ||
StrPos(wrongKey, String(Key).c_str()) != NULL)
Key=0;
}
//---------------------------------------------------------------------------
// Verificar por copiado/pegado
void VerifyOnPaste(TObject *Sender)
{
TEdit *ed = static_cast<TEdit*>(Sender);
for(int i = 1; i <= ed->Text.Length();i++)
if (StrPos(wrongKey, ed->Text.c_str()+i) != NULL || isdigit(ed->Text[1])) {
MessageBox(Application->Handle,AnsiString("Una cadena no válida fue pegada en " + ed->Name + ".\nRevísela antes de continuar.").c_str(),"Atención",MB_OK | MB_ICONERROR);
ed->SetFocus();
}
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Edit1KeyPress(TObject *Sender, char &Key)
{
VerifyKey(Sender,Key);
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Edit2KeyPress(TObject *Sender, char &Key)
{
VerifyKey(Sender,Key);
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Edit3KeyPress(TObject *Sender, char &Key)
{
VerifyKey(Sender,Key);
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Edit1Exit(TObject *Sender)
{
VerifyOnPaste(Sender);
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Edit2Exit(TObject *Sender)
{
VerifyOnPaste(Sender);
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Edit3Exit(TObject *Sender)
{
VerifyOnPaste(Sender);
}
//---------------------------------------------------------------------------
Última edición por aguml fecha: 06-09-2014 a las 18:50:46. |
|
#2
|
||||
|
||||
|
Hola aguml.
Cita:
Código:
void __fastcall TForm1::Edit1KeyPress(TObject *Sender, char &Key)
{
TEdit *ed = static_cast<TEdit*>(Sender);
if((ed->SelStart+ed->SelLength == 0 && Key>=0x30 && Key<=0x39) ||
StrPos(wrongKey, String(Key).c_str()) != NULL)
Key=0;
}
Lo mismo cuenta para la función miembro "Edit1Exit". Saludos ![]()
__________________
Daniel Didriksen Guía de estilo - Uso de las etiquetas - La otra guía de estilo .... |
|
#3
|
||||
|
||||
|
pues tienes toda la razon, no habia pensado en esa opcion. En ese caso seria mejor crearnos un nombre mas estandar pero es algo simplemente porque el nombre no haga referencia a un tedit, solo eso. Por ejemplo EditKeyPress y EditExit.
|
|
#4
|
||||
|
||||
|
ecfisa tu código para cuando sales del TEdit tiene algo mal, he estado mirandolo y yo al final lo he dejado así y funciona:
Código:
// Verificar por copiado/pegado
// El mismo evento lo asignamos a todos los TEdits que queramos filtrar
void __fastcall TForm1::EditsExit(TObject *Sender)
{
TEdit *ed = static_cast<TEdit*>(Sender);
//Si el TEdit no está vacío entramos
if(ed->Text != "")
{
//Si el primer caracter es un número en este caso no nos vale la cadena pegada
if(isdigit(ed->Text[1])){
MessageBox(Application->Handle,AnsiString("Una cadena no válida fue pegada en " + ed->Name + ".\nRevísela antes de continuar.").c_str(),"Atención",MB_OK | MB_ICONERROR);
ed->SetFocus();
}else{
//Si el primer caracter no es numérico comprobamos que la cadena no contenga caracteres inválidos para nuestro propósito recorriendola entera
for(int i = 1; i <= ed->Text.Length();i++)
{
if (StrPos(wrongKey, String(ed->Text[i]).c_str()) != NULL) {
MessageBox(Application->Handle,AnsiString("Una cadena no válida fue pegada en " + ed->Name + ".\nRevísela antes de continuar.").c_str(),"Atención",MB_OK | MB_ICONERROR);
ed->SetFocus();
break;
}
}
}
}
}
//---------------------------------------------------------------------------
Corrijeme en lo que veas que estoy equivocado. |
|
#5
|
||||
|
||||
|
Hola aguml.
Si tenes razón, la función falla en el caso que comentas. Y la tuya también lo hace cuando detecta un error al salir del Edit. Luego de mostrar el mensaje y asignarle nuevamente el foco y estándo el texto selecionado, permite la introducción de un número ya que los valores de SelStart y SelLength no son actualizados. Sin embargo, pude comprobar que se simplifica el tratamiento con el uso de String: Código:
...
String wrongChar = "|°¬!\"#$%&/()='?\\¿¡@´¨+*~{[^}]`<>,;.:-";
void __fastcall TForm1::FormCreate(TObject *Sender)
{
for(int i=0;i < ComponentCount; i++)
if(Components[i]->ClassNameIs("TEdit"))
(static_cast<TEdit*>(Components[i]))->Clear();
}
void __fastcall TForm1::EditKeyPress(TObject *Sender, char &Key)
{
TEdit *ed = static_cast<TEdit*>(Sender);
if(ed->SelStart+ed->SelLength == 0 && (char)Key>='0' && (char)Key<='9' ||
wrongChar.AnsiPos((char)Key)!=0) {
MessageBeep(MB_ICONERROR);
Key=0;
}
}
void __fastcall TForm1::EditExit(TObject *Sender)
{
TEdit *ed = static_cast<TEdit*>(Sender);
bool invalid = false;
if(ed->Text == "") return;
if(ed->Text[1]>='0'&&ed->Text[1]<='9'|| wrongChar.AnsiPos(ed->Text[1])!=0)
invalid = true;
for(int i = 2; i <= ed->Text.Length(); i++)
if(wrongChar.AnsiPos(ed->Text[i]))
invalid = true;
if (invalid) {
MessageBeep(MB_ICONERROR);
ed->SetFocus();
ed->SelStart = 0;
ed->SelLength = 0;
}
}
![]()
__________________
Daniel Didriksen Guía de estilo - Uso de las etiquetas - La otra guía de estilo .... |
|
#6
|
||||
|
||||
|
interesante. Mañana lo pruebo y te cuento.
|
|
#7
|
||||
|
||||
|
Bien, me ha servido para orientarme en mi código y ver otro fallo más. ¿qué pasa si seleccionamos el primer caracter o un rango que contenga el primer caracter y pulsamos un número? pues que el número se escribe porque SelLength no es igual a 0 y lo he solucionando cambiando el == por un >= y con eso da igual la cantidad de caracteres que seleccione que si el primer caracter es uno de ellos no dejará que se introduzca un número.
Así quedó mi código: Código:
const char* wrongKey = "|°¬!\"#$%&/()='?\\¿¡@´¨+*~{[^}]`<>,;.:-";
//---------------------------------------------------------------------------
// Verificar en escritura
// El mismo evento lo asignamos a todos los TEdits que queramos filtrar
void __fastcall TForm1::EditsKeyPress(TObject *Sender, char &Key)
{
TEdit *ed = static_cast<TEdit*>(Sender);
// Si es el primer caracter o si hay una seleccion que abarque al primer caracter
// y este es numérico o si la tecla pulsada es uno de los caracteres prohibidos
// evitamos que se imprima el caracter
if((ed->SelStart == 0 && ed->SelLength >= 0 && isdigit(Key)) ||
StrPos(wrongKey, String(Key).c_str()) != NULL)
{
Key=0;
MessageBeep(0);
}
}
//---------------------------------------------------------------------------
// Verificar por copiado/pegado
// El mismo evento lo asignamos a todos los TEdits que queramos filtrar
void __fastcall TForm1::EditsExit(TObject *Sender)
{
TEdit *ed = static_cast<TEdit*>(Sender);
bool invalid = false;
// Si el TEdit no está vacío entramos
if(ed->Text != "")
{
// Si el primer caracter es un número en este caso no nos vale la cadena pegada
if(isdigit(ed->Text[1])){
invalid = true;
}else{
// Si el primer caracter no es numérico comprobamos que la cadena no contenga caracteres inválidos para nuestro propósito recorriendola entera
for(int i = 1; i <= ed->Text.Length();i++)
{
if (StrPos(wrongKey, String(ed->Text[i] ).c_str()) != NULL) {
// Si se encuentra un caracter inválido
invalid = true;
// Salimos del bucle
break;
}
}
}
if(invalid)
{
// Mostramos un mensaje avisando
MessageBox(Application->Handle,AnsiString("Una cadena no válida fue pegada en " + ed->Name + ".\nRevísela antes de continuar.").c_str(),"Atención",MB_OK | MB_ICONERROR);
// Devolvemos el foco al TEdit que contiene la cadena inválida
ed->SetFocus();
ed->SelStart = 0;
ed->SelLength = 0;
}
}
}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormCreate(TObject *Sender)
{
//Limpiamos todos los TEdits
for(int i=0;i < ComponentCount; i++)
if(Components[i]->ClassNameIs("TEdit"))
(static_cast<TEdit*>(Components[i]))->Clear();
}
//---------------------------------------------------------------------------
|
![]() |
| Herramientas | Buscar en Tema |
| Desplegado | |
|
|
Temas Similares
|
||||
| Tema | Autor | Foro | Respuestas | Último mensaje |
| nombres de tablas en un SP | akela | Conexión con bases de datos | 2 | 14-12-2007 21:11:34 |
| Propiedad tableName,al criterio | look | SQL | 2 | 16-10-2007 01:54:32 |
| ¿Que componentes usar para tablas Paradox? | h2o_mx | Tablas planas | 5 | 18-05-2006 18:14:38 |
| Consejo para manejar tablas Paradox | Coco_jac | Varios | 8 | 17-11-2005 17:27:17 |
| como bloquear para borrar en tablas Paradox | Mario1980 | Varios | 4 | 01-12-2004 15:17:51 |
|