从编辑控件获取文本(纯 Win32 API)
我多年来一直试图让它发挥作用,但没有成功(悲伤的表情)。
int iChars = GetWindowTextLength (GetDlgItem(handle,ID))+1; // Room for '\0'
char* pstrText;
pstrText = (char*) malloc (sizeof(char)*iChars);
if (pstrText != NULL) {
//GetWindowText (GetDlgItem(handle,ID), pstrText, iChars);
GetDlgItemText(handle,ID,pstrText,iChars);
}
return pstrText; // Memory gets freed after it returns
工作示例:
char* MWC::System::TextBox::GetText(){
int len = SendMessage(handle, WM_GETTEXTLENGTH, 0, 0);
char* buffer = new char[len];
SendMessage(handle, WM_GETTEXT, (WPARAM)len+1, (LPARAM)buffer);
return buffer;
}
I've been trying to get this to work for like ages but with no avail (sad face).
int iChars = GetWindowTextLength (GetDlgItem(handle,ID))+1; // Room for '\0'
char* pstrText;
pstrText = (char*) malloc (sizeof(char)*iChars);
if (pstrText != NULL) {
//GetWindowText (GetDlgItem(handle,ID), pstrText, iChars);
GetDlgItemText(handle,ID,pstrText,iChars);
}
return pstrText; // Memory gets freed after it returns
Working example:
char* MWC::System::TextBox::GetText(){
int len = SendMessage(handle, WM_GETTEXTLENGTH, 0, 0);
char* buffer = new char[len];
SendMessage(handle, WM_GETTEXT, (WPARAM)len+1, (LPARAM)buffer);
return buffer;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这里的
wParam
参数是错误的:由于零终止符,您应该传递
len+1
。The
wParam
parameter is wrong here:You should pass
len+1
because of the zero-terminator.你在返回之前释放内存!
您必须为客户端提供一种在不再需要时将其释放的方法...
希望这会有所帮助!
You are freeing the memory before returning!!!
You must provide a way for the client to free when its no longer needed...
Hope this helps!
在返回之前,您已经释放了
pstrText
指向的内存。您应该返回一个实际上可以包含文本的字符串对象,并在释放时自动释放它。或者您必须要求调用者为字符串分配内存,但您只是包装了 API。You already free the memory pointed to by
pstrText
before you return. You should return a string object that can actually contain the text and frees it automatically on release. Or you'll have to ask the caller to allocate memory for the string, but then you are just wrapping the API.