HyperLink.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. // HyperLink.cpp : implementation file
  2. //
  3. // HyperLink static control. Will open the default browser with the given URL
  4. // when the user clicks on the link.
  5. //
  6. // Copyright (C) 1997, 1998 Chris Maunder (chrismaunder@codeguru.com)
  7. // All rights reserved. May not be sold for profit.
  8. //
  9. // Thanks to Pål K. Tønder for auto-size and window caption changes.
  10. //
  11. // "GotoURL" function by Stuart Patterson
  12. // As seen in the August, 1997 Windows Developer's Journal.
  13. // Copyright 1997 by Miller Freeman, Inc. All rights reserved.
  14. // Modified by Chris Maunder to use TCHARs instead of chars.
  15. //
  16. // "Default hand cursor" from Paul DiLascia's Jan 1998 MSJ article.
  17. //
  18. #include "stdafx.h"
  19. #include "HyperLink.h"
  20. #ifdef _DEBUG
  21. #define new DEBUG_NEW
  22. #undef THIS_FILE
  23. static char THIS_FILE[] = __FILE__;
  24. #endif
  25. #define TOOLTIP_ID 1
  26. /////////////////////////////////////////////////////////////////////////////
  27. // CHyperLink
  28. CHyperLink::CHyperLink()
  29. {
  30. m_hLinkCursor = NULL; // No cursor as yet
  31. m_crLinkColour = RGB( 0, 0, 255); // Blue
  32. m_crVisitedColour = RGB( 255, 0, 0); // red
  33. m_crHoverColour = RGB( 0, 255, 0); //::GetSysColor(COLOR_HIGHLIGHT);
  34. m_bOverControl = FALSE; // Cursor not yet over control
  35. m_bVisited = FALSE; // Hasn't been visited yet.
  36. m_bUnderline = TRUE; // Underline the link?
  37. m_bAdjustToFit = TRUE; // Resize the window to fit the text?
  38. m_strURL.Empty();
  39. }
  40. CHyperLink::~CHyperLink()
  41. {
  42. m_Font.DeleteObject();
  43. }
  44. BEGIN_MESSAGE_MAP(CHyperLink, CStatic)
  45. //{{AFX_MSG_MAP(CHyperLink)
  46. ON_CONTROL_REFLECT(STN_CLICKED, OnClicked)
  47. ON_WM_CTLCOLOR_REFLECT()
  48. ON_WM_SETCURSOR()
  49. ON_WM_MOUSEMOVE()
  50. //}}AFX_MSG_MAP
  51. END_MESSAGE_MAP()
  52. /////////////////////////////////////////////////////////////////////////////
  53. // CHyperLink message handlers
  54. BOOL CHyperLink::PreTranslateMessage(MSG* pMsg)
  55. {
  56. m_ToolTip.RelayEvent(pMsg);
  57. return CStatic::PreTranslateMessage(pMsg);
  58. }
  59. void CHyperLink::OnClicked()
  60. {
  61. int result = (int)GotoURL(m_strURL, SW_SHOW);
  62. m_bVisited = (result > HINSTANCE_ERROR);
  63. if (!m_bVisited) {
  64. MessageBeep(MB_ICONEXCLAMATION); // Unable to follow link
  65. ReportError(result);
  66. } else
  67. SetVisited(); // Repaint to show visited colour
  68. }
  69. HBRUSH CHyperLink::CtlColor(CDC* pDC, UINT nCtlColor)
  70. {
  71. ASSERT(nCtlColor == CTLCOLOR_STATIC);
  72. if (m_bOverControl)
  73. pDC->SetTextColor(m_crHoverColour);
  74. else if (m_bVisited)
  75. pDC->SetTextColor(m_crVisitedColour);
  76. else
  77. pDC->SetTextColor(m_crLinkColour);
  78. // transparent text.
  79. pDC->SetBkMode(TRANSPARENT);
  80. return (HBRUSH)GetStockObject(NULL_BRUSH);
  81. }
  82. void CHyperLink::OnMouseMove(UINT nFlags, CPoint point)
  83. {
  84. CStatic::OnMouseMove(nFlags, point);
  85. if (m_bOverControl) // Cursor is currently over control
  86. {
  87. CRect rect;
  88. GetClientRect(rect);
  89. if (!rect.PtInRect(point))
  90. {
  91. m_bOverControl = FALSE;
  92. ReleaseCapture();
  93. RedrawWindow();
  94. return;
  95. }
  96. }
  97. else // Cursor has just moved over control
  98. {
  99. m_bOverControl = TRUE;
  100. RedrawWindow();
  101. SetCapture();
  102. }
  103. }
  104. BOOL CHyperLink::OnSetCursor(CWnd* /*pWnd*/, UINT /*nHitTest*/, UINT /*message*/)
  105. {
  106. if (m_hLinkCursor)
  107. {
  108. ::SetCursor(m_hLinkCursor);
  109. return TRUE;
  110. }
  111. return FALSE;
  112. }
  113. void CHyperLink::PreSubclassWindow()
  114. {
  115. // We want to get mouse clicks via STN_CLICKED
  116. DWORD dwStyle = GetStyle();
  117. ::SetWindowLong(GetSafeHwnd(), GWL_STYLE, dwStyle | SS_NOTIFY);
  118. // Set the URL as the window text
  119. if (m_strURL.IsEmpty())
  120. GetWindowText(m_strURL);
  121. // Check that the window text isn't empty. If it is, set it as the URL.
  122. CString strWndText;
  123. GetWindowText(strWndText);
  124. if (strWndText.IsEmpty()) {
  125. ASSERT(!m_strURL.IsEmpty()); // Window and URL both NULL. DUH!
  126. SetWindowText(m_strURL);
  127. }
  128. // Create the font
  129. LOGFONT lf;
  130. GetFont()->GetLogFont(&lf);
  131. lf.lfUnderline = m_bUnderline;
  132. m_Font.CreateFontIndirect(&lf);
  133. SetFont(&m_Font);
  134. PositionWindow(); // Adjust size of window to fit URL if necessary
  135. SetDefaultCursor(); // Try and load up a "hand" cursor
  136. // Create the tooltip
  137. CRect rect;
  138. GetClientRect(rect);
  139. m_ToolTip.Create(this);
  140. m_ToolTip.AddTool(this, m_strURL, rect, TOOLTIP_ID);
  141. CStatic::PreSubclassWindow();
  142. }
  143. /////////////////////////////////////////////////////////////////////////////
  144. // CHyperLink operations
  145. void CHyperLink::SetURL(CString strURL)
  146. {
  147. m_strURL = strURL;
  148. if (::IsWindow(GetSafeHwnd())) {
  149. PositionWindow();
  150. m_ToolTip.UpdateTipText(strURL, this, TOOLTIP_ID);
  151. }
  152. }
  153. CString CHyperLink::GetURL() const
  154. {
  155. return m_strURL;
  156. }
  157. void CHyperLink::SetColours(COLORREF crLinkColour, COLORREF crVisitedColour,
  158. COLORREF crHoverColour /* = -1 */)
  159. {
  160. m_crLinkColour = crLinkColour;
  161. m_crVisitedColour = crVisitedColour;
  162. if (crHoverColour == -1)
  163. m_crHoverColour = ::GetSysColor(COLOR_HIGHLIGHT);
  164. else
  165. m_crHoverColour = crHoverColour;
  166. if (::IsWindow(m_hWnd))
  167. Invalidate();
  168. }
  169. COLORREF CHyperLink::GetLinkColour() const
  170. {
  171. return m_crLinkColour;
  172. }
  173. COLORREF CHyperLink::GetVisitedColour() const
  174. {
  175. return m_crVisitedColour;
  176. }
  177. COLORREF CHyperLink::GetHoverColour() const
  178. {
  179. return m_crHoverColour;
  180. }
  181. void CHyperLink::SetVisited(BOOL bVisited /* = TRUE */)
  182. {
  183. m_bVisited = bVisited;
  184. if (::IsWindow(GetSafeHwnd()))
  185. Invalidate();
  186. }
  187. BOOL CHyperLink::GetVisited() const
  188. {
  189. return m_bVisited;
  190. }
  191. void CHyperLink::SetLinkCursor(HCURSOR hCursor)
  192. {
  193. m_hLinkCursor = hCursor;
  194. if (m_hLinkCursor == NULL)
  195. SetDefaultCursor();
  196. }
  197. HCURSOR CHyperLink::GetLinkCursor() const
  198. {
  199. return m_hLinkCursor;
  200. }
  201. void CHyperLink::SetUnderline(BOOL bUnderline /* = TRUE */)
  202. {
  203. m_bUnderline = bUnderline;
  204. if (::IsWindow(GetSafeHwnd()))
  205. {
  206. LOGFONT lf;
  207. GetFont()->GetLogFont(&lf);
  208. lf.lfUnderline = m_bUnderline;
  209. m_Font.DeleteObject();
  210. m_Font.CreateFontIndirect(&lf);
  211. SetFont(&m_Font);
  212. Invalidate();
  213. }
  214. }
  215. BOOL CHyperLink::GetUnderline() const
  216. {
  217. return m_bUnderline;
  218. }
  219. void CHyperLink::SetAutoSize(BOOL bAutoSize /* = TRUE */)
  220. {
  221. m_bAdjustToFit = bAutoSize;
  222. if (::IsWindow(GetSafeHwnd()))
  223. PositionWindow();
  224. }
  225. BOOL CHyperLink::GetAutoSize() const
  226. {
  227. return m_bAdjustToFit;
  228. }
  229. // Move and resize the window so that the window is the same size
  230. // as the hyperlink text. This stops the hyperlink cursor being active
  231. // when it is not directly over the text. If the text is left justified
  232. // then the window is merely shrunk, but if it is centred or right
  233. // justified then the window will have to be moved as well.
  234. //
  235. // Suggested by Pål K. Tønder
  236. void CHyperLink::PositionWindow()
  237. {
  238. if (!::IsWindow(GetSafeHwnd()) || !m_bAdjustToFit)
  239. return;
  240. // Get the current window position
  241. CRect rect;
  242. GetWindowRect(rect);
  243. CWnd* pParent = GetParent();
  244. if (pParent)
  245. pParent->ScreenToClient(rect);
  246. // Get the size of the window text
  247. CString strWndText;
  248. GetWindowText(strWndText);
  249. CDC* pDC = GetDC();
  250. CFont* pOldFont = pDC->SelectObject(&m_Font);
  251. CSize Extent = pDC->GetTextExtent(strWndText);
  252. pDC->SelectObject(pOldFont);
  253. ReleaseDC(pDC);
  254. // Get the text justification via the window style
  255. DWORD dwStyle = GetStyle();
  256. // Recalc the window size and position based on the text justification
  257. if (dwStyle & SS_CENTERIMAGE)
  258. rect.DeflateRect(0, (rect.Height() - Extent.cy)/2);
  259. else
  260. rect.bottom = rect.top + Extent.cy;
  261. if (dwStyle & SS_CENTER)
  262. rect.DeflateRect((rect.Width() - Extent.cx)/2, 0);
  263. else if (dwStyle & SS_RIGHT)
  264. rect.left = rect.right - Extent.cx;
  265. else // SS_LEFT = 0, so we can't test for it explicitly
  266. rect.right = rect.left + Extent.cx;
  267. // Move the window
  268. SetWindowPos(NULL, rect.left, rect.top, rect.Width(), rect.Height(), SWP_NOZORDER);
  269. }
  270. /////////////////////////////////////////////////////////////////////////////
  271. // CHyperLink implementation
  272. // The following appeared in Paul DiLascia's Jan 1998 MSJ articles.
  273. // It loads a "hand" cursor from the winhlp32.exe module
  274. void CHyperLink::SetDefaultCursor()
  275. {
  276. if (m_hLinkCursor == NULL) // No cursor handle - load our own
  277. {
  278. // Get the windows directory
  279. CString strWndDir;
  280. GetWindowsDirectory(strWndDir.GetBuffer(MAX_PATH), MAX_PATH);
  281. strWndDir.ReleaseBuffer();
  282. strWndDir += _T("\\winhlp32.exe");
  283. // This retrieves cursor #106 from winhlp32.exe, which is a hand pointer
  284. HMODULE hModule = LoadLibrary(strWndDir);
  285. if (hModule) {
  286. HCURSOR hHandCursor = ::LoadCursor(hModule, MAKEINTRESOURCE(106));
  287. if (hHandCursor)
  288. m_hLinkCursor = CopyCursor(hHandCursor);
  289. }
  290. FreeLibrary(hModule);
  291. }
  292. }
  293. LONG CHyperLink::GetRegKey(HKEY key, LPCTSTR subkey, LPTSTR retdata)
  294. {
  295. HKEY hkey;
  296. LONG retval = RegOpenKeyEx(key, subkey, 0, KEY_QUERY_VALUE, &hkey);
  297. if (retval == ERROR_SUCCESS) {
  298. long datasize = MAX_PATH;
  299. TCHAR data[MAX_PATH];
  300. RegQueryValue(hkey, NULL, data, &datasize);
  301. lstrcpy(retdata,data);
  302. RegCloseKey(hkey);
  303. }
  304. return retval;
  305. }
  306. void CHyperLink::ReportError(int nError)
  307. {
  308. CString str;
  309. switch (nError) {
  310. case 0: str = "The operating system is out\nof memory or resources."; break;
  311. case SE_ERR_PNF: str = "The specified path was not found."; break;
  312. case SE_ERR_FNF: str = "The specified file was not found."; break;
  313. case ERROR_BAD_FORMAT: str = "The .EXE file is invalid\n(non-Win32 .EXE or error in .EXE image)."; break;
  314. case SE_ERR_ACCESSDENIED: str = "The operating system denied\naccess to the specified file."; break;
  315. case SE_ERR_ASSOCINCOMPLETE: str = "The filename association is\nincomplete or invalid."; break;
  316. case SE_ERR_DDEBUSY: str = "The DDE transaction could not\nbe completed because other DDE transactions\nwere being processed."; break;
  317. case SE_ERR_DDEFAIL: str = "The DDE transaction failed."; break;
  318. case SE_ERR_DDETIMEOUT: str = "The DDE transaction could not\nbe completed because the request timed out."; break;
  319. case SE_ERR_DLLNOTFOUND: str = "The specified dynamic-link library was not found."; break;
  320. case SE_ERR_NOASSOC: str = "There is no application associated\nwith the given filename extension."; break;
  321. case SE_ERR_OOM: str = "There was not enough memory to complete the operation."; break;
  322. case SE_ERR_SHARE: str = "A sharing violation occurred. ";
  323. default: str.Format("Unknown Error (%d) occurred.", nError); break;
  324. }
  325. str = "Unable to open hyperlink:\n\n" + str;
  326. AfxMessageBox(str, MB_ICONEXCLAMATION | MB_OK);
  327. }
  328. HINSTANCE CHyperLink::GotoURL(LPCTSTR url, int showcmd)
  329. {
  330. TCHAR key[MAX_PATH + MAX_PATH];
  331. // First try ShellExecute()
  332. HINSTANCE result = ShellExecute(NULL, _T("open"), url, NULL,NULL, showcmd);
  333. // If it failed, get the .htm regkey and lookup the program
  334. if ((UINT)result <= HINSTANCE_ERROR) {
  335. if (GetRegKey(HKEY_CLASSES_ROOT, _T(".htm"), key) == ERROR_SUCCESS) {
  336. lstrcat(key, _T("\\shell\\open\\command"));
  337. if (GetRegKey(HKEY_CLASSES_ROOT,key,key) == ERROR_SUCCESS) {
  338. TCHAR *pos;
  339. pos = _tcsstr(key, _T("\"%1\""));
  340. if (pos == NULL) { // No quotes found
  341. pos = strstr(key, _T("%1")); // Check for %1, without quotes
  342. if (pos == NULL) // No parameter at all...
  343. pos = key+lstrlen(key)-1;
  344. else
  345. *pos = '\0'; // Remove the parameter
  346. }
  347. else
  348. *pos = '\0'; // Remove the parameter
  349. lstrcat(pos, _T(" "));
  350. lstrcat(pos, url);
  351. result = (HINSTANCE) WinExec(key,showcmd);
  352. }
  353. }
  354. }
  355. return result;
  356. }