HyperLink.cpp 12 KB

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