Scalabium Software

SMReport Autogenerated
Knowledge for your independence'.
Home Delphi and C++Builder tips

#146: Standard RichEdit component and URL highlighting

Very popular question in delphi forums is: how can I highlight URLs in RichEdit and how can I detect a mouse click in text where URL is...
And everytime I see the answers like "go to XXXX site and use this superb XXX product instead RichEdit".

Today I want to show how to implement URL highlighting and URL navigation without any third-party components. This functionality is implemented in RichEdit from Microsoft (and MS Outlook use this feature, for example) and only Borland's developers didn't publish it for us.

So what we need:
1. drop on your form a RichEdit component from win32 page of component palette

2. in OnCreate event of your form write the next code:

  mask: Integer;
  mask := SendMessage(RichEdit1.Handle, EM_GETEVENTMASK, 0, 0);
  SendMessage(RichEdit1.Handle, EM_SETEVENTMASK, 0, mask or ENM_LINK);
  SendMessage(RichEdit1.Handle, EM_AUTOURLDETECT, Integer(True), 0);

  RichEdit1.Text := 'Scalabium Software'#13#10 +
    ' Site is located at Welcome to our site.';

After that your Richedit will convert automatically any URLs in highlighted (blue color and underlined). Even if you'll start to enter any text directly in Richedit, any begings for URL will be converted too (not only existing text string but new too)

3. now we must detect mouse clicks in URL range. For this task we must override WndProc method of our form:

  TForm1 = class(TForm)
    procedure WndProc(var Message: TMessage); override;

procedure TForm1.WndProc(var Message: TMessage);
  p: TENLink;
  strURL: string;
  if (Message.Msg = WM_NOTIFY) then
    if (PNMHDR(Message.LParam).code = EN_LINK) then
      p := TENLink(Pointer(TWMNotify(Message).NMHdr)^);
      if (p.msg = WM_LBUTTONDOWN) then
        SendMessage(RichEdit1.Handle, EM_EXSETSEL, 0, LongInt(@(p.chrg)));
        strURL := RichEdit1.SelText;
        ShellExecute(Handle, 'open', PChar(strURL), 0, 0, SW_SHOWNORMAL);


Now you can compile your project (don't forget to include Richedit and ShellAPI units in uses clause) and your RichEdit component will work like a charm.

Of course, you can modify a code and process this parsed strURL as you like instead implemented navigation in browser as I did...

Published: November 6, 2002

See also
Metafile Convert
SMImport suite
Paradox to MS Access converter
Fast Document Viewer
Word Web-stream
DBISAM Password Recovery
dBase Viewer
SMMsg suite

Contact to webmaster


Borland Software Code Gear Scalabium Delphi tips

Copyright© 1998-2017, Scalabium Software. All rights reserved.

SMExport advertising