Get the handle and write to the console that launched our process

前端 未结 4 1725
清歌不尽
清歌不尽 2021-02-06 16:54

How could I write to the standard output of some already open console? I find the console I need with this piece of code:

    IntPtr ptr = GetForegroundWindow();         


        
4条回答
  •  感动是毒
    2021-02-06 17:23

    If you just want to write to the console that's used by some other app, then you can use the following - you'll need to use P/Invoke to do the first step:

    • AttachConsole(pid) to attach to that console - if your process is already associated with a console, you'll have to FreeConsole first, since a process can be associated with only one console at a time.
    • Now that you're attached, get the console output handle using CreateFile("CONOUT$", GENERIC_WRITE, FILE_SHARE_WRITE, ... ) - might be able to do this part in managed code.
    • Now that you've got the HANDLE, wrap it up in managed code - this part you already know.

    Having said that, even though you can do this, it's not necessarily a good idea to do so. There's nothing to stop the original process from writing to the console while you are doing likewise, and the output from both getting mixed-up, depending on how the processes are doing buffering. If you want to do something like notify the user of something regardless of which window is active, there may be a better way of doing that.

提交回复
热议问题