问题
What is the best way to convert HWND to Hex String in C++, I mean also with a "0x" prefix?
HWND hWnd = FindWindow(L"Notepad", L"Untitled - Notepad");
MessageBox(nullptr, LPCWSTR(hWnd), L"Hello World!", MB_ICONINFORMATION | MB_OK | MB_DEFBUTTON1);
But I expect this to output 0x00000000 (assuming Notepad windows is not open) , but it always returns an empty string.
I also tried this answer, but I ended up with returning 0000000000000000.
Anyone can help me on that conversion?
回答1:
What you are doing is not conversion. You just cast hWnd to a pointer to string. Almost always it will not point to a valid string, producing an undefined behavior when you try to print it as a string.
To do it properly, you should trait hWnd's bit's as integer and print it to some buffer as hex before showing in the message box:
#include <sstream>
#include <cstdint>
#include <iomanip>
//.....
std::wstringstream ss;
ss << std::hex << L"0x" << std::setw(16) << std::setfill(L'0') <<
*reinterpret_cast<uint64_t*>(&hWnd) << std::endl;
MessageBox(nullptr, ss.str().c_str(), L"Hello World!",
MB_ICONINFORMATION | MB_OK | MB_DEFBUTTON1);
Notes:
1) stringstream is a C++-style sprintf. It's str() method returns std::string, so to get a C-style pointer you should call c_str on it.
2) I have no Windows to check what is HWND actually. So please check it's size and use appropriate integer type instead of uint64_t. It's important, as if you use a too wide type, you'll get garbage or even access violation. A better approach is to use an integer type template like one discussed here.
3) Probably, you need std::wstringstream as you are using wide-char version of MessageBox.
4) Decoration. ss << *reinterpret_cast<uint64_t*>(&hWnd) just prints raw hex digits to ss, so to get the right format, you should fine-tune it, setting proper padding and filling character. For example, this will cause all integers to be printed as 16-digit numbers with leading zeros:
ss << std::setw(16) << std::setfill(L'0') ...
where setw and setfill functions are from iomanip header. Also, printing 0x prefix is your job, not stringstream's. Also take a look at std::showbase.
回答2:
To get a string representation of a hexadecimal number insert the 0x literal followed by a handle into a stringstream:
#include <Windows.h>
#include <sstream>
#include <iostream>
int main(){
HWND hWnd = FindWindow(L"Notepad", L"Untitled - Notepad");
std::stringstream ss;
ss << "0x" << hWnd;
std::cout << ss.str();
}
If you need to print out the result in a MessageBox use wide stringstream:
#include <Windows.h>
#include <sstream>
int main(){
HWND hWnd = FindWindow(L"Notepad", L"Untitled - Notepad");
std::wstringstream wss;
wss << "0x" << hWnd;
MessageBox(NULL, wss.str().c_str(), L"Hello World!", MB_ICONINFORMATION | MB_OK | MB_DEFBUTTON1);
}
来源:https://stackoverflow.com/questions/45071216/convert-hwnd-to-hex-string-in-c