adspace


Code for Small C++ Class to Transform Any Static Control
into a Hyperlink Control?

Answer Posted / Rahul Chandra

To transform any static control into a hyperlink in C++, you can use the `SetWindowLongPtr()` function to set a custom window procedure and handle the `WM_LBUTTONDOWN` message:n```cppn#include <windows.h>n#include <shlobj.h>nnclass HyperlinkStatic : public CWindow {npublic:n HyperlinkStatic(HWND parent) : CWindow(parent, WC_STATIC) {n SetLongPtr(GWLP_USERDATA, reinterpret_cast<LONG_PTR>(this));n RegisterClass();n }nprivate:n static LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {n auto hWndUserData = GetWindowLongPtr(hwnd, GWLP_USERDATA);n if (hWndUserData == reinterpret_cast<LONG_PTR>(this)) {n if (message == WM_LBUTTONDOWN) {n POINT pt;n GetCursorPos(&pt);n ScreenToClient(hwnd, &pt);n const auto range = GetTextRange();n SendMessage(hwnd, EM_EXSETSEL, 0, MAKELPARAM(range.cpMin, range.cpMax));n OpenURL(this);n }n }n return DefWindowProc(hwnd, message, wParam, lParam);n }n void RegisterClass() {n WNDCLASSEXW wcex;n ZeroMemory(&wcex, sizeof(wcex));n wcex.cbSize = sizeof(wcex);n wcex.style = CS_OWNDC | CS_HREDRAW | CS_VREDRAW;n wcex.lpfnWndProc = WndProc;n wcex.hInstance = GetModuleHandle(nullptr);n wcex.lpszClassName = TEXT("HyperlinkStatic");n RegisterClassEx(wcex);n }n void OpenURL(HWND hwnd) const {n const auto textRange = GetTextRange();n if (textRange.cpMin <= textRange.cpMax) {n IShellLink* psl;n CoCreateInstance(CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&psl));n PWSTR url = nullptr;n if (SUCCEEDED(psl->SetPath(textRange.chrg.cpMin, &url))) {n IFACEMETHODCALLMACRO(psl, SetAttributes, DWORD(LNK_INVISIBLE | LNK_NOREPRESENTATION), 0);n CoTaskMemFree(url);n }n psl->Release();n }n }n TEXTMETRICW textMetrics;n CHARRANGE textRange = {0};n void GetTextRange() {n if (GetTextLength(&textRange.cpMax) > 0) {n GetText(textRange.chrg, &textMetrics, CFM_TEXT);n textRange.cpMax += textRange.cpMin + textMetrics.tmAveCharWidth;n }n }n};n``

Is This Answer Correct ?    0 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

Question 1: Implement a base class Appointment and derived classes Onetime, Daily, Weekly, and Monthly. An appointment has a description (for example, “see the dentist”) and a date and time. Write a virtual function occurs_on(int year, int month, int day) that checks whether the appointment occurs on that date. For example, for a monthly appointment, you must check whether the day of the month matches. Then fill a vector of Appointment* with a mixture of appointments. Have the user enter a date and print out all appointments that happen on that date. *This Should Be Done IN C++

1271