### Example Command Message Handler Setup Source: https://learn.microsoft.com/en-us/cpp/mfc/tn006-message-maps This example demonstrates the setup for handling command, command update, and extended command messages, including resource definitions, class declarations, message map entries, and implementation. ```cpp #define ID_MYCMD 100 #define ID_COMPLEX 101 ``` ```cpp afx_msg void OnMyCommand(); afx_msg void OnUpdateMyCommand(CCmdUI* pCmdUI); afx_msg BOOL OnComplexCommand(UINT nID); ``` ```cpp ON_COMMAND(ID_MYCMD, OnMyCommand) ON_UPDATE_COMMAND_UI(ID_MYCMD, OnUpdateMyCommand) ON_COMMAND_EX(ID_MYCMD, OnComplexCommand) ``` ```cpp void CMyClass::OnMyCommand() { // handle the command } void CMyClass::OnUpdateMyCommand(CCmdUI* pCmdUI) { // set the UI state with pCmdUI } BOOL CMyClass::OnComplexCommand(UINT nID) { // handle the command return TRUE; } ``` -------------------------------- ### Create a Setup Project in Visual Studio Source: https://learn.microsoft.com/en-us/cpp/ide/walkthrough-deploying-your-program-cpp Steps to create a new setup project within your existing Visual Studio solution. This project will generate the installer for your application. ```text 1. From the Visual Studio main menu, choose **File** > **New** > **Project**. 2. In the search box, type `Setup` and select **Setup Project**. 3. Enter a name for the setup project (e.g., `Setup`) and select **Add to solution**. 4. Right-click the **Application Folder** node and select **Add** > **Project Output**. 5. Select **Primary Output** and click **OK**. 6. Right-click the newly added **Primary Output** and choose **Create Shortcut**. 7. Rename the shortcut to your application's name (e.g., _Game_) and drag it to the **User's Programs Menu** node. 8. Select the setup project in **Solution Explorer**, then open the **Properties** window. 9. Configure installer properties such as **Manufacturer**, **Product Name**, and **SupportUrl**. ``` -------------------------------- ### Example of creating and removing a directory Source: https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/mkdir-wmkdir Demonstrates how to create a directory using `_mkdir`, verify its creation, and then remove it using `_rmdir`. Ensure necessary headers like `` are included. ```C // crt_makedir.c #include #include #include int main( void ) { if( _mkdir( "\\testtmp" ) == 0 ) { printf( "Directory \'\\testtmp\' was successfully created\n" ); system( "dir \\testtmp" ); if( _rmdir( "\\testtmp" ) == 0 ) printf( "Directory \'\\testtmp\' was successfully removed\n" ); else printf( "Problem removing directory \'\\testtmp\'\n" ); } else printf( "Problem creating directory \'\\testtmp\'\n" ); } ``` -------------------------------- ### Get GUID of a Library Block with `__uuidof` Source: https://learn.microsoft.com/en-us/cpp/cpp/uuidof-operator This example demonstrates how to retrieve the GUID of a library block created with the `module` attribute using the `__uuidof` operator. It requires linking with `ole32.lib` and includes necessary headers for Windows and string manipulation. ```cpp #include "stdio.h" #include "windows.h" [emitidl]; [module(name="MyLib")]; [export] struct stuff { int i; }; int main() { LPOLESTR lpolestr; StringFromCLSID(__uuidof(MyLib), &lpolestr); wprintf_s(L"%s", lpolestr); CoTaskMemFree(lpolestr); } ``` -------------------------------- ### Iterating an MFC List with GetHeadPosition and GetNext Source: https://learn.microsoft.com/en-us/cpp/mfc/accessing-all-members-of-a-collection Use GetHeadPosition to get the starting position and GetNext to retrieve elements sequentially. This example uses a typed pointer list. ```C++ CTypedPtrList myList; myList.AddHead(new CPerson()); POSITION pos = myList.GetHeadPosition(); while (pos != NULL) { CPerson *thePerson = myList.GetNext(pos); thePerson->AssertValid(); } ``` -------------------------------- ### Retrieve .NET Framework Version Source: https://learn.microsoft.com/en-us/cpp/dotnet/windows-operations-cpp-cli This C++ example demonstrates how to get the version of the installed .NET Framework. It accesses the Major, Minor, Build, and Revision components of the Environment.Version property. ```C++ // dotnet_ver.cpp // compile with: /clr using namespace System; int main() { Version^ version = Environment::Version; if (version) { int build = version->Build; int major = version->Major; int minor = version->Minor; int revision = Environment::Version->Revision; Console::Write(".NET Framework version: "); Console::WriteLine("{0}.{1}.{2}.{3}", build, major, minor, revision); } return 0; } ``` -------------------------------- ### BSCMAKE Build Example Source: https://learn.microsoft.com/en-us/cpp/build/reference/bscmake-command-line An example command to build a MAIN.bsc file using three specified .sbr files. Ensure all necessary .sbr files are included for a full build. ```bash BSCMAKE main.sbr file1.sbr file2.sbr ``` -------------------------------- ### Output of GUID conversion example Source: https://learn.microsoft.com/en-us/cpp/dotnet/how-to-convert-between-system-guid-and-guid This is the expected output when running the C++ code example for GUID conversion. ```text 11111111-2222-3333-4455-555555555555 11111111-2222-3333-4455-555555555555 ``` -------------------------------- ### CHeapPtr Constructor Example Source: https://learn.microsoft.com/en-us/cpp/atl/reference/cheapptr-class Shows how to create a default CHeapPtr and then create another CHeapPtr by copying the first one. ```cpp // Create a new CHeapPtr object CHeapPtr myHP; // Create a new CHeapPtr from the first CHeapPtr myHP2(myHP); ``` -------------------------------- ### C++ GUID Association Warning C4917 Example Source: https://learn.microsoft.com/en-us/cpp/error-messages/compiler-warnings/compiler-warning-level-1-c4917 This C++ code example demonstrates how compiler warning C4917 is generated when a GUID is applied to a struct. Ensure GUIDs are only associated with classes, interfaces, or namespaces. ```cpp // C4917.cpp // compile with: /W1 #pragma warning(default : 4917) __declspec(uuid("00000000-0000-0000-0000-000000000001")) struct S { } s; // C4917, don't put uuid on a struct int main() { } ``` -------------------------------- ### Main Code Example Using Bookmarks Source: https://learn.microsoft.com/en-us/cpp/data/oledb/implementing-a-simple-consumer This example demonstrates how to instantiate a bookmark object, set it at a specific row, and then navigate back to that bookmarked row using MoveToBookmark. ```cpp /////////////////////////////////////////////////////////////////////// // MyCons.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "Products.h" #include #include using namespace std; int _tmain(int argc, _TCHAR* argv[]) { HRESULT hr = CoInitialize(NULL); // Instantiate rowset CProducts rs; hr = rs.OpenAll(); hr = rs.MoveFirst(); // Cast CURRENCY m_UnitPrice to a long value LONGLONG lPrice = rs.m_UnitPrice.int64; // Open file output.txt for writing in overwrite mode ofstream outfile( "C:\\output.txt", ios::out ); if (!outfile) // Test for invalid file return -1; // Instantiate a bookmark object myBookmark for the main code CBookmark<4> myBookmark; int nCounter = 0; // Iterate through the rowset and output column data to output.txt row by row // In the file, mark the beginning of this set of data: outfile << "initial row dump" << endl; while(SUCCEEDED(hr) && hr != DB_S_ENDOFROWSET ) { nCounter++; if(nCounter == 5 ) myBookmark = rs.m_bookmark; // Output the column information for each row: outfile << rs.m_ProductID << rs.m_ProductName << lPrice << rs.m_QuantityPerUnit << rs.m_UnitsInStock << rs.m_ReorderLevel << endl; hr = rs.MoveNext(); } // Move cursor to bookmark hr = rs.MoveToBookmark(myBookmark); // Iterate through the rowset and output column data to output.txt row by row // In the file, mark the beginning of this set of data: outfile << "row dump starting from bookmarked row" << endl; while(SUCCEEDED(hr) && hr != DB_S_ENDOFROWSET ) { // Output the column information for each row outfile << rs.m_ProductID << rs.m_ProductName << lPrice << rs.m_QuantityPerUnit << rs.m_UnitsInStock << rs.m_ReorderLevel << endl; hr = rs.MoveNext(); } rs.CloseAll(); CoUninitialize(); return 0; } ``` -------------------------------- ### Get Chunk GUID Source: https://learn.microsoft.com/en-us/cpp/mfc/reference/cmfcfilterchunkvalueimpl-class Retrieves the GUID that identifies the chunk. This method returns a constant reference to the GUID. ```cpp REFGUID GetChunkGUID() const; ``` -------------------------------- ### Display Help Summary Source: https://learn.microsoft.com/en-us/cpp/build/reference/bscmake-options The /HELP option displays a summary of the BSCMAKE command-line syntax. ```bash BSCMAKE /HELP ``` -------------------------------- ### Output of gets example Source: https://learn.microsoft.com/en-us/cpp/c-runtime-library/gets-getws This is the expected output when running the `crt_gets.c` example with the input 'Hello there!'. ```text Hello there!The line entered was: Hello there! ``` -------------------------------- ### CHeapPtr::Allocate Example Source: https://learn.microsoft.com/en-us/cpp/atl/reference/cheapptr-class Demonstrates how to create a CHeapPtr object and allocate space for 10 integers on the heap. ```cpp // Create a new CHeapPtr object CHeapPtr myHP; // Allocate space for 10 integers on the heap myHP.Allocate(10); ``` -------------------------------- ### C++ Compiler Error C2788 Example Source: https://learn.microsoft.com/en-us/cpp/error-messages/compiler-errors-2/compiler-error-c2788 This example demonstrates how to trigger C2788 by associating multiple GUIDs with a template instantiation. To resolve the error, ensure that a type used with __uuidof has only one GUID. ```cpp // C2788.cpp #include struct __declspec(uuid("00000001-0000-0000-0000-000000000000")) A {}; struct __declspec(uuid("{00000002-0000-0000-0000-000000000000}")) B {}; template class MyClass {}; typedef MyClass MyBadClass; typedef MyClass MyGoodClass; int main() { __uuidof(MyBadClass); // C2788 // try the following line instead __uuidof(MyGoodClass); } ``` -------------------------------- ### Build and Test Example 2 Source: https://learn.microsoft.com/en-us/cpp/sanitizers/error-stack-buffer-overflow Commands to build the C++ example with Address Sanitizer and run it with a debugger, providing an argument. ```bash cl example2.cpp /fsanitize=address /Zi devenv /debugexe example2.exe 9 ``` -------------------------------- ### Get Pointer Size Example Source: https://learn.microsoft.com/en-us/cpp/cpp/sizeof-operator This example demonstrates how to use `sizeof` to get the size of a character array and the size of a pointer to a character. The `getPtrSize` function returns the size of the pointer, not the array it points to. ```cpp #include using namespace std; size_t getPtrSize( char *ptr ) { return sizeof( ptr ); } int main() { char szHello[] = "Hello, world!"; cout << "The size of a char is: " << sizeof( char ) << "\nThe length of " << szHello << " is: " << sizeof szHello << "\nThe size of the pointer is " << getPtrSize( szHello ) << endl; } ``` -------------------------------- ### Example: Get current file clock time Source: https://learn.microsoft.com/en-us/cpp/standard-library/file-clock-class This example demonstrates how to get the current time using `file_clock` by casting from `utc_clock::now()`. Compile with `/std:c++latest`. The output format may vary. ```cpp // compile using: /std:c++latest #include #include using namespace std::chrono; int main() { std::cout << clock_cast(utc_clock::now()); return 0; } ``` -------------------------------- ### Demonstrate CSettingsStore Open and Read Methods Source: https://learn.microsoft.com/en-us/cpp/mfc/reference/csettingsstore-class This example shows how to use the Open and Read methods to access registry values. It checks for the existence of a registry key and reads a DWORD value. ```cpp CSettingsStore reg(FALSE, TRUE); DWORD dwEnableBalloonTips = 1; if (reg.Open(_T("Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced")) && reg.Read(_T("EnableBalloonTips"), dwEnableBalloonTips)) { return dwEnableBalloonTips == 1; } ``` -------------------------------- ### Install and Start OpenSSH Server on Linux Source: https://learn.microsoft.com/en-us/cpp/linux/connect-to-your-remote-linux-computer Use these commands to install the OpenSSH server package and start the service on your Ubuntu system. Ensure the SSH server is running before attempting to connect from Visual Studio. ```bash sudo apt install openssh-server sudo service ssh start ``` -------------------------------- ### Create Setup Batch File for Visual C++ Deployment Source: https://learn.microsoft.com/en-us/cpp/windows/deploying-visual-cpp-application-by-using-the-vcpp-redistributable-package This batch script sets up the installation of a Visual C++ Redistributable package and copies the application files. Uncomment the appropriate line for your target architecture (x86, x64, or ARM64). Adjust the application name and installation path if necessary. ```batch @echo off REM Choose one of the following Redistributable files to install ::vc_redist.x86.exe REM remove leading :: to install Redistributable for x86 ::vc_redist.x64.exe REM remove leading :: to install Redistributable for x64 ::vc_redist.arm64.exe REM remove leading :: to install Redistributable for ARM64 mkdir "C:\Program Files\MyMFCApp" copy MyMFCApp.exe "C:\Program Files\MyMFCApp" ``` -------------------------------- ### Example of using gets Source: https://learn.microsoft.com/en-us/cpp/c-runtime-library/gets-getws This C example demonstrates the usage of the `gets` function. It includes a warning about the lack of input length limitation, which can lead to buffer overruns. Consider using `gets_s` for safer input handling. ```C // crt_gets.c // compile with: /WX /W3 #include int main( void ) { char line[21]; // room for 20 chars + '\0' gets( line ); // C4996 // Danger: No way to limit input to 20 chars. // Consider using gets_s instead. printf( "The line entered was: %s\n", line ); } ``` -------------------------------- ### Complete Example: Consume Windows Runtime Component Source: https://learn.microsoft.com/en-us/cpp/cppcx/wrl/how-to-activate-and-use-a-windows-runtime-component-using-wrl This complete C++ example demonstrates activating and using a Windows Runtime component, including initialization, activation factory creation, string handling, object instantiation, and property retrieval. ```cpp // wrl-consume-component.cpp // compile with: runtimeobject.lib #include #include #include #include using namespace ABI::Windows::Foundation; using namespace Microsoft::WRL; using namespace Microsoft::WRL::Wrappers; // Prints an error string for the provided source code line and HRESULT // value and returns the HRESULT value as an int. int PrintError(unsigned int line, HRESULT hr) { wprintf_s(L"ERROR: Line:%d HRESULT: 0x%X\n", line, hr); return hr; } int wmain() { // Initialize the Windows Runtime. RoInitializeWrapper initialize(RO_INIT_MULTITHREADED); if (FAILED(initialize)) { return PrintError(__LINE__, initialize); } // Get the activation factory for the IUriRuntimeClass interface. ComPtr uriFactory; HRESULT hr = GetActivationFactory(HStringReference(RuntimeClass_Windows_Foundation_Uri).Get(), &uriFactory); if (FAILED(hr)) { return PrintError(__LINE__, hr); } // Create a string that represents a URI. HString uriHString; hr = uriHString.Set(L"http://www.microsoft.com"); if (FAILED(hr)) { return PrintError(__LINE__, hr); } // Create the IUriRuntimeClass object. ComPtr uri; hr = uriFactory->CreateUri(uriHString.Get(), &uri); if (FAILED(hr)) { ``` -------------------------------- ### Example: Initializing and Parsing Command Line Source: https://learn.microsoft.com/en-us/cpp/mfc/reference/ccommandlineinfo-class Demonstrates how to create a CCommandLineInfo object and pass it to CWinApp::ParseCommandLine within the InitInstance function. ```cpp CCommandLineInfo cmdInfo; ParseCommandLine(cmdInfo); ``` -------------------------------- ### Get Tooltip Information Example Source: https://learn.microsoft.com/en-us/cpp/mfc/reference/ctooltipctrl-class The following code example retrieves information about the current tooltip window. ```cpp { //Get information about the current tooltip. TOOLINFO tInfo = {0}; tInfo.cbSize = sizeof(TOOLINFO); CToolBarCtrl& m_toolBarCtrl = m_wndToolBar.GetToolBarCtrl(); CToolTipCtrl* m_toolTip = m_toolBarCtrl.GetToolTips(); BOOL bRet = m_toolTip->GetCurrentTool( &tInfo ); } ``` -------------------------------- ### Output of _getdrive Example Source: https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/getdrive This is the expected output when running the `_getdrive` example code, showing available drives and their current directories. ```text Available drives are: A: (Current directory is A:\) C: (Current directory is C:\) E: (Current directory is E:\testdir\bin) F: (Current directory is F:\) G: (Current directory is G:\) ``` -------------------------------- ### Example: Open and Map a File with CAtlFileMappingBase Source: https://learn.microsoft.com/en-us/cpp/atl/reference/catlfilemappingbase-class This example demonstrates creating a CAtlFileMappingBase object, creating a file, and then mapping that file for read/write access. It includes assertions to verify the file handle and mapping size. ```cpp int OpenMyFileMap() { // Create the file-mapping object. CAtlFileMappingBase myFileMap; // Create a file. CAtlFile myFile; myFile.Create(_T("myMapTestFile"), GENERIC_READ|GENERIC_WRITE|STANDARD_RIGHTS_ALL, FILE_SHARE_READ|FILE_SHARE_WRITE, OPEN_ALWAYS); // The file handle. HANDLE hFile = (HANDLE)myFile; // Test the file has opened successfully. ATLASSERT(hFile != INVALID_HANDLE_VALUE); // Open the file for file-mapping. // Must give a size as the file is zero by default. if (myFileMap.MapFile(hFile, 1024, 0, PAGE_READWRITE, FILE_MAP_READ) != S_OK) { CloseHandle(hFile); return 0; } // Confirm the size of the mapping file. ATLASSERT(myFileMap.GetMappingSize() == 1024); // Now the file-mapping object is open, a second // process could access the filemap object to exchange // data. return 0; } ``` -------------------------------- ### Example of shared_ptr get() Source: https://learn.microsoft.com/en-us/cpp/standard-library/shared-ptr-class Illustrates using the get() method to obtain the address of the managed resource and checking for null. ```cpp // std__memory__shared_ptr_get.cpp // compile with: /EHsc #include #include int main() { std::shared_ptr sp0; std::shared_ptr sp1(new int(5)); std::cout << "sp0.get() == 0 == " << std::boolalpha << (sp0.get() == 0) << std::endl; std::cout << "*sp1.get() == " << *sp1.get() << std::endl; return (0); } ``` -------------------------------- ### Example: Using BrowseForFolder - MFC Source: https://learn.microsoft.com/en-us/cpp/mfc/reference/cshellmanager-class Demonstrates retrieving the CShellManager and using BrowseForFolder to select a directory. This example is part of the Explorer sample. ```cpp CString strPath; // The this pointer points to the CExplorerView class which extends the CView class. // CMFCShellListCtrl m_wndList if (m_wndList.GetCurrentFolder(strPath) && theApp.GetShellManager()->BrowseForFolder(strPath, this, strPath, _T("Copy the selected item(s) to the folder:"))) { MessageBox(CString(_T("The selected path is: ")) + strPath); } ``` -------------------------------- ### Install Visual Studio Installer Projects Extension Source: https://learn.microsoft.com/en-us/cpp/ide/walkthrough-deploying-your-program-cpp Follow these steps to install the 'Microsoft Visual Studio Installer Projects' extension from the Visual Studio Marketplace. This extension is required to create setup projects. ```text 1. From the main menu in Visual Studio choose **Extensions** > **Manage Extensions**. 2. Select the **Online** tab and type _Microsoft Visual Studio Installer Projects_ in the search box. 3. Select **Microsoft Visual Studio Installer Projects** and click **Download**. 4. Choose to run and install the extension, then restart Visual Studio. ``` -------------------------------- ### gets, _getws API Documentation Source: https://learn.microsoft.com/en-us/cpp/c-runtime-library/gets-getws Documentation for the `gets` and `_getws` functions, including syntax, parameters, return values, and examples. ```APIDOC ## gets, _getws ### Description Gets a line from the `stdin` stream. These functions are obsolete and have security risks. Secure versions like `gets_s` and `_getws_s` are recommended. ### Method N/A (These are C library functions, not HTTP API endpoints) ### Endpoint N/A ### Parameters #### `buffer` - **buffer** (char* or wchar_t*) - Storage location for input string. ### Return value - Returns its argument if successful. - A `NULL` pointer indicates an error or end-of-file condition. Use `ferror` or `feof` to determine which one has occurred. - If `buffer` is `NULL`, an invalid parameter handler is invoked. If execution continues, `NULL` is returned and `errno` is set to `EINVAL`. ### Remarks - Reads a line from `stdin` up to and including the first newline character ('\n'). - Replaces the newline character with a null character ('\0'). - `_getws` is the wide-character version. - **Important**: Prone to buffer overruns due to no input length limit. Use `fgets` instead. - C++ has secure template overloads. ### Generic-text routine mappings | TCHAR.H routine | `_UNICODE` and `_MBCS` not defined | `_MBCS` defined | `_UNICODE` defined | |---|---|---|---| | `_getts` | **`gets`** | **`gets`** | **`_getws`** ### Requirements | Routine | Required header | |---|---| | **`gets`** | `` | | **`_getws`** | `` or `` | ### Example ```c // crt_gets.c // compile with: /WX /W3 #include int main( void ) { char line[21]; // room for 20 chars + '\0' gets( line ); // C4996 // Danger: No way to limit input to 20 chars. // Consider using gets_s instead. printf( "The line entered was: %s\n", line ); } ``` #### Output Example ``` Hello there!The line entered was: Hello there! ``` ### See also - `fgets`, `fgetws` - `fputs`, `fputws` - `puts`, `_putws` ``` -------------------------------- ### Build and Test Simple C Example Source: https://learn.microsoft.com/en-us/cpp/sanitizers/error-stack-use-after-return Commands to build and debug the `example1.cpp` using Visual Studio 2019. This includes setting the necessary compiler flags and environment variables. ```cmd cl example1.cpp /fsanitize=address /fsanitize-address-use-after-return /Zi set ASAN_OPTIONS=detect_stack_use_after_return=1 devenv /debugexe example1.exe ``` -------------------------------- ### Build and Test Example 3 Source: https://learn.microsoft.com/en-us/cpp/sanitizers/error-stack-buffer-overflow Commands to build the C++ example with Address Sanitizer and run it with a debugger in Visual Studio. ```bash cl example3.cpp /fsanitize=address /Zi devenv /debugexe example3.exe ``` -------------------------------- ### C++ get Example Usage Source: https://learn.microsoft.com/en-us/cpp/standard-library/utility-functions Demonstrates how to retrieve elements from a std::pair using both index-based and type-based access with the get function. ```cpp #include #include using namespace std; int main() { typedef pair MyPair; MyPair c0(9, 3.14); // get elements by index cout << " " << get<0>(c0); cout << " " << get<1>(c0) << endl; // get elements by type (C++14) MyPair c1(1, 0.27); cout << " " << get(c1); cout << " " << get(c1) << endl; } ``` -------------------------------- ### Create a Dockable Toolbar - C++ Example Source: https://learn.microsoft.com/en-us/cpp/mfc/reference/ctoolbar-class Example demonstrating the creation of a dockable toolbar within a CMainFrame, including loading toolbar resources and enabling docking. ```cpp //This example creates a dockable toolbar. if (!m_wndToolBar.Create(this) || !m_wndToolBar.LoadToolBar(IDR_MAINFRAME)) { TRACE0("Failed to create toolbar\n"); return -1; // fail to create } //Make the toolbar dockable m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY); EnableDocking(CBRS_ALIGN_ANY); DockControlBar(&m_wndToolBar); ``` -------------------------------- ### Get Storyboard Start Keyframe - C++ Source: https://learn.microsoft.com/en-us/cpp/mfc/reference/canimationcontroller-class Returns a keyframe that identifies the start of the storyboard. This is useful for setting relative keyframes or transitions. ```cpp static CBaseKeyFrame* GetKeyframeStoryboardStart(); ``` -------------------------------- ### Create and split a path using _makepath_s and _splitpath_s Source: https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/makepath-s-wmakepath-s This example demonstrates how to use _makepath_s to construct a path and then _splitpath_s to parse it back into its components. Ensure the buffer size is sufficient to avoid truncation. ```C #include #include int main( void ) { char path_buffer[_MAX_PATH]; char drive[_MAX_DRIVE]; char dir[_MAX_DIR]; char fname[_MAX_FNAME]; char ext[_MAX_EXT]; errno_t err; err = _makepath_s( path_buffer, _MAX_PATH, "c", "\sample\crt\", "crt_makepath_s", "c" ); if (err != 0) { printf("Error creating path. Error code %d.\n", err); exit(1); } printf( "Path created with _makepath_s: %s\n\n", path_buffer ); err = _splitpath_s( path_buffer, drive, _MAX_DRIVE, dir, _MAX_DIR, fname, _MAX_FNAME, ext, _MAX_EXT ); if (err != 0) { printf("Error splitting the path. Error code %d.\n", err); exit(1); } printf( "Path extracted with _splitpath_s:\n" ); printf( " Drive: %s\n", drive ); printf( " Dir: %s\n", dir ); printf( " Filename: %s\n", fname ); printf( " Ext: %s\n", ext ); } ``` -------------------------------- ### Get Start Timestamp Source: https://learn.microsoft.com/en-us/cpp/build-insights/reference/sdk/cpp-event-data-types/trace-info Returns a tick value captured at the time the trace was started. This can be used with TickFrequency to calculate elapsed time. ```cpp const long long& StartTimestamp() const; ``` -------------------------------- ### Output of `_mbsspnp` example Source: https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/strspnp-wcsspnp-mbsspnp-mbsspnp-l The expected output when running the `crt_mbsspnp.c` example, showing the substring starting from the first character not found in the charset. ```text abbage ``` -------------------------------- ### Example: Registering a Custom Window Class Source: https://learn.microsoft.com/en-us/cpp/mfc/reference/application-information-and-management Demonstrates the process of initializing a `WNDCLASS` structure and registering a unique window class using `AfxRegisterClass`. This example sets window styles, a custom window procedure, instance handle, icon, cursor, background brush, and class name. ```cpp // Register your unique class name that you wish to use WNDCLASS wndcls; memset(&wndcls, 0, sizeof(WNDCLASS)); // start with NULL defaults wndcls.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW; //you can specify your own window procedure wndcls.lpfnWndProc = ::DefWindowProc; wndcls.hInstance = AfxGetInstanceHandle(); wndcls.hIcon = LoadIcon(wndcls.hInstance, MAKEINTRESOURCE(IDI_MYICON)); wndcls.hCursor = LoadCursor(wndcls.hInstance, MAKEINTRESOURCE(IDC_ARROW)); wndcls.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); wndcls.lpszMenuName = NULL; // Specify your own class name for using FindWindow later wndcls.lpszClassName = _T("MyNewClass"); // Register the new class and trace if it fails if(!AfxRegisterClass(&wndcls)) { TRACE("Class Registration Failed\n"); } ``` -------------------------------- ### IErrorRecordsImpl::GetErrorGUID Source: https://learn.microsoft.com/en-us/cpp/data/oledb/ierrorrecordsimpl-class Gets the error GUID from an error record. ```APIDOC ## IErrorRecordsImpl::GetErrorGUID Gets the error GUID from an error record. ### Syntax ```cpp REFGUID GetErrorGUID(ERRORINFO& rCurError); ``` #### Parameters * **_rCurError_**: An `ERRORINFO` record in an `IErrorInfo` interface. ### Return Value A reference to a GUID for the error. ``` -------------------------------- ### CreateMenu Example Source: https://learn.microsoft.com/en-us/cpp/mfc/reference/cmenu-class Example demonstrating the creation of a new application menu, adding a pop-up menu with an item, replacing the old menu, and assigning the new menu. ```cpp // The code fragment below shows how to create a new menu for the // application window using CreateMenu() and CreatePopupMenu(). // Then, the created menu will replace the current menu of the // application. The old menu will be destroyed with DestroyMenu(). // NOTE: The code fragment below is done in a CFrameWnd-derived class. // Create a new menu for the application window. VERIFY(m_NewMenu.CreateMenu()); // Create a "File" popup menu and insert this popup menu to the // new menu of the application window. The "File" menu has only // one menu item, i.e. "Exit". VERIFY(m_FileMenu.CreatePopupMenu()); m_FileMenu.AppendMenu(MF_STRING, ID_APP_EXIT, _T("E&xit")); m_NewMenu.AppendMenu(MF_POPUP, (UINT_PTR)m_FileMenu.m_hMenu, _T("&File")); // Remove and destroy old menu SetMenu(NULL); CMenu *old_menu = CMenu::FromHandle(m_hMenuDefault); old_menu->DestroyMenu(); // Add new menu. SetMenu(&m_NewMenu); // Assign default menu m_hMenuDefault = m_NewMenu.m_hMenu; ``` -------------------------------- ### Install ODBC Driver Manager Source: https://learn.microsoft.com/en-us/cpp/mfc/tn048-writing-odbc-setup-and-administration-programs Call SQLInstallDriverManager to get the target directory for the Driver Manager. This function is part of the ODBC installer API. ```cpp SQLInstallDriverManager ``` -------------------------------- ### Example Usage of `_set_SSE2_enable` Source: https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/set-sse2-enable This C example demonstrates how to enable SSE2 implementation and check its status. It requires including `` and ``. ```C // crt_set_SSE2_enable.c // processor: x86 #include #include int main() { int i = _set_SSE2_enable(1); if (i) printf("SSE2 enabled.\n"); else printf("SSE2 not enabled; processor does not support SSE2.\n"); } ``` -------------------------------- ### CSettingsStore Example Source: https://learn.microsoft.com/en-us/cpp/mfc/reference/csettingsstore-class An example demonstrating the usage of the Open and Read methods of the CSettingsStore class. ```APIDOC ## Example The following example demonstrates how to use the Open and Read methods of the `CSettingsStore` class. This code snippet is part of the Tool Tip Demo sample. ```cpp CSettingsStore reg(FALSE, TRUE); DWORD dwEnableBalloonTips = 1; if (reg.Open(_T("Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced")) && reg.Read(_T("EnableBalloonTips"), dwEnableBalloonTips)) { return dwEnableBalloonTips == 1; } ``` ``` -------------------------------- ### Example: Get a sys_info Source: https://learn.microsoft.com/en-us/cpp/standard-library/sys-info-struct This example demonstrates how to obtain and print `sys_info` for the current system time using C++'s chrono library. ```APIDOC ## Example: Get a `sys_info` ### Code ```cpp // compile using: /std:c++latest #include #include using namespace std::chrono; int main() { sys_time st = system_clock::now(); const auto& timeZoneDatabase = get_tzdb(); const auto& currentZone = timeZoneDatabase.current_zone(); auto sysInfo = currentZone->get_info(st); std::cout << sysInfo << "\n"; return 0; } ``` ### Output ``` begin: 2021-03-14 10:00:00, end: 2021-11-07 09:00:00, offset: -25200s, save: 60min, abbrev: PDT ``` ### Requirements - **Header:** `` - **Namespace:** `std::chrono` - **Compiler Option:** `/std:c++latest` ``` -------------------------------- ### Output of _fullpath Example Source: https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/fullpath-wfullpath This output shows the results of running the _fullpath example code with different partial path inputs. ```text Full path is: C:\Documents and Settings\user\My Documents\test Full path is: C:\test Full path is: C:\Documents and Settings\user\test ``` -------------------------------- ### Example of crbegin usage Source: https://learn.microsoft.com/en-us/cpp/standard-library/list-class This example demonstrates using `crbegin` to get a const reverse iterator and access the last element of the list by dereferencing it. ```cpp // list_crbegin.cpp // compile with: /EHsc #include #include int main( ) { using namespace std; list c1; list ::const_reverse_iterator c1_crIter; c1.push_back( 10 ); c1.push_back( 20 ); c1.push_back( 30 ); c1_crIter = c1.crbegin( ); cout << "The last element in the list is " << *c1_crIter << "." << endl; } ``` -------------------------------- ### Example of Establishing a Connection Source: https://learn.microsoft.com/en-us/cpp/mfc/reference/connection-maps Demonstrates how to use AfxConnectionAdvise to connect a source object to a sink object, obtaining a connection cookie. ```cpp //CMySink is a CCmdTarget-derived class supporting automation. //Instantiate the sink class. CMySink mysink; //Get a pointer to sink's IUnknown, no AddRef done. IID iid = IID_IUnknown; IUnknown* pUnkSink = mysink.GetInterface(&iid); //Establish a connection between source and sink. //pUnkSrc is IUnknown of server obtained by CoCreateInstance(). //dwCookie is a cookie identifying the connection, and is needed //to terminate this connection. AfxConnectionAdvise(pUnkSrc, IID_ISampleSink, pUnkSink, TRUE, &dwCookie); ``` -------------------------------- ### Get Starting Coordinates of Linear Gradient Source: https://learn.microsoft.com/en-us/cpp/mfc/reference/cd2dlineargradientbrush-class Retrieves the starting coordinates of the linear gradient in the brush's coordinate space. This is a const method. ```cpp CD2DPointF GetStartPoint() const; ``` -------------------------------- ### Example: Create CMFCRibbonBar Source: https://learn.microsoft.com/en-us/cpp/mfc/reference/cmfcribbonbar-class Demonstrates how to use the Create method to initialize a CMFCRibbonBar object with a parent window and specific styles. ```cpp // CMFCRibbonBar m_wndRibbonBar m_wndRibbonBar.Create(this, WS_CHILD | CBRS_TOP); ``` -------------------------------- ### C++ Compiler Error C2776 Example Source: https://learn.microsoft.com/en-us/cpp/error-messages/compiler-errors-2/compiler-error-c2776 This example demonstrates the C++ compiler error C2776. It shows a struct with a property that has two 'get' functions specified, which triggers the error. The commented-out line shows the correct way to define a property with a single 'get' function. ```cpp // C2776.cpp struct A { __declspec(property(get=GetProp,get=GetPropToo)) // try the following line instead // __declspec(property(get=GetProp)) int prop; // C2776 int GetProp(void); int GetPropToo(void); }; ``` -------------------------------- ### Get starting offset of a submatch using match_results::position Source: https://learn.microsoft.com/en-us/cpp/standard-library/match-results-class Returns the starting offset (position) of a specified submatch within the target sequence. It calculates the distance from the beginning of the target sequence to the start of the submatch. ```C++ difference_type position(size_type sub = 0) const; ``` -------------------------------- ### Full Build with Exclusions and Output File Specification Source: https://learn.microsoft.com/en-us/cpp/build/reference/bscmake-options This example demonstrates a full build of 'main.bsc' from multiple .sbr files, excluding duplicate instances of 'toolbox.h', and specifying the output file name. ```bash BSCMAKE /n /S toolbox.h /o main.bsc file1.sbr file2.sbr file3.sbr ``` -------------------------------- ### Example of fpos state management Source: https://learn.microsoft.com/en-us/cpp/standard-library/fpos-class Demonstrates getting and setting the conversion state of an fpos object. This example requires the ``, ``, and `` headers. ```cpp // fpos_state.cpp // compile with: /EHsc #include #include #include int main() { using namespace std; streamoff s; ifstream file( "fpos_state.txt" ); fpos f = file.tellg( ); char ch; while ( !file.eof( ) ) file.get( ch ); s = f; cout << f.state( ) << endl; f.state( 9 ); cout << f.state( ) << endl; } ``` -------------------------------- ### Initialize MFC and Access ODBC Database Source: https://learn.microsoft.com/en-us/cpp/mfc/reference/application-information-and-management This example demonstrates initializing MFC using `AfxWinInit` and then attempting to connect to an ODBC database. This code is suitable for console applications where `WinMain` is not used, or as a standalone example of MFC initialization. ```cpp #include #include int _tmain(int /*argc*/, TCHAR * /*argv[]*/, TCHAR * /*envp[]*/) { int nRetCode = 0; // initialize MFC and print and error on failure if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0)) { // TODO: change error code to suit your needs _tprintf(_T("Fatal Error: MFC initialization failed\n")); nRetCode = 1; } else { // try to connect to an ODBC database that doesn't exist // (this wouldn't work at all without initializing MFC) CDatabase db; try { db.Open(_T("This Databsae Doesn't Exist")); // we shouldn't realistically get here _tprintf_s(_T("Successful!\n") _T("Closing ...\n")); db.Close(); _tprintf_s(_T("Closed!")); } catch (CDBException *pEx) { // we got an exception! print an error message // (this wouldn't work without initializing MFC) TCHAR sz[1024]; _tprintf_s(_T("Error: ")); if (pEx->GetErrorMessage(sz, 1024)) _tprintf_s(sz); else _tprintf_s(_T("No error message was available")); _tprintf_s(_T("\n")); pEx->Delete(); nRetCode = 1; } } return nRetCode; } ``` -------------------------------- ### Get sys_info for current time Source: https://learn.microsoft.com/en-us/cpp/standard-library/sys-info-struct This example demonstrates how to get the `sys_info` for the current system time using `std::chrono`. Compile with `/std:c++latest`. ```cpp // compile using: /std:c++latest #include #include using namespace std::chrono; int main() { sys_time st = system_clock::now(); const auto& timeZoneDatabase = get_tzdb(); const auto& currentZone = timeZoneDatabase.current_zone(); auto sysInfo = currentZone->get_info(st); std::cout << sysInfo << "\n"; return 0; } ``` -------------------------------- ### Create a Release Build for a Custom Platform Source: https://learn.microsoft.com/en-us/cpp/build/walkthrough-using-msbuild-to-create-a-visual-cpp-project Use the `/p` option to specify custom build configurations and platforms. This example builds for a platform named `myplatform` in release mode. ```bash msbuild myproject.vcxproj /p:configuration=release /p:platform=myplatform ``` -------------------------------- ### Get Activity Start Timestamp Source: https://learn.microsoft.com/en-us/cpp/build-insights/reference/sdk/cpp-event-data-types/activity Retrieves the tick value recorded when the activity began. Use this to determine the start point of an activity's execution. ```C++ const long long& StartTimestamp() const; ``` -------------------------------- ### Compile and link example application Source: https://learn.microsoft.com/en-us/cpp/cpp/tutorial-import-stl-named-module Compile the C++ example file and link it with the compiled module object files. The compiler automatically finds the `.ifc` file if it's in the same directory. ```bash cl /std:c++latest /EHsc /nologo /W4 stdCompatExample.cpp link stdCompatExample.obj std.obj std.compat.obj ``` -------------------------------- ### Lock MScalendar Control Example Source: https://learn.microsoft.com/en-us/cpp/mfc/reference/application-control Example demonstrating how to start and lock the Microsoft Calendar control's class factory using its program ID. ```cpp // Starts and locks control's (Microsoft Calendar) class factory. // Control will remain in memory for lifetime of // application or until AfxOleUnlockControl() is called. AfxOleLockControl(_T("MSCAL.Calendar")); ``` -------------------------------- ### Sample Output for _getdiskfree Example Source: https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/getdiskfree Displays the expected output format for the _getdiskfree example, showing disk drive information including total and available clusters, sectors per cluster, and bytes per sector. ```text Drive: C Total clusters: 249754111 Available clusters: 160184686 Sectors per cluster: 8 Bytes per sector: 512 ``` -------------------------------- ### Install SSH Server on Linux Source: https://learn.microsoft.com/en-us/cpp/linux/remote-file-explorer Commands to install and start the SSH server on a Linux machine. Ensure SSH is running before connecting with Visual Studio. ```bash sudo apt update sudo apt install openssh-server sudo systemctl start ssh sudo systemctl status ssh ``` -------------------------------- ### Example VC Redist Download Link Source: https://learn.microsoft.com/en-us/cpp/windows/troubleshoot-vc-redistributable-installation-issues This is an example of a direct download link for a specific older version of the Visual C++ Redistributable, constructed using the provided templates. ```url https://aka.ms/vs/18/release/14.50.35719/VC_redist.x64.exe ``` -------------------------------- ### Output of _creat Example Source: https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/creat-wcreat This is the expected output when the _creat example program successfully creates the 'data' file. ```text Created data file. ``` -------------------------------- ### C++ `get` example with tuple elements Source: https://learn.microsoft.com/en-us/cpp/standard-library/tuple-functions Demonstrates accessing tuple elements by both index and type. This example requires including the , , and headers. ```cpp #include #include #include using namespace std; int main() { tuple tup(0, 1.42, "Call me Tuple"); // get elements by index cout << " " << get<0>(tup); cout << " " << get<1>(tup); cout << " " << get<2>(tup) << endl; // get elements by type cout << " " << get(tup); cout << " " << get(tup); cout << " " << get(tup) << endl; } ``` -------------------------------- ### Output of _access_s example Source: https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/access-s-waccess-s Shows the expected output when running the `_access_s` example, indicating file existence and write permission status. ```text File crt_access_s.c exists. File crt_access_s.c does not have write permission. ``` -------------------------------- ### Get First Element with hash_map::cbegin Source: https://learn.microsoft.com/en-us/cpp/standard-library/hash-map-class This example shows how to get a const iterator to the first element of a hash_map using `cbegin()`. Note that `hash_map` is obsolete. ```cpp // hash_map_cbegin.cpp // compile with: /EHsc #include #include int main( ) { using namespace std; using namespace stdext; hash_map hm1; hash_map :: const_iterator hm1_cIter; typedef pair Int_Pair; hm1.insert ( Int_Pair ( 2, 4 ) ); hm1_cIter = hm1.cbegin ( ); cout << "The first element of hm1 is " << hm1_cIter -> first << "." << endl; } ``` -------------------------------- ### Get Compiler Help Source: https://learn.microsoft.com/en-us/cpp/build/walkthrough-compile-a-c-program-on-the-command-line Enter `cl /?` at the developer command prompt for a quick list of available compiler options. ```bash cl /? ``` -------------------------------- ### Get Start Position for Item Iteration Source: https://learn.microsoft.com/en-us/cpp/mfc/reference/coledocument-class Call this function to get the position of the first item in the document. Pass the returned value to `GetNextItem`, `GetNextClientItem`, or `GetNextServerItem`. ```cpp virtual POSITION GetStartPosition() const; ``` -------------------------------- ### Get the starting index of a valarray slice Source: https://learn.microsoft.com/en-us/cpp/standard-library/slice-class Shows how to retrieve the starting index of a slice from a valarray using the `start()` member function. This is useful when you need to know the exact position where a slice begins within the original valarray. ```cpp // slice_start.cpp // compile with: /EHsc #include #include int main( ) { using namespace std; int i; size_t startVAR; valarray va ( 20 ), vaResult; for ( i = 0 ; i < 20 ; i += 1 ) va [ i ] = i+1; cout << "The operand valarray va is:\n ( "; for ( i = 0 ; i < 20 ; i++ ) cout << va [ i ] << " "; cout << ")." << endl; slice vaSlice ( 3 , 6 , 3 ); vaResult = va [ vaSlice ]; cout << "The slice of valarray va is vaResult = " << "va[slice( 3, 6, 3)] = ( "; for ( i = 0 ; i < 6 ; i++ ) cout << vaResult [ i ] << " "; cout << ")." << endl; startVAR = vaSlice.start ( ); cout << "The start index of slice vaSlice is: " << startVAR << "." << endl; } ``` -------------------------------- ### Select Startup Item in Visual Studio Source: https://learn.microsoft.com/en-us/cpp/build/get-started-linux-cmake Before launching the application, select the executable from the launch drop-down in the toolbar. This example shows how to select 'AppBasicExampleGui.exe'. ```text AppBasicExampleGui.exe ```