Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / programming / debugging

Self-debugger attach to process

5.00/5 (2 votes)
30 Sep 2011CPOL 14.4K  
I was glad to integrate your code into my C# application.Actually, within the debugger windows, I can't recognize any human-readable reference to the calling process, but the function is working. :)So, for whoever may be interested, the following code is my C# 4 equivalent:using...

I was glad to integrate your code into my C# application.


Actually, within the debugger windows, I can't recognize any human-readable reference to the calling process, but the function is working. :)


So, for whoever may be interested, the following code is my C# 4 equivalent:


C#
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;

namespace MyApp.Diagnostics
{
    public static class DebugHelper
    {
        [DllImport("kernel32.dll")]
        static extern bool IsDebuggerPresent();

        [DllImport("kernel32.dll")]
        static extern void DebugBreak();

        public static bool AttachCurrentProcessToDebugger()
        {
            try
            {
                if (!IsDebuggerPresent())
                {
                    var sExePath = Path.Combine(Environment.SystemDirectory, 
                                   "VSJitDebugger.exe");

                    var process = Process.Start(sExePath, " -p " + 
                                  Process.GetCurrentProcess().Id);
                    process.WaitForExit();
                    if (process.ExitCode != 0)
                        return false;

                    for (int i = 0; i < 5 * 60; i++)
                    {
                        if (IsDebuggerPresent())
                            break;

                        Thread.Sleep(200);
                    }
                }

                DebugBreak();

                return true;
            }
            catch (Exception ex)
            {
                var sExMessage = (ex.InnerException != null ? 
                    ex.InnerException.Message + "; " : string.Empty)
                    + ex.Message
                    + ((ex.TargetSite != null) ? ex.TargetSite.ToString() : string.Empty);
                Debug.Print(ex.GetType().Name + ": " + sExMessage + ex.StackTrace);
                return false;
            }
        }
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)