Is there a way to determine if a debugger is attached to a C # process?

I have a program that Process.Start () is another program, and it disables it after N seconds.

Sometimes I choose to attach a debugger to a running program. In these cases, I do not want the process to shut down after N seconds.

I want the host program to detect that the debugger is connected or not, so it may not close it.

Clarification: I am not looking to determine if the debugger is attached to my process, I am looking to determine if the debugger is attached to the process that I spawned.

+60
debugging c #
Feb 02 2018-10-02T00
source share
5 answers

You will need P / Invoke before CheckRemoteDebuggerPresent . This requires a handle to the target process, which you can get from Process.Handle.

+20
Feb 02 2018-10-02T00
source share
if(System.Diagnostics.Debugger.IsAttached) { // ... } 
+156
Feb 02 2018-10-02T00
source share

Is the current process debugged?

 var isDebuggerAttached = System.Diagnostics.Debugger.IsAttached; 

Is another process debugged?

 Process process = ...; bool isDebuggerAttached; if (!CheckRemoteDebuggerPresent(process.Handle, out isDebuggerAttached) { // handle failure (throw / return / ...) } else { // use isDebuggerAttached } /// <summary>Checks whether a process is being debugged.</summary> /// <remarks> /// The "remote" in CheckRemoteDebuggerPresent does not imply that the debugger /// necessarily resides on a different computer; instead, it indicates that the /// debugger resides in a separate and parallel process. /// <para/> /// Use the IsDebuggerPresent function to detect whether the calling process /// is running under the debugger. /// </remarks> [DllImport("Kernel32.dll", SetLastError=true, ExactSpelling=true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool CheckRemoteDebuggerPresent( SafeHandle hProcess, [MarshalAs(UnmanagedType.Bool)] ref bool isDebuggerPresent); 

Within the Visual Studio Extension

 Process process = ...; bool isDebuggerAttached = Dte.Debugger.DebuggedProcesses.Any( debuggee => debuggee.ProcessID == process.Id); 
+6
Oct 11 '16 at 20:49
source share

I know this is old, but I had the same problem, and I realized that you have a pointer to EnvDTE, you can check if this process is in Dte.Debugger.DebuggedProcesses :

 foreach (EnvDTE.Process p in Dte.Debugger.DebuggedProcesses) { if (p.ProcessID == spawnedProcess.Id) { // stuff } } 

Calling CheckRemoteDebuggerPresent checks if the process is really debugged, I believe that it will not work to detect managed debugging.

+5
Aug 09 '10 at 21:55
source share

The solution for me is Debugger.IsAttached, as described here: http://www.fmsinc.com/free/NewTips/NET/NETtip32.asp

0
Jan 26 '12 at 20:16
source share



All Articles