Posted on 2011-05-01 09:54
acpeng 阅读(4568)
评论(1) 编辑 收藏 引用 所属分类:
MFC/SDK编程
最近写一个小的对话框程序时,想加一个文本超链接,研究了一下,发上自己的研究成果,供大家参考。下面说说完整的步骤。
(假定静态文本ID为ID_STATIC)
首先,设置鼠标的形状及响应鼠标点击
第一步,在Dlg类中定义一个protect成员变量HCURSOR m_hCursor,
在构造函数里(或者在OnInitDialog()里)调用语句
m_hCursor=AfxGetApp()->LoadCursor(IDI_CURLINK);加载鼠标;
第二步,在Dlg类中定义一个protect成员变量RECT m_StaticRect,表示静态文本的坐标,在成员函数OnInitDialog()里调用语句
GetDlgItem(IDC_STATIC)->GetWindowRect(&m_StaticRect);
ScreenToClient(&m_StaticRect);
第三步,加载鼠标移动消息,在OnMouseMove()里调用语句
if( point.x > m_StaticRect.left && point.x < m_StaticRect.right &&
point.y > m_StaticRect.top && point.y < m_StaticRect.bottom )

{
SetCursor(m_hCursor);
}
第四步,加载鼠标单击消息,在OnLButtonDown()里添加语句
if( point.x > m_StaticRect.left && point.x < m_StaticRect.right &&point.y > m_StaticRect.top && point.y < m_StaticRect.bottom )


{
SetCursor(m_hCursor);
ShellExecute(NULL,"open",TEXT("http://www.tlu.edu.cn"),NULL,NULL, SW_SHOWNORMAL);
}
注意,若是邮箱,则改为ShellExecute(NULL, "open",_T("mailto:apeng332@sohu.com"), NULL, NULL, SW_SHOWNORMAL);
在鼠标单击抬起的时候最好也加上SetCursor(m_hCursor);使得鼠标的移动更流畅,鼠标右键消息也可以加上SetCursor(m_hCursor)。
其次,设置静态文本的字体与颜色
第一步,字体的设置:在Dlg类中定义一个protect成员变量CFont m_Font表示字体,在类的成员函数OnInitDialog()里调用m_Font.CreateFont(……),注意参数很多,参考MSDN。接着编写两行代码:
CStatic *m_static=(CStatic *)GetDlgItem(IDC_STATIC);
m_static->SetFont(&m_Font,false);
第二步,颜色的设置:在Dlg中加载WM_CTLCOLOR消息,在此消息的响应函数OnCtlColor(……)里添加如下代码:
HBRUSH CScreenShotsDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)


{
HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
if (pWnd->GetDlgCtrlID() == IDC_STATIC)

{
pDC->SetTextColor(RGB(255, 0, 0));
}
return hbr;
}
即可