Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OutputDebugString / System.Diagnostics.Debug.WriteLine and Debugger.IsAttached

Tags:

c#

I need to check if OutputDebugString / System.Diagnostics.Debug.WriteLine's output will go to never never land.

Seems like OutputDebugString is a native method while System.Diagnostics.Debug.WriteLine is writing to internal trace listeners.

Is Debugger.IsAttached a sufficient check for this?

Debugger.IsAttached doesn't seem to pick up if something like DebugView is running. I need to be able to check if ANYTHING will see output from OutputDebugString / System.Diagnostics.Debug.WriteLine.

like image 387
SledgeHammer Avatar asked Mar 27 '26 00:03

SledgeHammer


1 Answers

If you are willing to get your hands dirty and use some native stuff you can achieve this. You'll need to use P/Invoke.

OutputDebugString, as you can read here, is based on 4 kernel objects. Mutex named DBWinMutex, a shared memory DBWIN_BUFFER and two events (DBWIN_BUFFER_READY and DBWIN_DATA_READY) as they wrote in the article - we can't relay on the mutex as it exists all the time. But we could check if the shared section is created.

If we import OpenFileMapping to our project from pinvoke.net

static class NativeFunctions
{
    [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
    static extern IntPtr OpenFileMapping(
        uint dwDesiredAccess, 
        bool bInheritHandle,
        string lpName);
}

Then we can check if the section is created or not and based on that decide whether something is listening.

Writing this simple program

public const int FILE_MAP_READ = 0x0004;
static void Main(string[] args)
{
    if (NativeFunctions.OpenFileMapping(FILE_MAP_READ, false, "DBWIN_BUFFER") != IntPtr.Zero)
    {
        Log("Someone is listening");
    }
    else
    {
        Log("I am here alone");
    }
}

private static void Log(string log)
{
    Debug.WriteLine(log);
    Console.WriteLine(log);
}

When running without DebugView we get "I'm here alone"

enter image description here

and with the tool

enter image description here

Additionally to clarify the things ".. while System.Diagnostics.Debug.WriteLine is writing to internal trace listeners." Debug.WriteLine will also write to the same place as OutputDebugString but only if VS is not attached - otherwise VS will capture the log and post to its Output window.

like image 56
Paweł Łukasik Avatar answered Mar 29 '26 14:03

Paweł Łukasik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!