-
Get Text from Edit
Both work, and both seem to return a value, which is more correct:
PHP Code:
//First version -- as you see with one line commented out
//Second version -- include the memory allocation line
//--------------------
//Get text from edit box
//--------------------
char* GetTextFromEdit(HWND hwnd, DWORD ID)
{
char* Text;
int len = GetWindowTextLength( GetDlgItem(hwnd, ID) );
if(len > 0)
{
//Text = (char*)GlobalAlloc(GPTR, len + 1);
GetDlgItemText(hwnd, ID, Text, len + 1);
}
return Text;
}
Problem with the second version, is the function returns the text I need, I do not get a chance to unallocate it...Which is a problem, but it seems without allocating the memory, it works fine when returning to a char*
-
The first version is incorrect and your program will crash at some point - you're not allocated any memory for the text. GetDlgItemText, as far as I can see, does not allocate the memory for the text string itself - it expects a preallocated buffer and the length of that buffer to be passed to it. Therefore you *must* allocate the memory for the buffer yourself.
Why use GlobalAlloc anyway? new is fine.
As for freeing the memory later, you could just make the caller responsible for freeing it, or maybe use a smart pointer (though unless you're going to use smart pointers widely, I wouldn't use one here). You could just modify the function to put the returned string into an std::string and then free the buffer before returning the std::string..there's lots of ways you can approach it.
-
I would use std::string to make it easier on yourself:
Code:
string GetTextFromEdit(HWND hwnd, DWORD ID)
{
string str;
LPTSTR buffer;
int len = GetWindowTextLength(GetDlgItem(hwnd, ID));
if(len > 0)
{
buffer = new TCHAR[len + 1];
GetDlgItemText(hwnd, ID, buffer, len + 1);
str = buffer;
delete[] buffer;
}
return str;
}
Then you can do something like MessageBox(hwnd, GetTextFromEdit(hwnd, ID).c_str(), "", 0);