3

我将一个DLL注入一个进程,在该进程的入口点我产生一个新线程并分配一个控制台,我将所有std重定向到控制台,当我关闭控制台窗口时,整个进程关闭,有没有办法这样它就不会关闭进程?这是我的代码:

入口点:

#pragma region EntryPoint
BOOL APIENTRY DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
    switch (ul_reason_for_call)
    {
        case DLL_PROCESS_ATTACH:
            {
                DWORD threadId;
                hProcess = GetCurrentProcess();
                hThread = CreateThread( NULL, 0, Attach, 0, 0, &threadId);
            } break;
        case DLL_PROCESS_DETACH:
            CloseHandle(hThread);
        break;
    }
    return TRUE;
}
#pragma endregion EntryPoint

附:

DWORD WINAPI Attach(LPVOID args)
{
    RedirectIOToConsole();
}

这是控制台代码:

#include "hFatboy.h"

#ifndef _USE_OLD_IOSTREAMS
using namespace std;
#endif

static const WORD MAX_CONSOLE_LINES = 500;
extern HANDLE hProcess;

byte *readMemory(DWORD address, int length)
{
    byte *buffer = new byte[length];
    SIZE_T bytesRead;
    if (ReadProcessMemory(hProcess, (void *)address, buffer, length, &bytesRead))
        return buffer;

    return NULL;
}
void RedirectIOToConsole()
{
    int hConHandle;
    long lStdHandle;

    CONSOLE_SCREEN_BUFFER_INFO coninfo;
    FILE *fp;

    AllocConsole();
    GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &coninfo);
    coninfo.dwSize.Y = MAX_CONSOLE_LINES;
    SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), coninfo.dwSize);

    lStdHandle = (long)GetStdHandle(STD_OUTPUT_HANDLE);
    hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);

    fp = _fdopen( hConHandle, "w" );

    *stdout = *fp;

    setvbuf( stdout, NULL, _IONBF, 0 );

    lStdHandle = (long)GetStdHandle(STD_INPUT_HANDLE);
    hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);

    fp = _fdopen( hConHandle, "r" );

    *stdin = *fp;

    setvbuf( stdin, NULL, _IONBF, 0 );

    lStdHandle = (long)GetStdHandle(STD_ERROR_HANDLE);
    hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);

    fp = _fdopen( hConHandle, "w" );

    *stderr = *fp;

    setvbuf( stderr, NULL, _IONBF, 0 );

    ios::sync_with_stdio();
}
4

1 回答 1

1

你可以尝试注册一个HandlerRoutineSetConsoleCtrlHandler然后,您将能够拦截关闭事件CTRL_CLOSE_EVENT并避免调用ExitProcess.

于 2012-12-19T15:00:50.950 回答