- 1 year ago
How do I get the name of a right clicked item in a folder in windows using C++
To get the name of a right-clicked item in a folder in Windows using C++, you can use the Windows Shell APIs. Here's an example of how you can achieve this:
cpp#include <iostream>
#include <Windows.h>
#include <ShlObj.h>
int main()
{
// Get the path of the selected item from the command line
LPWSTR selectedItemPath = GetCommandLineW();
// Convert the path to a C++ string
std::wstring selectedItem(selectedItemPath);
// Extract the file name from the path
size_t lastSlash = selectedItem.find_last_of(L"\\");
std::wstring fileName = selectedItem.substr(lastSlash + 1);
// Display the file name
std::wcout << L"Selected File Name: " << fileName << std::endl;
// Release the memory allocated by GetCommandLineW
LocalFree(selectedItemPath);
return 0;
}
In the above example:
The
GetCommandLineW
function is used to retrieve the command-line arguments passed to the application. The selected item path is stored as a wide string (LPWSTR
).The path is converted to a C++ string (
std::wstring
) to make it easier to work with.The file name is extracted from the path by finding the last occurrence of the backslash character (
\
) using thefind_last_of
function.The extracted file name is then displayed using
std::wcout
.Finally, the memory allocated by
GetCommandLineW
is released using theLocalFree
function.
Make sure to link against the Shell32.lib
library and include the necessary header files (Windows.h
and ShlObj.h
) in your C++ project.
When you run the program, it will retrieve the name of the right-clicked item in the folder and display it in the console.