Club Builder - Foros de discusión Club Builder
Foro de C++Builder en español
 
 FAQFAQ   BuscarBuscar   MiembrosMiembros   Grupos de UsuariosGrupos de Usuarios   RegistrarseRegistrarse 
 PerfilPerfil   Entra para ver tus mensajes privadosEntra para ver tus mensajes privados   EntrarEntrar 

Palabras Resaltadas en RichEdit

 
Publicar nuevo tema   Responder al tema    Foros de discusión -> Tips & Tricks
Ver tema anterior :: Ver tema siguiente  
Autor Mensaje
Mensaje    Asunto: Palabras Resaltadas en RichEdit Responder citando

ventana en ejecución



buscando un poco por el foro y por algo de internet, existen muchas maneras de hacer un resaltado de palabras, dentro de un RichEdit

Para ello debes Crear un Nuevo Proyecto e Insertar un Componente RichEdit

y establecer el siguiente codigo en cada uno de los archivos correspondientes

ARCHIVO.CPP
Código:

//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include "uRichEdit.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
//----------------
#define USE_SETREDRAW 1 // definimos el mensaje para las letras
//-------------------
TForm1 *Form1;
//Lista de palababras a utilizar
// por el momento son 7 pero se pueden agregar mas
static const int NUMEROPALABRAS = 6;
static const char * LISTAPALABRAS[NUMEROPALABRAS] =
{
   "int",
   "char",
   "float",
   "if",
   "while",
   "for"
};
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
   : TForm(Owner)
{
   // para cuando se teclea una direccion url como ejemplo www.ccsg.com
   unsigned mask = SendMessage(this->RichEdit1->Handle,EM_GETEVENTMASK, 0, 0);
   SendMessage(this->RichEdit1->Handle, EM_SETEVENTMASK,0, mask | ENM_LINK);
   SendMessage(this->RichEdit1->Handle, EM_AUTOURLDETECT,true, 0);
}
//----------------------------------------------------------------
void __fastcall NormalizaText(HANDLE hWnd, int iFrom, int iTo)
{
   CHARRANGE charrange;
   CHARFORMAT charformat;
   charrange.cpMin = iFrom;
   charrange.cpMax = iTo;
   SendMessage(hWnd,EM_EXSETSEL,0,(LPARAM)&charrange);
   charformat.cbSize = sizeof(CHARFORMAT);
   charformat.dwMask = CFM_BOLD;
   charformat.dwEffects = 0;
   SendMessage(hWnd,EM_SETCHARFORMAT,SCF_SELECTION,(LPARAM)&charformat);
   charrange.cpMin = charrange.cpMax = iTo+1;
   SendMessage(hWnd,EM_EXSETSEL,0,(LPARAM)&charrange);
}
//-----------------------------------------------------------------------------------
void __fastcall NegritaText(HANDLE hWnd, int iFrom, int iTo)
{
   CHARRANGE charrange;
   CHARFORMAT charformat;
   charrange.cpMin = iFrom;
   charrange.cpMax = iTo;
   SendMessage(hWnd,EM_EXSETSEL,0,(LPARAM)&charrange);
   charformat.cbSize = sizeof(CHARFORMAT);
   charformat.dwMask = CFM_BOLD;
   charformat.dwEffects = CFE_BOLD;
   SendMessage(hWnd,EM_SETCHARFORMAT,SCF_SELECTION,(LPARAM)&charformat);
   charrange.cpMin = charrange.cpMax = iTo+1;
   SendMessage(hWnd,EM_EXSETSEL,0,(LPARAM)&charrange);
   charformat.cbSize = sizeof(CHARFORMAT);
   charformat.dwMask = CFM_BOLD;
   charformat.dwEffects = 0;
   SendMessage(hWnd,EM_SETCHARFORMAT,SCF_SELECTION,(LPARAM)&charformat);
}
//-----------------------------------------------------------------------------------
bool __fastcall VerificaLista(char * pSrc, int iLength) {
   int i,j;
   char ch;
   bool retval = false;
   char tempbuf[256];
   strncpy(tempbuf,pSrc,iLength);
   tempbuf[iLength] = 0;
   strlwr(tempbuf);
   for( i=0; i < NUMEROPALABRAS; i++ )
   {
      retval = (strcmp(LISTAPALABRAS[i],tempbuf)==0);
      if( retval )
      {
         break;
      }
   }
   return retval;
}
//---------------------------------------------------------------------------
int __fastcall PreparaRichEdit(HANDLE hWnd, LPSTR pTextBuf, int & Position)
{
   ::TEXTRANGE textrange;
#ifdef USE_SETREDRAW
   SendMessage(hWnd,WM_SETREDRAW,FALSE,0);
#endif
   SendMessage(hWnd,EM_EXGETSEL,0,(LPARAM)&textrange.chrg);
   textrange.chrg.cpMin = textrange.chrg.cpMax-64;
   if( textrange.chrg.cpMin < 0 )
      textrange.chrg.cpMin = 0;
   textrange.lpstrText = pTextBuf;
   SendMessage(hWnd,EM_GETTEXTRANGE,0,(LPARAM)&textrange);
   Position = textrange.chrg.cpMax;
   return textrange.chrg.cpMax-textrange.chrg.cpMin;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::HighLight(void)
{
   int iStart;
   int iLength;
   HANDLE hWnd = RichEdit1->Handle;
   int RichContentLength = GetWindowTextLength(hWnd);
   char * pContent = new char[RichContentLength];
   if( pContent != NULL )
   {
      SendMessage(hWnd,WM_SETREDRAW,FALSE,0);
      if( GetWindowText(hWnd,pContent,RichContentLength) )
      {
         char * ptr;
         iStart = 0;
         for( iLength=1; iLength > 0; iStart+=iLength )
         {
            iStart += strspn(pContent+iStart," \r\n");
            ptr = strpbrk(pContent+iStart," \r");
            if( ptr )
            {
               iLength = ptr-pContent-iStart;
            }
            else
            {
               iLength = strlen(pContent+iStart);
            }
            if( iLength > 0 )
            {
               if( VerificaLista(pContent+iStart,iLength) )
               {
                  NegritaText(hWnd,iStart,iStart+iLength);
               }
            }
         }
      }
      SendMessage(hWnd,WM_SETREDRAW,TRUE,0);
      RedrawWindow(hWnd,NULL,NULL,RDW_INVALIDATE);
      delete [] pContent;
   }
}
//---------------------------------------------------------------------------
void __fastcall TForm1::WndProc(Messages::TMessage &Message)
{
  if (Message.Msg == WM_NOTIFY)
  {
   if (((LPNMHDR)Message.LParam)->code ==EN_LINK)
   {
     ENLINK* p = (ENLINK *)Message.LParam;
     if (p->msg == WM_LBUTTONDOWN)
     {
      SendMessage(this->RichEdit1->Handle,EM_EXSETSEL, 0, (LPARAM)&(p->chrg));
      ShellExecute(this->Handle, "open",this->RichEdit1->SelText.c_str(), 0, 0,SW_SHOWNORMAL);
     }
   }
  }

  TForm::WndProc(Message);
}
//------------------------------------------------------------------------------
void __fastcall TForm1::RichEdit1KeyUp(TObject *Sender, WORD &Key,
     TShiftState Shift)
{
   int WEnd, WStart, LStart, Length;
   CHAR * ptr;
   char Mark;
   HANDLE hWnd;
   CHAR buff[256];
   hWnd = RichEdit1->Handle;
   switch( Key )
   {
      case VK_RETURN:
         Length = PreparaRichEdit(hWnd,buff,WEnd);
         if( Length > 2 )
         {
            ptr = buff+Length-2;
            if( ptr[-1] > ' ' )
            {
              Length = 0;
              for(; ptr > buff; ptr-- )
              {
                if( ptr[-1] <= ' ' )
                {
                  break;
                }
                Length += 1;
              }
              if( VerificaLista(ptr,Length) )
              {
                NegritaText(hWnd,WEnd-Length-2,WEnd);
              } else
              {
                NormalizaText(hWnd,WEnd-Length-2,WEnd);
              }
            }
         }
#ifdef USE_SETREDRAW
         SendMessage(hWnd,WM_SETREDRAW,TRUE,0);
         RedrawWindow(hWnd,NULL,NULL,RDW_INVALIDATE);
#endif
         break;
       case VK_BACK:
       case VK_SPACE:
         Length = PreparaRichEdit(hWnd,buff,WEnd);
         if( Length > 1 )
         {
            ptr = buff+Length-1;
            if( ptr[-1] > ' ' )
            {
               Length = 0;
               for(; ptr > buff; ptr-- )
               {
                  if( ptr[-1] <= ' ' )
                  {
                     break;
                  }
                  Length += 1;
               }
               if( VerificaLista(ptr,Length) )
               {
                  NegritaText(hWnd,WEnd-Length-1,WEnd-1);
               }
               else
               {
                  NormalizaText(hWnd,WEnd-Length-1,WEnd-1);
               }
            }
         }
#ifdef USE_SETREDRAW
         SendMessage(hWnd,WM_SETREDRAW,TRUE,0);
         RedrawWindow(hWnd,NULL,NULL,RDW_INVALIDATE);
#endif
         break;
     }
}
//---------------------------------------------------------------------------


Dentro del Archivo.h

Código:

//---------------------------------------------------------------------------

#ifndef uRichEditH
#define uRichEditH
//---------------------------------------------------------------------------
#include <Classes.hpp>
#include <Controls.hpp>
#include <StdCtrls.hpp>
#include <Forms.hpp>
#include <ComCtrls.hpp>
#include <Dialogs.hpp>
#include <Menus.hpp>
//---------------------------------------------------------------------------
class TForm1 : public TForm
{
__published:   // IDE-managed Components
   TRichEdit *RichEdit1;
   TOpenDialog *OpenDialog1;
   TSaveDialog *SaveDialog1;
   TMainMenu *MainMenu1;
   TMenuItem *File1;
   TMenuItem *New1;
   TMenuItem *Open1;
   TMenuItem *Close1;
   TMenuItem *N3;
   TMenuItem *Save1;
   TMenuItem *SaveAs1;
   TMenuItem *N2;
   TMenuItem *Exit1;
   TMenuItem *Compilador1;
   TMenuItem *VerificarSintaxis1;
   TMenuItem *N1;
   void __fastcall RichEdit1KeyUp(TObject *Sender, WORD &Key, TShiftState Shift);
private:   // User declarations
   void __fastcall WndProc(Messages::TMessage &Message);
public:      // User declarations
   __fastcall TForm1(TComponent* Owner);
   void __fastcall HighLight(void);
};
//---------------------------------------------------------------------------
extern PACKAGE TForm1 *Form1;
//---------------------------------------------------------------------------
#endif

_________________
Cool


Ultima edición por Cesar C. Salazar Gonzalez el Mar 16 Dic, 2008 2:16 am, editado 2 veces
Volver arriba
Ver perfil de usuario Enviar mensaje privado Enviar email MSN Messenger
Mensaje    Asunto: Responder citando

Muy bueno Cesar,

Gracias
Volver arriba
Ver perfil de usuario Enviar mensaje privado
Mensaje    Asunto: Responder citando

cesar tu ejemplo me serviria a las mil pero me da error en preparar el richedit
if( textrange.chrg.cpMin <0>Handle;
me dice que desconoce el handle???
que puedo hacer?
_________________
Todos somos ignorantes, lo que no todos ignoramos lo mismo...
Volver arriba
Ver perfil de usuario Enviar mensaje privado Enviar email
Mensaje    Asunto: Responder citando

El detalle ha sido que al poner el codigo, se han alterado las sentencias, pues se requiere "[x] Deshabilitar HTML en este mensaje"


por si no has visto el código nuevamente, en la parte que me comentas tiene el codigo correcto.

Código:
{...}
if( textrange.chrg.cpMin < 0 )
      textrange.chrg.cpMin = 0;
{....}

_________________
Cool


Ultima edición por Cesar C. Salazar Gonzalez el Mar 16 Dic, 2008 6:02 am, editado 1 vez
Volver arriba
Ver perfil de usuario Enviar mensaje privado Enviar email MSN Messenger
Mensaje    Asunto: Responder citando

Cesar gracias por responder pero amigo, no me llevo la idea ,me podrias explicar mas pausadamente porfavor?
gracias
_________________
Todos somos ignorantes, lo que no todos ignoramos lo mismo...
Volver arriba
Ver perfil de usuario Enviar mensaje privado Enviar email
Mensaje    Asunto: Responder citando

cesar si con el codigo que me das y mas especificamente con
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
// para cuando se teclea una direccion url como ejemplo www.ccsg.com
unsigned mask = SendMessage(this->RE->Handle,EM_GETEVENTMASK, 0, 0);
SendMessage(this->RE->Handle, EM_SETEVENTMASK,0, mask | ENM_LINK);
SendMessage(this->RE->Handle, EM_AUTOURLDETECT,true, 0);
}

yo deseara tomar el stilo o autodetectar el principio y fin de la url que le hago?
_________________
Todos somos ignorantes, lo que no todos ignoramos lo mismo...
Volver arriba
Ver perfil de usuario Enviar mensaje privado Enviar email
Mensaje    Asunto: Responder citando

César: Este código que has puesto, ¿valdría también para un QRRichEdit?
_________________
Un saludo

Necesitamos tu ayuda: Envía AI al 27595 (Coste 1,20 euros + IVA)
Volver arriba
Ver perfil de usuario Enviar mensaje privado Enviar email
Mensaje    Asunto: Responder citando

Angel: aun que no lo he probado, debo suponer que si, pues decienden de la misma clase "customRichedit", soy sincero no lo he probado, pero al ser funciones fuera del Componente es casi un echo que puede funcionar.
_________________
Cool
Volver arriba
Ver perfil de usuario Enviar mensaje privado Enviar email MSN Messenger
Mostrar mensajes de anteriores:   
Cambiar a:  
No puedes publicar temas nuevos en este foro
No puedes responder a temas en este foro
No puedes editar tus mensajes en este foro
No puedes borrar tus mensajes en este foro
No puedes votar en las encuestas de este foro


Hosting WordPress Indedmedia desde 3,99 €
© 2002–2026 Club Builder · Funciona con phpBB.