How to add a hyperlink to my dialog?
October 28th, 2004 by Andrey Yatsyk

Question

I need to place a hyperlink to my dialog and to handle clicks on this link in my application code. How can I do it?

Answer

You can simulate a link in dialog by a number of ways. First of all you can draw a link text on screen in WM_PAINT handler. You should select desired (most probably underlined) font into dialog device context, and draw link text to dialog. Your OnPaint method should contain code like this:

CFont* pOldFont = dc.SelectObject(&m_fontUnderlined);
dc.SetTextColor(rgbLinkColor);
dc.DrawText(strFirstLinkText, m_rtFirstLink, 0);
dc.SelectObject(pOldFont);

Also don’t forget to check does stylus pressed inside link text. This could be done in WM_LBUTTONDOWN handler:

if (m_rtFirstLink.PtInRect(point)) {
//link activated
}

Link rectangle should be calculated in advance:

CFont* pOldFont = dc.SelectObject(&m_fontUnderlined);
CSize szFirstLinkSize = dc.GetTextExtent(strFirstLinkText);
m_rtFirstLink = CRect(
CPoint(rectClient.left+(rectClient.Width()-szFirstLinkSize.cx)/2,
rectClient.top+50), szFirstLinkSize);

The other way is to use custom drawn static control. You should set underlined font in this static:

GetDlgItem(IDC_LINK_2)->SetFont(&m_fontUnderlined);

For font color changing you should handle WM_CTLCOLOR message and update color in provided device context:

HBRUSH CTestHyperlinkDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);

if (pWnd->GetDlgCtrlID()==IDC_LINK_2) {
pDC->SetTextColor(rgbLinkColor);
}

return hbr;
}

Link activation is received through BN_CLICKED notification in dialog. Ensure that Notify check box is set in link static styles. It is responsible for SS_NOTIFY style.
Also you can use controls that supports links, such as RichInk or HTML Viewer controls. RichInk supports EM_INSERTLINKS message for link insertion and HTML Viewer could be fed with html code. Please, look at related resources section of this article for mere information.
You can download a sample program that uses a number of approaches discussed in this article. This is a eVC4 MFC dialog based application. In case of pure WinAPI application implementation details will change but these approaches still apply.

Related resources:

Section: User Interface
Section: HTML in Programs
QA: How to create a colored button?
Article: Developing in C++ with the HTML Viewer Control
Article: EM_INSERTLINKS message
Article: Using Rich Ink Technology in Microsoft Windows CE 3.0

(Discuss in forum)

Leave a Reply