I have a program that Process.Start()
another program, and it shuts it down after N seconds.
Sometimes I choose to attach a debugger to the started pro
You will need to P/Invoke down to CheckRemoteDebuggerPresent. This requires a handle to the target process, which you can get from Process.Handle.
if(System.Diagnostics.Debugger.IsAttached)
{
// ...
}
I know this is old, but I was having the same issue and realized if you have a pointer to the EnvDTE, you can check if the process is in Dte.Debugger.DebuggedProcesses:
foreach (EnvDTE.Process p in Dte.Debugger.DebuggedProcesses) {
if (p.ProcessID == spawnedProcess.Id) {
// stuff
}
}
The CheckRemoteDebuggerPresent call only checks if the process is being natively debugged, I believe - it won't work for detecting managed debugging.
var isDebuggerAttached = System.Diagnostics.Debugger.IsAttached;
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);
Process process = ...;
bool isDebuggerAttached = Dte.Debugger.DebuggedProcesses.Any(
debuggee => debuggee.ProcessID == process.Id);
The solution for me is Debugger.IsAttached as described here: http://www.fmsinc.com/free/NewTips/NET/NETtip32.asp