将 OutputDebugString 记录到文件(没有 DebugView)

Dan*_*ich 6 winapi

我的 WPF 应用程序使用第三方 Win32 dll,通过 OutputDebugString 记录消息。

我可以在 Visual Studio 中或通过 DebugView 查看 OutputDebugString 消息,但我不想要求客户运行 DebugView。我想从 OutputDebugString 捕获消息并自动将它们记录到文件中,因此如果客户遇到问题,我可以要求她向我发送该日志文件。

这可能吗?或者用户是否必须启动 DebugView,重现错误,然后以这种方式向我发送日志?

小智 4

OutputDebugStringW。我建议为此使用Detours库。

#include <windows.h>
#include <detours.h>
#pragma comment(lib, "detours.lib")

BOOL SetHook(__in BOOL bState, __inout PVOID* ppPointer, __in PVOID pDetour)
{
  if (DetourTransactionBegin() == NO_ERROR)
    if (DetourUpdateThread(GetCurrentThread()) == NO_ERROR)
      if ((bState ? DetourAttach : DetourDetach)(ppPointer, pDetour) == NO_ERROR)
        if (DetourTransactionCommit() == NO_ERROR)
          return TRUE;
  return FALSE;
{

#define InstallHook(x, y) SetHook(TRUE, x, y)  

VOID (WINAPI * _OutputDebugStringW)(__in_z_opt LPCWSTR lpcszString) = OutputDebugStringW;

VOID WINAPI OutputDebugStringHook(__in_z_opt LPCWSTR lpcszString)
{
  // do something with the string, like write to file

  _OutputDebugStringW(lpcszString);
}

// somewhere in your code
InstallHook((PVOID*)&_OutputDebugStringW, OutputDebugStringHook);
Run Code Online (Sandbox Code Playgroud)