RichEdit超链接

原文:http://ccrun.com/

首先在Form上放置一个RichEdit。


在窗体的构造函数中添加以下代码:
__fastcall TMainForm::TMainForm(TComponent* Owner)
        : TForm(Owner)
{
    unsigned mask = SendMessage(RichEdit1->Handle, EM_GETEVENTMASK, 0, 0);
    SendMessage(RichEdit1->Handle, EM_SETEVENTMASK, 0, mask | ENM_LINK);
    SendMessage(RichEdit1->Handle, EM_AUTOURLDETECT, true, 0);  //自动检测URL

    RichEdit1->Text = "欢迎访问C++ Builder\n"
                      "网址: http://www.ccrun.com\n"
                      "偶的信箱:\n"
                      "mailto::[email protected] \n"
                      "嘿嘿\n";
}

重载窗体的WndProc

1。在.h中添加:

   protected:
      virtual void __fastcall WndProc(Messages::TMessage &Message);

2。在.cpp中添加:
//---------------------------------------------------------------------------
void __fastcall TMainForm::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(RichEdit1->Handle, EM_EXSETSEL, 0, (LPARAM)&(p->chrg));
                ShellExecute(Handle, "open", RichEdit1->SelText.c_str(), 0, 0, SW_SHOWNORMAL);
            }
        }
    }
    TForm::WndProc(Message);

}

设置任意字符串为超链接

void SetLink(bool bEnabled)
{
    ::CHARFORMAT2   cf; 
    ZeroMemory(&cf, sizeof(::CHARFORMAT2));
    cf.cbSize = sizeof(::CHARFORMAT2); 
    cf.dwMask = CFM_LINK; 
    bEnabled?(cf.dwEffects |= CFE_LINK):(cf.dwEffects &= ~CFE_LINK); 
    
    SendMessage(Form1->RichEdit1->Handle,EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&cf);
}
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
        : TForm(Owner)
{
}
//---------------------------------------------------------------------------


void __fastcall TForm1::FormCreate(TObject *Sender)
{
    RichEdit1->Clear();
    RichEdit1->Text="接收或拒绝";
    int start=RichEdit1->Text.Pos("接收");
    RichEdit1->SelStart=start-1;
    RichEdit1->SelLength=4;
    SetLink(true);


    unsigned mask = SendMessage(RichEdit1->Handle, EM_GETEVENTMASK, 0, 0);
    SendMessage(RichEdit1->Handle, EM_SETEVENTMASK, 0, mask | ENM_LINK);
}
//---------------------------------------------------------------------------
void __fastcall TForm1::WndProc(TMessage &msg)
{
  if(msg.Msg==WM_NOTIFY)
  {
        if (((LPNMHDR)msg.LParam)->code == EN_LINK)
        {
            ENLINK* p = (ENLINK *)msg.LParam;
            if (p->msg == WM_LBUTTONDOWN)
            {
                SendMessage(RichEdit1->Handle, EM_EXSETSEL, 0, (LPARAM)&(p->chrg));
                ShowMessage(RichEdit1->SelText);
            }
        }
  }
  else
  {
      TForm::WndProc(msg);
  }
}

你可能感兴趣的:(RichEdit超链接)