65.9K
CodeProject is changing. Read more.
Home

Self-debugger attach to process

starIconstarIconstarIconstarIconstarIcon

5.00/5 (2 votes)

Sep 30, 2011

CPOL
viewsIcon

14350

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:

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;
            }
        }
    }
}