### Complete Split Button Dropdown Handling Example Source: https://learn.microsoft.com/en-us/windows/win32/controls/handle-the-bcn-dropdown-notification-from-a-split-button This complete example integrates all steps for handling the BCN_DROPDOWN notification. It includes checking the notification, getting coordinates, creating, populating, and displaying the menu. ```cpp case WM_NOTIFY: switch (((LPNMHDR)lParam)->code) { case BCN_DROPDOWN: { NMBCDROPDOWN* pDropDown = (NMBCDROPDOWN*)lParam; if (pDropDown->hdr.hwndFrom = GetDlgItem(hDlg, IDC_SPLIT)) { // Get screen coordinates of the button. POINT pt; pt.x = pDropDown->rcButton.left; pt.y = pDropDown->rcButton.bottom; ClientToScreen(pDropDown->hdr.hwndFrom, &pt); // Create a menu and add items. HMENU hSplitMenu = CreatePopupMenu(); AppendMenu(hSplitMenu, MF_BYPOSITION, IDC_MENUCOMMAND1, L"Menu item 1"); AppendMenu(hSplitMenu, MF_BYPOSITION, IDC_MENUCOMMAND2, L"Menu item 2"); // Display the menu. TrackPopupMenu(hSplitMenu, TPM_LEFTALIGN | TPM_TOPALIGN, pt.x, pt.y, 0, hDlg, NULL); return TRUE; } break; } } return FALSE; } ``` -------------------------------- ### Example TranslateDispatch Implementation Source: https://learn.microsoft.com/en-us/windows/win32/controls/translatedispatch An example implementation of the TranslateDispatch callback function. This specific example handles WM_KEYDOWN messages to perform custom keyboard actions. ```cpp BOOL CALLBACK TranslateDispatchCallback(LPMSG lpmsg) { BOOL fResult = FALSE; if (lpmsg->message == WM_KEYDOWN) { // Perform custom keyboard actions here. fResult = TRUE; } return fResult; } ``` -------------------------------- ### Complete .theme File Example Source: https://learn.microsoft.com/en-us/windows/win32/controls/themesfileformat-overview This example demonstrates the structure and various sections of a complete .theme file, including theme settings, icon definitions, cursor configurations, desktop backgrounds, sound events, slideshow settings, and visual styles. ```ini [Theme] DisplayName=My Current Theme BrandImage=c:\Fabrikam\brand.png ; Computer [CLSID\{20D04FE0-3AEA-1069-A2D8-08002B30309D}\DefaultIcon] DefaultValue=%SystemRoot%\System32\imageres.dll,-109 ; Documents [CLSID\{59031A47-3F72-44A7-89C5-5595FE6B30EE}\DefaultIcon] DefaultValue=%SystemRoot%\System32\shell32.dll,-235 ; Network [CLSID\{F02C1A0D-BE21-4350-88B0-7367FC96EF3C}\DefaultIcon] DefaultValue=%SystemRoot%\System32\imageres.dll,-25 ; Recycle Bin [CLSID\{645FF040-5081-101B-9F08-00AA002F954E}\DefaultIcon] Full=%SystemRoot%\System32\imageres.dll,-54 Empty=%SystemRoot%\System32\imageres.dll,-55 [Control Panel\Cursors] Arrow= Help= AppStarting= Wait= NWPen= No= SizeNS= SizeWE= Crosshair= IBeam= SizeNWSE= SizeNESW= SizeAll= UpArrow= DefaultValue=Windows default [Control Panel\Desktop] Wallpaper=%ProgramFiles%\fabrikam\wallpaper\ocean.jpg TileWallpaper=0 WallpaperStyle=2 Pattern= ScreenSaveActive=0 [AppEvents\Schemes\Apps\.Default\.Default] DefaultValue=%WinDir%\media\ding.wav [AppEvents\Schemes\Apps\.Default\AppGPFault] DefaultValue= [AppEvents\Schemes\Apps\.Default\Maximize] DefaultValue= [AppEvents\Schemes\Apps\.Default\MenuCommand] DefaultValue= [AppEvents\Schemes\Apps\.Default\MenuPopup] DefaultValue= [AppEvents\Schemes\Apps\.Default\Minimize] DefaultValue= [AppEvents\Schemes\Apps\.Default\Open] DefaultValue= [AppEvents\Schemes\Apps\.Default\RestoreDown] DefaultValue= [AppEvents\Schemes\Apps\.Default\RestoreUp] DefaultValue= [AppEvents\Schemes\Apps\.Default\RingIn] DefaultValue= [AppEvents\Schemes\Apps\.Default\Ringout] DefaultValue= [AppEvents\Schemes\Apps\.Default\SystemAsterisk] DefaultValue=%WinDir%\media\chord.wav [AppEvents\Schemes\Apps\.Default\SystemDefault] DefaultValue= [AppEvents\Schemes\Apps\.Default\SystemExclamation] DefaultValue=%WinDir%\media\chord.wav [AppEvents\Schemes\Apps\.Default\SystemExit] DefaultValue= [AppEvents\Schemes\Apps\.Default\SystemHand] DefaultValue=%WinDir%\media\chord.wav [AppEvents\Schemes\Apps\.Default\SystemQuestion] DefaultValue=%WinDir%\media\chord.wav [AppEvents\Schemes\Apps\.Default\SystemStart] DefaultValue= [AppEvents\Schemes\Apps\Explorer\EmptyRecycleBin] DefaultValue=%WinDir%\media\ding.wav [AppEvents\Schemes\Apps\.Default\Close] DefaultValue= [Slideshow] Interval=1800000 Shuffle=1 ImagesRootPath=%ProgramFiles%\fabrikam\wallpaper Item0Path=%ProgramFiles%\fabrikam\wallpaper\ocean.jpg Item1Path=%ProgramFiles%\fabrikam\wallpaper\mountain.jpg Item2Path=%ProgramFiles%\fabrikam\wallpaper\river.jpg [boot] SCRNSAVE.EXE=%WinDir%\System32\bubbles.scr [MasterThemeSelector] MTSM=DABJDKT ThemeColorBPP=4 [VisualStyles] Path=%SystemRoot%\resources\Themes\Aero\Aero.msstyles ColorStyle=NormalColor Size=NormalSize ColorizationColor=0x856E3BA1 Transparency=1 ``` -------------------------------- ### Example ReaderScroll Callback Implementation Source: https://learn.microsoft.com/en-us/windows/win32/controls/readerscroll An example implementation of the ReaderScroll callback function. This function handles scrolling the reader mode window based on the provided dx and dy parameters. It returns TRUE on success. ```cpp BOOL CALLBACK ReaderScrollCallback(PREADERMODEINFO prmi, int dx, int dy) { if (prmi == NULL) return FALSE; // Call custom ScrollWindow method to scroll the window ScrollWindow(prmi->hwnd, dx, dy); return TRUE; } ``` -------------------------------- ### Create and Initialize Application Window Source: https://learn.microsoft.com/en-us/windows/win32/controls/create-a-simple-combo-box Sets up the window class and creates the main application window, including DPI scaling for consistent sizing. ```cpp wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wcex.lpszMenuName = NULL; wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.lpszClassName = TEXT("DemoApp"); RegisterClassEx(&wcex); // Create the application window. // // Because the CreateWindow function takes its size in pixels, we // obtain the system DPI and use it to scale the window size. int dpiX = 0; int dpiY = 0; HDC hdc = GetDC(NULL); if (hdc) { dpiX = GetDeviceCaps(hdc, LOGPIXELSX); dpiY = GetDeviceCaps(hdc, LOGPIXELSY); ReleaseDC(NULL, hdc); } m_hwnd = CreateWindow( TEXT("DemoApp"), TEXT("Simple Combo Box Example"), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, static_cast(ceil(640.f * dpiX / 96.f)), static_cast(ceil(480.f * dpiY / 96.f)), NULL, NULL, HINST_THISCOMPONENT, this ); hr = m_hwnd ? S_OK : E_FAIL; if (SUCCEEDED(hr)) { ShowWindow(m_hwnd, SW_SHOWNORMAL); UpdateWindow(m_hwnd); } ``` -------------------------------- ### Edit_GetHilite Source: https://learn.microsoft.com/en-us/windows/win32/controls/bumper-edit-control-reference-macros Gets the start and end character positions of the current selection. ```APIDOC ## Edit_GetHilite ### Description Retrieves the starting and ending character positions of the currently selected text within the edit control. ### Method Edit_GetHilite ### Parameters None ### Response Returns the start and end character positions of the selection. ``` -------------------------------- ### Edit_GetSel Source: https://learn.microsoft.com/en-us/windows/win32/controls/bumper-edit-control-reference-macros Gets the starting and ending character positions of the current text selection. ```APIDOC ## Edit_GetSel ### Description Retrieves the starting and ending character positions of the currently selected text within the edit control. ### Method Edit_GetSel ### Parameters None ### Response Returns a DWORD where the low-order word is the starting position and the high-order word is the ending position of the selection. ``` -------------------------------- ### SimpleComboBox.cpp - Main Application Logic Source: https://learn.microsoft.com/en-us/windows/win32/controls/create-a-simple-combo-box This source file contains the main entry point (WinMain) and the implementation of the DemoApp class, including initialization, message loop, and window procedure. ```cpp // SimpleComboBox.cpp #include "SimpleComboBox.h" /****************************************************************** * * * The application entry point. * * * ******************************************************************/ int WINAPI WinMain( HINSTANCE /* hInstance */, HINSTANCE /* hPrevInstance */, LPSTR /* lpCmdLine */, int /* nCmdShow */ ) { // Ignore the return value because we want to run the program even in the // unlikely event that HeapSetInformation fails. HeapSetInformation(NULL, HeapEnableTerminationOnCorruption, NULL, 0); if (SUCCEEDED(CoInitialize(NULL))) { { DemoApp app; if (SUCCEEDED(app.Initialize())) { app.RunMessageLoop(); } } CoUninitialize(); } return 0; } /****************************************************************** * * * DemoApp::DemoApp constructor * * * * Initialize member data. * * * ******************************************************************/ DemoApp::DemoApp() : m_hwnd(NULL) { } /****************************************************************** * * * Release resources. * * * ******************************************************************/ DemoApp::~DemoApp() { // TODO: Release app resource here. } /******************************************************************* * * * Create the application window and the combobox. * * * *******************************************************************/ HRESULT DemoApp::Initialize() { HRESULT hr; // Register the window class. WNDCLASSEX wcex = { sizeof(WNDCLASSEX) }; wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = DemoApp::WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = sizeof(LONG_PTR); wcex.hInstance = HINST_THISCOMPONENT; ``` -------------------------------- ### CB_GETEDITSEL Source: https://learn.microsoft.com/en-us/windows/win32/controls/bumper-combobox-control-reference-messages Gets the starting and ending positions of the current text selection in the edit control of a combo box. ```APIDOC ## CB_GETEDITSEL ### Description Gets the starting and ending positions of the current text selection in the edit control of a combo box. ### Method Message ### Parameters #### Message Parameters - **wParam**: Pointer to a variable that receives the starting position of the selection. If no text is selected, this value is the caret position. - **lParam**: Pointer to a variable that receives the ending position of the selection. If no text is selected, this value is the caret position. ### Return Value If the message succeeds, the return value is the length of the selection in characters. If no text is selected, the return value is the caret position. Otherwise, it is CB_ERR. ``` -------------------------------- ### Define and Launch a Wizard Property Sheet (C++) Source: https://learn.microsoft.com/en-us/windows/win32/controls/wizards This example demonstrates initializing a PROPSHEETHEADER structure for a Wizard97-style wizard with watermark and header graphics, then launching the wizard. Ensure g_hInstance and ahpsp are properly defined. ```cpp // g_hInstance is the global HINSTANCE of the application. // ahpsp is an array of HPROPSHEETPAGE handles. PROPSHEETHEADER psh = { sizeof(psh) }; psh.hInstance = g_hInstance; psh.hwndParent = NULL; psh.phpage = ahpsp; psh.dwFlags = PSH_WIZARD97 | PSH_WATERMARK | PSH_HEADER; psh.pszbmWatermark = MAKEINTRESOURCE(IDB_WATERMARK); psh.pszbmHeader = MAKEINTRESOURCE(IDB_BANNER); psh.nStartPage = 0; psh.nPages = 4; PropertySheet(&psh); ``` -------------------------------- ### Edit_GetSel Source: https://learn.microsoft.com/en-us/windows/win32/controls/edit-controls Gets the starting and ending character positions of the current selection in an edit or rich edit control. This macro can be used as an alternative to sending the EM_GETSEL message. ```APIDOC ## Edit_GetSel ### Description Gets the starting and ending character positions of the current selection in an edit or rich edit control. ### Method Macro ### Endpoint N/A ### Parameters None ### Request Example N/A ### Response Returns the starting and ending character positions of the selection. ### Response Example N/A ``` -------------------------------- ### Create Text Host and Text Services Instance Source: https://learn.microsoft.com/en-us/windows/win32/controls/create-windowless-rich-edit-controls This code demonstrates the initialization of the text host and text services objects. Ensure the TextHost object is correctly implemented and that the CreateTextServices function is available. ```cpp HRESULT hr; IUnknown* pUnk = NULL; ITextServices* pTextServices = NULL; // Create an instance of the application-defined object that implements the ITextHost interface. TextHost* pTextHost = new TextHost(); if (pTextHost == NULL) goto errorHandler; // Create an instance of the text services object. hr = CreateTextServices(NULL, pTextHost, &pUnk); if (FAILED(hr)) goto errorHandler; // Retrieve the IID_ITextServices interface identifier from Msftedit.dll. IID* pIID_ITS = (IID*) (VOID*) GetProcAddress(hmodRichEdit, "IID_ITextServices"); // Retrieve the ITextServices interface. hr = pUnk->QueryInterface(*pIID_ITS, (void **)&pTextServices); if (FAILED(hr)) goto errorHandler; ``` -------------------------------- ### EM_GETSEL Source: https://learn.microsoft.com/en-us/windows/win32/controls/edit-controls Gets the starting and ending character positions (in TCHARs) of the current selection in an edit control. This message can be sent to either an edit control or a rich edit control. ```APIDOC ## EM_GETSEL ### Description Retrieves the start and end positions of the current text selection in an edit control. ### Method Message ### Parameters - **LPARAM** (PLONG) - A pointer to a LONG that receives the ending position of the selection. If no text is selected, this value is the same as the starting position. ### Response - **Return Value** (DWORD) - The low-order word is the starting character position of the selection. The high-order word is the ending character position of the selection. ``` -------------------------------- ### Complete InsertObject Function Example Source: https://learn.microsoft.com/en-us/windows/win32/controls/using-rich-edit-com This function demonstrates inserting an OLE object into a rich edit control. It includes error handling and setup for OLE interfaces and storage. ```cpp BOOL InsertObject(HWND hRichEdit, LPCTSTR pszFileName) { HRESULT hr; LPRICHEDITOLE pRichEditOle; SendMessage(hRichEdit, EM_GETOLEINTERFACE, 0, (LPARAM)&pRichEditOle); if (pRichEditOle == NULL) { return FALSE; } LPLOCKBYTES pLockBytes = NULL; hr = CreateILockBytesOnHGlobal(NULL, TRUE, &pLockBytes); if (FAILED(hr)) { return FALSE; } LPSTORAGE pStorage; hr = StgCreateDocfileOnILockBytes(pLockBytes, STGM_SHARE_EXCLUSIVE | STGM_CREATE | STGM_READWRITE, 0, &pStorage); if (FAILED(hr)) { return FALSE; } FORMATETC formatEtc; formatEtc.cfFormat = 0; formatEtc.ptd = NULL; formatEtc.dwAspect = DVASPECT_CONTENT; formatEtc.lindex = -1; formatEtc.tymed = TYMED_NULL; LPLOCKBYTES pLockBytes = NULL; hr = CreateILockBytesOnHGlobal(NULL, TRUE, &pLockBytes); if (FAILED(hr)) { return FALSE; } LPSTORAGE pStorage; hr = StgCreateDocfileOnILockBytes(pLockBytes, STGM_SHARE_EXCLUSIVE | STGM_CREATE | STGM_READWRITE, 0, &pStorage); if (FAILED(hr)) { return FALSE; } FORMATETC formatEtc; formatEtc.cfFormat = 0; formatEtc.ptd = NULL; formatEtc.dwAspect = DVASPECT_CONTENT; formatEtc.lindex = -1; formatEtc.tymed = TYMED_NULL; LPOLECLIENTSITE pClientSite; hr = pRichEditOle->GetClientSite(&pClientSite); if (FAILED(hr)) { return FALSE; } LPUNKNOWN pUnk; CLSID clsid = CLSID_NULL; hr = OleCreateFromFile(clsid, pszFileName, IID_IUnknown, OLERENDER_DRAW, &formatEtc, pClientSite, pStorage, (void**)&pUnk); pClientSite->Release(); if (FAILED(hr)) { return FALSE; } LPOLEOBJECT pObject; hr = pUnk->QueryInterface(IID_IOleObject, (void**)&pObject); pUnk->Release(); if (FAILED(hr)) { return FALSE; } OleSetContainedObject(pObject, TRUE); REOBJECT reobject = { sizeof(REOBJECT)}; hr = pObject->GetUserClassID(&clsid); if (FAILED(hr)) { pObject->Release(); return FALSE; } reobject.clsid = clsid; reobject.cp = REO_CP_SELECTION; reobject.dvaspect = DVASPECT_CONTENT; reobject.dwFlags = REO_RESIZABLE | REO_BELOWBASELINE; reobject.dwUser = 0; reobject.poleobj = pObject; reobject.polesite = pClientSite; reobject.pstg = pStorage; SIZEL sizel = { 0 }; reobject.sizel = sizel; SendMessage(hRichEdit, EM_SETSEL, 0, -1); DWORD dwStart, dwEnd; SendMessage(hRichEdit, EM_GETSEL, (WPARAM)&dwStart, (LPARAM)&dwEnd); SendMessage(hRichEdit, EM_SETSEL, dwEnd+1, dwEnd+1); SendMessage(hRichEdit, EM_REPLACESEL, TRUE, (WPARAM)L"\n"); hr = pRichEditOle->InsertObject(&reobject); pObject->Release(); pRichEditOle->Release(); if (FAILED(hr)) { return FALSE; } return TRUE; } ``` -------------------------------- ### Create a Simple Toolbar with System Icons (C++) Source: https://learn.microsoft.com/en-us/windows/win32/controls/create-toolbars Creates a toolbar with standard system icons and enables the 'New' and 'Open' buttons while disabling 'Save'. Requires Win32 API knowledge. ```cpp HIMAGELIST g_hImageList = NULL; HWND CreateSimpleToolbar(HWND hWndParent) { // Declare and initialize local constants. const int ImageListID = 0; const int numButtons = 3; const int bitmapSize = 16; const DWORD buttonStyles = BTNS_AUTOSIZE; // Create the toolbar. HWND hWndToolbar = CreateWindowEx(0, TOOLBARCLASSNAME, NULL, WS_CHILD | TBSTYLE_WRAPABLE, 0, 0, 0, 0, hWndParent, NULL, g_hInstance, NULL); if (hWndToolbar == NULL) return NULL; // Create the image list. g_hImageList = ImageList_Create(bitmapSize, bitmapSize, // Dimensions of individual bitmaps. ILC_COLOR16 | ILC_MASK, // Ensures transparent background. numButtons, 0); // Set the image list. SendMessage(hWndToolbar, TB_SETIMAGELIST, (WPARAM)ImageListID, (LPARAM)g_hImageList); // Load the button images. SendMessage(hWndToolbar, TB_LOADIMAGES, (WPARAM)IDB_STD_SMALL_COLOR, (LPARAM)HINST_COMMCTRL); // Initialize button info. // IDM_NEW, IDM_OPEN, and IDM_SAVE are application-defined command constants. TBBUTTON tbButtons[numButtons] = { { MAKELONG(STD_FILENEW, ImageListID), IDM_NEW, TBSTATE_ENABLED, buttonStyles, {0}, 0, (INT_PTR)L"New" }, { MAKELONG(STD_FILEOPEN, ImageListID), IDM_OPEN, TBSTATE_ENABLED, buttonStyles, {0}, 0, (INT_PTR)L"Open"}, { MAKELONG(STD_FILESAVE, ImageListID), IDM_SAVE, 0, buttonStyles, {0}, 0, (INT_PTR)L"Save"} }; // Add buttons. SendMessage(hWndToolbar, TB_BUTTONSTRUCTSIZE, (WPARAM)sizeof(TBBUTTON), 0); SendMessage(hWndToolbar, TB_ADDBUTTONS, (WPARAM)numButtons, (LPARAM)&tbButtons); // Resize the toolbar, and then show it. SendMessage(hWndToolbar, TB_AUTOSIZE, 0, 0); ShowWindow(hWndToolbar, TRUE); return hWndToolbar; } ``` -------------------------------- ### LVN_BEGINSCROLL Notification Code Example Source: https://learn.microsoft.com/en-us/windows/win32/controls/lvn-beginscroll This code snippet shows how to access the NMLVSCROLL structure when the LVN_BEGINSCROLL notification is received. The structure contains the scroll operation's starting position. ```cpp LVN_BEGINSCROLL pnmLVScroll = (LPNMLVSCROLL) lParam; ``` -------------------------------- ### Create Command Link Button Instance Source: https://learn.microsoft.com/en-us/windows/win32/controls/create-a-command-link Use CreateWindow with the BS_COMMANDLINK style to create a command link button. Ensure the parent window and instance handle are correctly provided. ```C++ HWND hwndCommandLink = CreateWindow( L"BUTTON", // Predefined class; Unicode assumed L"", // Text will be defined later WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_COMMANDLINK, // Styles 200, // x position 10, // y position 100, // Button width 100, // Button height m_hwnd, // Parent window NULL, // No menu (HINSTANCE)GetWindowLongPtr(m_hwnd, GWLP_HINSTANCE), NULL); // Pointer not needed ``` -------------------------------- ### Set and Get State Image Index - Win32 Source: https://learn.microsoft.com/en-us/windows/win32/controls/using-treeview Properly set and retrieve the state image index for tree-view items. The examples assume two states (unchecked and checked) and may require modification for more states. ```c++ #include #include // Assume hwndTreeView is the handle to the tree-view control // Assume hti is the handle to the tree-view item // To set the state image index (e.g., checked) // TVIS_STATEIMAGEMASK is used to set the state image // The index is typically 1-based for checked, 0-based for unchecked TreeView_SetItemState(hwndTreeView, hti, INDEXTOSTATEIMAGEMASK(2), TVIS_STATEIMAGEMASK); // To get the state image index TVITEM item; item.mask = TVIF_STATE; TreeView_GetItem(hwndTreeView, &item); // Extract the state image index (1-based) int stateImageIndex = (item.state & TVIS_STATEIMAGEMASK) >> 12; ``` -------------------------------- ### Initialize Tree-View Image Lists (C++) Source: https://learn.microsoft.com/en-us/windows/win32/controls/initialize-the-image-list Creates an image list, adds bitmaps to it, and associates the image list with a tree-view control. Ensure global variables and constants like g_hInst, image indexes, and bitmap dimensions are defined. ```cpp BOOL InitTreeViewImageLists(HWND hwndTV) { HIMAGELIST himl; // handle to image list HBITMAP hbmp; // handle to bitmap // Create the image list. if ((himl = ImageList_Create(CX_BITMAP, CY_BITMAP, FALSE, NUM_BITMAPS, 0)) == NULL) return FALSE; // Add the open file, closed file, and document bitmaps. hbmp = LoadBitmap(g_hInst, MAKEINTRESOURCE(IDB_OPEN_FILE)); g_nOpen = ImageList_Add(himl, hbmp, (HBITMAP)NULL); DeleteObject(hbmp); hbmp = LoadBitmap(g_hInst, MAKEINTRESOURCE(IDB_CLOSED_FILE)); g_nClosed = ImageList_Add(himl, hbmp, (HBITMAP)NULL); DeleteObject(hbmp); hbmp = LoadBitmap(g_hInst, MAKEINTRESOURCE(IDB_DOCUMENT)); g_nDocument = ImageList_Add(himl, hbmp, (HBITMAP)NULL); DeleteObject(hbmp); // Fail if not all of the images were added. if (ImageList_GetImageCount(himl) < 3) return FALSE; // Associate the image list with the tree-view control. TreeView_SetImageList(hwndTV, himl, TVSIL_NORMAL); return TRUE; } ``` -------------------------------- ### Handle WM_THEMECHANGED Message Source: https://learn.microsoft.com/en-us/windows/win32/controls/using-visual-styles When your control receives a WM_THEMECHANGED message, call CloseThemeData to close the existing theme handle and OpenThemeData to get the theme handle to the newly loaded visual style. This example assumes g_hTheme is a global handle to the theme. ```cpp case WM_THEMECHANGED: CloseThemeData (g_hTheme); g_hTheme = OpenThemeData (hwnd, L"MyClassName"); ``` -------------------------------- ### Begin Tree-View Item Drag Operation in C++ Source: https://learn.microsoft.com/en-us/windows/win32/controls/drag-a-tree-view-item Initiates a drag operation for a tree-view item. This function uses TreeView_CreateDragImage to get a drag image, ImageList_BeginDrag to start the drag, and ImageList_DragEnter to display the image. It also captures mouse input and hides the cursor. ```cpp // Begin dragging an item in a tree-view control. // hwndTV - handle to the image list. // lpnmtv - address of information about the item being dragged. // // g_fDragging -- global BOOL that specifies whether dragging is underway. void Main_OnBeginDrag(HWND hwndTV, LPNMTREEVIEW lpnmtv) { HIMAGELIST himl; // handle to image list RECT rcItem; // bounding rectangle of item // Tell the tree-view control to create an image to use // for dragging. himl = TreeView_CreateDragImage(hwndTV, lpnmtv->itemNew.hItem); // Get the bounding rectangle of the item being dragged. TreeView_GetItemRect(hwndTV, lpnmtv->itemNew.hItem, &rcItem, TRUE); // Start the drag operation. ImageList_BeginDrag(himl, 0, 0, 0); ImageList_DragEnter(hwndTV, lpnmtv->ptDrag.x, lpnmtv->ptDrag.x); // Hide the mouse pointer, and direct mouse input to the // parent window. ShowCursor(FALSE); SetCapture(GetParent(hwndTV)); g_fDragging = TRUE; return; } ``` -------------------------------- ### Configure Desktop Background in Theme File Source: https://learn.microsoft.com/en-us/windows/win32/controls/themesfileformat-overview Use the [Control Panel\Desktop] section to specify the wallpaper path and display style. The path can point to various image formats. ```ini [Control Panel\Desktop] Wallpaper=%WinDir%\web\wallpaper\Windows\img0.jpg ; The path to the wallpaper picture can point to a ; .bmp, .gif, .jpg, .png, or .tif file. TileWallpaper=0 ; 0: The wallpaper picture should not be tiled ; 1: The wallpaper picture should be tiled WallpaperStyle=2 ; 0: The image is centered if TileWallpaper=0 or tiled if TileWallpaper=1 ; 2: The image is stretched to fill the screen ; 6: The image is resized to fit the screen while maintaining the aspect ratio. (Windows 7 and later) ; 10: The image is resized and cropped to fill the screen while maintaining the aspect ratio. (Windows 7 and later) ``` -------------------------------- ### Draw Button Control with Visual Styles Source: https://learn.microsoft.com/en-us/windows/win32/controls/using-visual-styles This example demonstrates how to draw a button control using visual styles. It opens a theme, draws the background and text, and then closes the theme. Fallback code should be used if visual styles are not available. ```C++ HTHEME hTheme = NULL; hTheme = OpenThemeData(hwndButton, L"Button"); // ... DrawMyControl(hDC, hwndButton, hTheme, iState); // ... if (hTheme) { CloseThemeData(hTheme); } void DrawMyControl(HDC hDC, HWND hwndButton, HTHEME hTheme, int iState) { RECT rc, rcContent; TCHAR szButtonText[255]; HRESULT hr; size_t cch; GetWindowRect(hwndButton, &rc); GetWindowText(hwndButton, szButtonText, (sizeof(szButtonText) / sizeof(szButtonText[0])+1)); hr = StringCchLength(szButtonText, (sizeof(szButtonText) / sizeof(szButtonText[0])), &cch); if (hTheme) { hr = DrawThemeBackground(hTheme, hDC, BP_PUSHBUTTON, iState, &rc, 0); if (SUCCEEDED(hr)) { hr = GetThemeBackgroundContentRect(hTheme, hDC, BP_PUSHBUTTON, iState, &rc, &rcContent); } if (SUCCEEDED(hr)) { hr = DrawThemeText(hTheme, hDC, BP_PUSHBUTTON, iState, szButtonText, cch, DT_CENTER | DT_VCENTER | DT_SINGLELINE, 0, &rcContent); } } else { // Draw the control without using visual styles. } } ``` -------------------------------- ### Print Rich Edit Control Contents Source: https://learn.microsoft.com/en-us/windows/win32/controls/printing-rich-edit-controls This function prints the contents of a rich edit control to the specified printer. It handles document setup, page formatting, and iterative printing of content. Ensure the HDC is valid and obtained correctly, for example, using PrintDlg. ```C++ // hwnd is the HWND of the rich edit control. // hdc is the HDC of the printer. This value can be obtained for the // default printer as follows: // // PRINTDLG pd = { sizeof(pd) }; // pd.Flags = PD_RETURNDC | PD_RETURNDEFAULT; // // if (PrintDlg(&pd)) // { // HDC hdc = pd.hDC; // ... // } BOOL PrintRTF(HWND hwnd, HDC hdc) { DOCINFO di = { sizeof(di) }; if (!StartDoc(hdc, &di)) { return FALSE; } int cxPhysOffset = GetDeviceCaps(hdc, PHYSICALOFFSETX); int cyPhysOffset = GetDeviceCaps(hdc, PHYSICALOFFSETY); int cxPhys = GetDeviceCaps(hdc, PHYSICALWIDTH); int cyPhys = GetDeviceCaps(hdc, PHYSICALHEIGHT); // Create "print preview". SendMessage(hwnd, EM_SETTARGETDEVICE, (WPARAM)hdc, cxPhys/2); FORMATRANGE fr; fr.hdc = hdc; fr.hdcTarget = hdc; // Set page rect to physical page size in twips. fr.rcPage.top = 0; fr.rcPage.left = 0; fr.rcPage.right = MulDiv(cxPhys, 1440, GetDeviceCaps(hDC, LOGPIXELSX)); fr.rcPage.bottom = MulDiv(cyPhys, 1440, GetDeviceCaps(hDC, LOGPIXELSY)); // Set the rendering rectangle to the printable area of the page. fr.rc.left = cxPhysOffset; fr.rc.right = cxPhysOffset + cxPhys; fr.rc.top = cyPhysOffset; fr.rc.bottom = cyPhysOffset + cyPhys; SendMessage(hwnd, EM_SETSEL, 0, (LPARAM)-1); // Select the entire contents. SendMessage(hwnd, EM_EXGETSEL, 0, (LPARAM)&fr.chrg); // Get the selection into a CHARRANGE. BOOL fSuccess = TRUE; // Use GDI to print successive pages. while (fr.chrg.cpMin < fr.chrg.cpMax && fSuccess) { fSuccess = StartPage(hdc) > 0; if (!fSuccess) break; int cpMin = SendMessage(hwnd, EM_FORMATRANGE, TRUE, (LPARAM)&fr); if (cpMin <= fr.chrg.cpMin) { fSuccess = FALSE; break; } fr.chrg.cpMin = cpMin; fSuccess = EndPage(hdc) > 0; } SendMessage(hwnd, EM_FORMATRANGE, FALSE, 0); if (fSuccess) { EndDoc(hdc); } else { AbortDoc(hdc); } return fSuccess; } ``` -------------------------------- ### TBN_SAVE Notification Code Example Source: https://learn.microsoft.com/en-us/windows/win32/controls/tbn-save This code snippet shows how to handle the TBN_SAVE notification. The application receives this notification code once at the start of the save process and once for each button. This gives an opportunity to add custom information to that saved by the Shell. If no custom information is to be added, the notification code can be ignored. ```C++ TBN_SAVE lpnmtb = (LPNMTBSAVE) lParam; ``` -------------------------------- ### Create Tab Control and Add Tabs (C++) Source: https://learn.microsoft.com/en-us/windows/win32/controls/create-a-tab-control-in-the-main-window Creates a tab control, sizes it to fit the parent window's client area, and adds tabs for each day of the week. Requires initialization of common controls and uses string resources for tab labels. ```cpp #define DAYS_IN_WEEK 7 // Creates a tab control, sized to fit the specified parent window's client // area, and adds some tabs. // Returns the handle to the tab control. // hwndParent - parent window (the application's main window). // HOWND DoCreateTabControl(HWND hwndParent) { RECT rcClient; INITCOMMONCONTROLSEX icex; HWND hwndTab; TCITEM tie; int i; TCHAR achTemp[256]; // Temporary buffer for strings. // Initialize common controls. icex.dwSize = sizeof(INITCOMMONCONTROLSEX); icex.dwICC = ICC_TAB_CLASSES; InitCommonControlsEx(&icex); // Get the dimensions of the parent window's client area, and // create a tab control child window of that size. Note that g_hInst // is the global instance handle. GetClientRect(hwndParent, &rcClient); hwndTab = CreateWindow(WC_TABCONTROL, L"", WS_CHILD | WS_CLIPSIBLINGS | WS_VISIBLE, 0, 0, rcClient.right, rcClient.bottom, hwndParent, NULL, g_hInst, NULL); if (hwndTab == NULL) { return NULL; } // Add tabs for each day of the week. tie.mask = TCIF_TEXT | TCIF_IMAGE; tie.iImage = -1; tie.pszText = achTemp; for (i = 0; i < DAYS_IN_WEEK; i++) { // Load the day string from the string resources. Note that // g_hInst is the global instance handle. LoadString(g_hInst, IDS_SUNDAY + i, achTemp, sizeof(achTemp) / sizeof(achTemp[0])); if (TabCtrl_InsertItem(hwndTab, i, &tie) == -1) { DestroyWindow(hwndTab); return NULL; } } return hwndTab; } ``` -------------------------------- ### SimpleComboBox.h - Header File Source: https://learn.microsoft.com/en-us/windows/win32/controls/create-a-simple-combo-box This header file defines the necessary structures, macros, and class declarations for the DemoApp, including utility functions like SafeRelease and Assert. ```cpp // SimpleComboBox.h // Windows Header Files: #include #include // C RunTime Header Files #include #include /****************************************************************** * * * Macros * * * ******************************************************************/ template inline void SafeRelease( Interface **ppInterfaceToRelease ) { if (*ppInterfaceToRelease != NULL) { (*ppInterfaceToRelease)->Release(); (*ppInterfaceToRelease) = NULL; } } #ifndef Assert #if defined( DEBUG ) || defined( _DEBUG ) #define Assert(b) if (!(b)) {OutputDebugStringA("Assert: " #b "\n");} #else #define Assert(b) #endif //DEBUG || _DEBUG #endif #ifndef HINST_THISCOMPONENT EXTERN_C IMAGE_DOS_HEADER __ImageBase; #define HINST_THISCOMPONENT ((HINSTANCE)&__ImageBase) #endif /****************************************************************** * * * DemoApp * * * ******************************************************************/ class DemoApp { public: DemoApp(); ~DemoApp(); HRESULT Initialize(); void RunMessageLoop(); private: HRESULT CreateResources(); void DiscardResources(); static LRESULT CALLBACK WndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam ); private: HWND m_hwnd; }; ``` -------------------------------- ### Retrieve selection range using CB_GETEDITSEL Source: https://learn.microsoft.com/en-us/windows/win32/controls/cb-geteditsel This example demonstrates two methods for obtaining the current selection range in a combo box's edit control using the CB_GETEDITSEL message. The first method uses output parameters to store the start and end positions, while the second method retrieves the range from the message's return value. ```cpp DWORD start, end; // Get the range from [out] parameters. // hwnd is the handle of the combo box control. SendMessage(hwnd, CB_GETEDITSEL, (WPARAM)&start, (LPARAM)&end; // Get the range from the return value. DWORD range = SendMessage(hwnd, CB_GETEDITSEL, NULL, NULL); start = LOWORD(range); end = HIWORD(range); ``` -------------------------------- ### Win32 Application Entry Point and Initialization Source: https://learn.microsoft.com/en-us/windows/win32/controls/create-an-up-down-control This C++ code defines the entry point for a Win32 application, handles window creation, message dispatching, and initializes common controls required for the Up-Down control. ```cpp #include "UpDown.h" #include #pragma comment(lib, "C:\\Program Files\\Microsoft SDKs\\Windows\\v7.1\\Lib\\ComCtl32.Lib") #pragma comment(linker,"\"/manifestdependency:type = 'win32' \ name = 'Microsoft.Windows.Common-Controls' \ version = '6.0.0.0' \ processorArchitecture = '*' \ publicKeyToken = '6595b64144ccf1df' \ language = '*'\"") #define MAX_LOADSTRING 100 HINSTANCE g_hInst; TCHAR g_szTitle[MAX_LOADSTRING]; TCHAR g_szWindowClass[MAX_LOADSTRING]; INITCOMMONCONTROLSEX icex; const UINT valMin=0; const UINT valMax=100; RECT rcClient; UINT cyVScroll; HWND hControl = NULL; HWND hwndGroupBox = NULL; HWND hwndLabel = NULL; HWND hwndUpDnEdtBdy = NULL; HWND hwndUpDnCtl = NULL; HWND hwndProgBar = NULL; HWND CreateGroupBox(HWND); HWND CreateLabel(HWND); HWND CreateUpDnBuddy(HWND); HWND CreateUpDnCtl(HWND); HWND CreateProgBar(HWND); LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); INT_PTR CALLBACK UpDownDialogProc(HWND, UINT, WPARAM, LPARAM); ATOM MyRegisterClass(HINSTANCE hInstance); BOOL InitInstance(HINSTANCE, int); int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); MSG msg; HACCEL hAccelTable; LoadString(hInstance, IDS_APP_TITLE, g_szTitle, MAX_LOADSTRING); LoadString(hInstance, IDC_UPDOWN, g_szWindowClass, MAX_LOADSTRING); MyRegisterClass(hInstance); if (!InitInstance (hInstance, nCmdShow)) return FALSE; hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_UPDOWN)); while (GetMessage(&msg, NULL, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } return (int) msg.wParam; } ATOM MyRegisterClass(HINSTANCE hInstance) { WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_UpDown)); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wcex.lpszMenuName = MAKEINTRESOURCE(IDM_MAIN); wcex.lpszClassName = g_szWindowClass; wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_UpDown)); return RegisterClassEx(&wcex); } BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) { HWND hWnd; g_hInst = hInstance; hWnd = CreateWindow(g_szWindowClass, g_szTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL); if (!hWnd) return FALSE; ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); return TRUE; } LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { UINT wmId, wmEvent; PAINTSTRUCT ps; HDC hdc; icex.dwSize = sizeof(INITCOMMONCONTROLSEX); switch (message) { case WM_CREATE: return TRUE; break; case WM_COMMAND: wmId = LOWORD(wParam); wmEvent = HIWORD(wParam); switch (wmId) { case IDM_RUN_UPDOWN: DialogBox(g_hInst, MAKEINTRESOURCE(IDD_UPDOWN), hWnd, UpDownDialogProc); break; case IDM_EXIT: ```