CURLLinkButton - 可自定义的超链接控件
一个 CButton 派生的超链接控件,带内置工具提示

引言
CURLLinkButton 类通过提供 URL 链接的支持来扩展 CButton 的功能。它显示 URL 链接并在单击时调用 shell。您可以在项目中将其用于链接到任何 URL,例如您的网站、应用程序、文件夹或您的电子邮件。您也可以像使用其他按钮一样,显示一个 messagebox、dialogbox 或您想要的任何内容。
这是一个超链接控件,其功能实际上与 Internet Explorer® 中使用的超链接控件相同,具有以下特性:
- 可以插入到任何对话框、窗体或视图中
- 链接到任何 URL 和电子邮件
- 包含内置的工具提示
- 自定义显示的文本、URL 前缀、URL、工具提示文本
- 自定义超链接的颜色(常规、悬停、已访问)和工具提示的颜色(文本颜色、背景颜色)
- 使用自定义光标或使用标准手形光标
- 将 URL 链接按钮的大小调整为按钮标题的大小
- 可以使用键盘进行焦点、导航和激活
- 单击时向父窗口发送消息
- 易于理解,易于使用
感谢 Niek Albers 提供 _TrackMouseEvent()。感谢 Paul DiLascia 提供来自 WinHlp32 的默认手形光标。
Using the Code
代码非常短小、可重用且易于理解。要在您的项目中使用的此控件,您需要
- 将 URLLinkButton.h 和 URLLinkButton.cpp 添加到您的项目中
- 在定义控件的头文件中包含 URLLinkButton.h
- 将一些按钮添加到对话框或窗体中。为每个您想要自定义为超链接控件的按钮添加一个成员变量。将这些变量的类型从 CButton替换为CURLLinkButton。
- 使用以下运算符自定义控件
//Resize a URL link button to the size of the button's caption
void SizeToContent();
//Customize the colors of Hyperlink 
void SetLinkColor(COLORREF clrRegular, COLORREF clrHover, COLORREF clrVisited);
//Customize the colors of the Tooltip
void SetToolTipColor(COLORREF clrTextColor, COLORREF clrBkColor);
//Customize the tooltip text. Use default tooltip if sTip is empty
void SetToolTipText(CString sTip=_T(""));
// Set URL. By default, window text will be used
void SetURL (LPCTSTR lpszURL);
//Set URL prefix. For example "mailto:"
void SetURLPrefix (LPCTSTR lpszPrefix); 
如果您的项目中包含光标资源,您可以自定义光标,或者可以使用默认的手形光标
#if(WINVER >= 0x0500)
    //Load system hand cursor
    m_hCursorHand = AfxGetApp()->LoadCursor (IDC_HAND); 
#else
    // Use a custom Hand cursor
    // Must add a cursor resourse in the project with ID: IDC_CURSOR_HAND
    //m_hCursorHand = AfxGetApp()->LoadCursor (IDC_CURSOR_HAND);
    // If you haven't the cursor resource in your project
    // load default hand cursor from WinHlp32 module with ID=106
    TCHAR szWindowsDir[MAX_PATH];
    GetWindowsDirectory(szWindowsDir ,MAX_PATH);
    strcat(szWindowsDir,"\\Winhlp32.exe");
    HMODULE hModule = LoadLibrary(szWindowsDir); 
    if (hModule)
        m_hCursorHand = ::LoadCursor(hModule, MAKEINTRESOURCE(106));
#endif 
当单击链接按钮时,将调用 ShellExecute 来打开 URL。如果这失败,它将向父窗口发送一个注册消息。
const UINT WM_LINK_CLICKED = ::RegisterWindowMessage (_T ("WM_LINK_CLICKED"));
您可以创建父窗口的消息处理程序,以便在单击超链接时执行任何您想要的操作。例如
afx_msg LRESULT OnLinkCliked(WPARAM wParam, LPARAM lParam);
ON_REGISTERED_MESSAGE(WM_LINK_CLICKED, OnLinkCliked)
LRESULT CURLLinkDlg::OnLinkCliked(WPARAM wParam, LPARAM lParam)
{
   UINT nLinkID = (UINT)wParam;
   switch(nLinkID)
   {
     case IDOK:
          OnOK();
     break;
     case IDC_SHOW_MESSAGE:
          MessageBox(_T("Hope you find this code useful!"));
     break;
   }
   return 0;
}
历史
- 2004 年 7 月 18 日- 首次向 The Code Project 公开发布
 
- 2005 年 3 月 2 日- 修复了内存泄漏
- 修复了在调用链接上的 Return 键以显示 dialogbox时的无限循环问题。您现在不需要选中链接按钮的“所有者绘制”选项
 




