在调试状态下,VC 等调试器可以捕捉程序中的 OutputDebugString 输出的信息。其实 OutputDebugString 就是往一片共享影射的内存中写入了一段数据,并创建了两个 Enevt,指明数据写入事件被触发。在非调试状态下,我们也可以通过编程实现捕捉 OutputDebugString 的输出。下面的代码演示了如何获取这些信息:
DWORD WINAPI CDebugTrack::TrackProc(PVOID pvParam)
{
HANDLE hMapping = NULL;
HANDLE hAckEvent = NULL;
PDEBUGBUFFER pdbBuffer = NULL;
TCHAR tzBuffer[MAX_DebugBuffer];
_Try
{
// 设置初始结果
m_dwResult = ERROR_INVALID_HANDLE;
// 打开事件句柄
hAckEvent = CreateEvent(NULL, FALSE, FALSE, TEXT("DBWIN_BUFFER_READY"));
_LeaveIf(hAckEvent == NULL);
m_hReadyEvent = CreateEvent(NULL, FALSE, FALSE, TEXT("DBWIN_DATA_READY"));
_LeaveIf(m_hReadyEvent == NULL);
// 创建文件映射
hMapping = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, MAX_DebugBuffer, TEXT("DBWIN_BUFFER"));
_LeaveIf(hMapping == NULL);
// 映射调试缓冲区
pdbBuffer = (PDEBUGBUFFER) MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
_LeaveIf(pdbBuffer == NULL);
// 循环
for (m_dwResult = ERROR_SIGNAL_PENDING; (m_dwResult == ERROR_SIGNAL_PENDING); )
{
// 等待缓冲区数据
SetEvent(hAckEvent);
if (WaitForSingleObject(m_hReadyEvent, INFINITE) == WAIT_OBJECT_0)
{
// 如果是继续等待,否则表示主线程发出了停止信号,退出当前线程
if (m_dwResult == ERROR_SIGNAL_PENDING)
{
// 添加新项
_AStrToStr(tzBuffer, pdbBuffer->szString);
CListView::AddDebugItem(tzBuffer, pdbBuffer->dwProcessId);
}
}
else
{
// 等待失败
m_dwResult = WAIT_ABANDONED;
}
}
}
_Finally
{
// 释放
if (pdbBuffer)
{
UnmapViewOfFile(pdbBuffer);
}
_SafeCloseHandle(hMapping);
_SafeCloseHandle(m_hReadyEvent);
_SafeCloseHandle(hAckEvent);
PostMessage(CMainWnd::m_hWnd, WM_COMMAND, IDC_DebugTrack, m_dwResult);
// 返回结果
return m_dwResult;
}
}
转帖:http://dev.csdn.net/article/48/48946.shtm
参考:http://blog.csdn.net/jia162/archive/2008/05/06/2398840.aspx