为什么API在c++中挂钩extextout和DrawText只输出垃圾

Why does API hooking ExtTextOut and DrawText in C++ only output rubbish?

本文关键字:DrawText 输出 extextout API c++ 为什么      更新时间:2023-10-16

我正在尝试使用Detour从第三方程序提取文本输出的API钩子。然而,我只得到垃圾,大量的数字和没有文本输出。

这些函数到底在什么时候被调用?除了文字,他们还被要求画其他东西吗?如果第三方程序使用一些高级工具来避免拦截这些调用,是否有一些基本的示例,我可以尝试确保我的方法确实正确接收文本?换句话说,在窗口中是否有一些程序使用这些方法在屏幕上绘制文本?

我的代码如下:

BOOL (__stdcall *Real_ExtTextOut)(HDC hdc,int x, int y, UINT options, const RECT* lprc,LPCWSTR text,UINT cbCount, const INT* lpSpacingValues) = ExtTextOut;
BOOL (__stdcall *Real_DrawText)(HDC hdc, LPCWSTR text,  int nCount, LPRECT lpRect, UINT uOptions) = DrawText;
int WINAPI Mine_DrawText(HDC hdc, LPCWSTR text,  int nCount, LPRECT lpRect, UINT uOptions)
{
        ofstream myFile;
    myFile.open ("C:\temp\textHooking\textHook\example.txt", ios::app);
    for(int i = 0; i < nCount; ++i)
        myFile << text[i];
    myFile << endl;
    int rv = Real_DrawText(hdc, text, nCount, lpRect, uOptions);
    return rv;
}
BOOL WINAPI Mine_ExtTextOut(HDC hdc, int X, int Y, UINT options, RECT* lprc, LPCWSTR text, UINT cbCount, INT* lpSpacingValues)
{
    ofstream myFile;
    myFile.open ("C:\temp\textHooking\textHook\example2.txt", ios::app);
    for(int i = 0; i < cbCount; ++i)
        myFile << text[i];
    myFile << endl;
    BOOL rv = Real_ExtTextOut(hdc, X, Y, options, lprc, text, cbCount, lpSpacingValues);
    return rv;
}
// Install the DrawText detour whenever this DLL is loaded into any process
BOOL APIENTRY DllMain( HMODULE hModule, DWORD  ul_reason_for_call, LPVOID lpReserved){
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
            DetourTransactionBegin();
            DetourUpdateThread(GetCurrentThread());
            DetourAttach(&(PVOID&)Real_ExtTextOut, Mine_ExtTextOut);
            DetourAttach(&(PVOID&)Real_DrawText, Mine_DrawText);
            DetourTransactionCommit();
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
        break;
    }
    return TRUE;
}

您正在将UTF-16字符代码写成整数。因此,文件中充满了数字。直接将文本缓冲区移到文件中可能更简单:

ofstream myFile;
myFile.open("C:\temp\textHooking\textHook\example.txt", ios::app);
myFile.write(reinterpret_cast<const char*>text, nCount*sizeof(*text));
myFile << endl;

您可能希望将UTF-16LE BOM放在文件的前面,以帮助您的文本编辑器计算出正在使用的编码。