简体   繁体   English

从编辑控件(Pure Win32 API)获取文本

[英]Get Text from an Edit Control (Pure Win32 API)

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;
}

The wParam parameter is wrong here: wParam参数在这里是错误的:

SendMessage(handle, WM_GETTEXT, (WPARAM)len, (LPARAM)buffer);

You should pass len+1 because of the zero-terminator. 由于零终止符,您应该传递len+1

You are freeing the memory before returning!!! 你回来之前就释放了记忆!

if ((pstrText != NULL) {
    GetDlgItemText(handle,ID,pstrText,sizeof(pstrText));
    free (pstrText); // Freeing memory Here!
}

You must provide a way for the client to free when its no longer needed... 当客户不再需要时,您必须为客户提供免费的方式...

Hope this helps! 希望这可以帮助!

You already free the memory pointed to by pstrText before you return. 在返回之前,您已经释放了pstrText指向的内存。 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. 或者你必须要求调用者为字符串分配内存,但是你只需要包装API。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM