def disconnectConsole():
    global consoleObject, consoleOutputHandle, consoleWinEventHookHandles, checkDeadTimer
    if not consoleObject:
        log.debugWarning("console was not connected")
        return False
    checkDeadTimer.Stop()
    checkDeadTimer = None
    #Unregister any win events we are using
    for handle in consoleWinEventHookHandles:
        winUser.unhookWinEvent(handle)
    consoleEventHookHandles = []
    consoleObject.stopMonitoring()
    winKernel.closeHandle(consoleOutputHandle)
    consoleOutputHandle = None
    consoleObject = None
    try:
        wincon.SetConsoleCtrlHandler(_consoleCtrlHandler, False)
    except WindowsError:
        pass
    #Try freeing NVDA from this console
    try:
        wincon.FreeConsole()
    except WindowsError:
        pass
    return True
def connectConsole(obj):
    global consoleObject, consoleOutputHandle, checkDeadTimer
    #Get the process ID of the console this NVDAObject is fore
    processID, threadID = winUser.getWindowThreadProcessID(obj.windowHandle)
    #Attach NVDA to this console so we can access its text etc
    try:
        wincon.AttachConsole(processID)
    except WindowsError as e:
        log.debugWarning("Could not attach console: %r" % e)
        return False
    wincon.SetConsoleCtrlHandler(_consoleCtrlHandler, True)
    consoleOutputHandle = winKernel.CreateFile(
        u"CONOUT$", winKernel.GENERIC_READ | winKernel.GENERIC_WRITE,
        winKernel.FILE_SHARE_READ | winKernel.FILE_SHARE_WRITE, None,
        winKernel.OPEN_EXISTING, 0, None)
    #Register this callback with all the win events we need, storing the given handles for removal later
    for eventID in (winUser.EVENT_CONSOLE_CARET,
                    winUser.EVENT_CONSOLE_UPDATE_REGION,
                    winUser.EVENT_CONSOLE_UPDATE_SIMPLE,
                    winUser.EVENT_CONSOLE_UPDATE_SCROLL,
                    winUser.EVENT_CONSOLE_LAYOUT):
        handle = winUser.setWinEventHook(eventID, eventID, 0,
                                         consoleWinEventHook, 0, 0, 0)
        if not handle:
            raise OSError("could not register eventID %s" % eventID)
        consoleWinEventHookHandles.append(handle)
    consoleObject = obj
    checkDeadTimer = gui.NonReEntrantTimer(_checkDead)
    checkDeadTimer.Start(CHECK_DEAD_INTERVAL)
    return True