テキストボックスのテキストの取得方法のメモ.
#include <iterator> #include <string> #include <vector> #include <windows.h> #include <tchar.h> std::basic_string<TCHAR> GetText(HWND handle) { int length = ::GetWindowTextLength(handle); if (length <= 0) return std::basic_string<TCHAR>(); std::vector<TCHAR> buffer(length + 1, 0); int result = ::GetWindowText(handle, reinterpret_cast<TCHAR*>(&buffer[0]), buffer.size()); if (result <= 0) return std::basic_string<TCHAR>(); // NULL 文字も含まれているなら以下でも良い? // return std::basic_string<TCHAR>(reinterpret_cast<TCHAR*>(&buffer[0])) std::vector<TCHAR>::iterator pos = buffer.begin(); std::advance(pos, result); return std::basic_string<TCHAR>(buffer.begin(), pos); }
バッファサイズをどれだけにするかをどうやって決めるんだろうと思っていたら,GetWindowTextLength() で先にテキスト長だけ取得して決めるようです.可変長配列を用意する場合,ややトリッキー?な記述になりますが std::vector を利用するのが最も楽かなと思います.