如何从指针获取字符串

时间:2014-04-11 06:50:22

标签: winapi

GetWindowThreadProcessId(hwndFoundWindow, &dwTrayProcessID);
HANDLE  hTrayProc = OpenProcess(PROCESS_ALL_ACCESS, 0, dwTrayProcessID);
int iButtonsCount = SendMessage(hwndFoundWindow, TB_BUTTONCOUNT, 0, 0);
LPVOID  lpData = VirtualAllocEx(hTrayProc, NULL, sizeof(TBBUTTON), MEM_COMMIT, PAGE_READWRITE);
int         iButton;
DWORD       dwBytesRead;
TBBUTTON   buttonData;

dwBytesRead = -1;
int chk_data = (int)SendMessage(hwndFoundWindow, TB_GETBUTTON, iButton, (LPARAM)lpData);
ReadProcessMemory(hTrayProc, lpData, &buttonData, sizeof(TBBUTTON), &dwBytesRead);

int len_text = (int)SendMessage(hwndFoundWindow, TB_GETBUTTONTEXTW, buttonData.idCommand, (LPARAM)lpData);

到现在为止,我知道按钮文本的长度,但我还需要在控制台上显示文本。 我的问题是我真的不知道如何从按钮获取该文本。请帮助。

我正在尝试的是...尝试访问lpData以获取字符串,但无法做到。

2 个答案:

答案 0 :(得分:0)

我的第一个评论是您需要在代码中添加错误检查。据我所见,您不会检查返回值。您调用的任何API函数都可能失败。如果您没有检查错误的返回值,那么您无法诊断出错的地方。

例如,从GetWindowThreadProcessId开始,您需要像这样写:

if (GetWindowThreadProcessId(hwndFoundWindow, &dwTrayProcessID) == 0)
{
    // handle error
}

等等所有其他功能。请仔细查阅MSDN,了解每个功能如何发出故障信号。

现在问题的主要部分。我相信这是TB_GETBUTTONTEXTW消息给你带来麻烦。你需要这样写:

LRESULT len = SendMessage(hwndFoundWindow, TB_GETBUTTONTEXTW, 
    buttonData.idCommand, NULL);
if (len == -1)
{
    // handle error
}

size_t size = sizeof(wchar_t)*(len+1);

LPVOID lpData = VirtualAllocEx(hTrayProc, NULL, size, MEM_COMMIT, PAGE_READWRITE);
if (lpData == NULL)
{
    // handle error
}

len = SendMessage(hwndFoundWindow, TB_GETBUTTONTEXTW, 
    buttonData.idCommand, (LPARAM)lpData);
if (len == -1)
{
    // handle error
}

wchar_t* str = new wchar_t[len+1];

if (!ReadProcessMemory(hTrayProc, lpData, (LPVOID)str, size, NULL))
{
    // handle error
}

// the text is now in str, as a null-terminated UTF-16 string

delete[] str;

答案 1 :(得分:-1)

你需要这样:(见documentation of TB_GETBUTTONTEXTW)。

WCHAR *buffer ;
int len_text = (int)SendMessage(hwndFoundWindow, TB_GETBUTTONTEXTW, 
                                buttonData.idCommand, (LPARAM)NULL); 

buffer = (WCHAR*)malloc(sizeof(WCHAR) * (len_text + 1)) ;
SendMessage(hwndFoundWindow, TB_GETBUTTONTEXTW, 
                                buttonData.idCommand, (LPARAM)buffer); 

....
free(buffer) ;