【发布时间】:2011-01-12 09:23:53
【问题描述】:
我有一个程序 Process.Start() 另一个程序,它在 N 秒后将其关闭。
有时我选择将调试器附加到已启动的程序中。在这些情况下,我不希望进程在 N 秒后关闭。
我希望主机程序检测是否连接了调试器,因此它可以选择不关闭它。
澄清:我不希望检测是否有调试器附加到 my 进程,我希望检测是否有调试器附加到我的进程产生了。
【问题讨论】:
我有一个程序 Process.Start() 另一个程序,它在 N 秒后将其关闭。
有时我选择将调试器附加到已启动的程序中。在这些情况下,我不希望进程在 N 秒后关闭。
我希望主机程序检测是否连接了调试器,因此它可以选择不关闭它。
澄清:我不希望检测是否有调试器附加到 my 进程,我希望检测是否有调试器附加到我的进程产生了。
【问题讨论】:
if(System.Diagnostics.Debugger.IsAttached)
{
// ...
}
【讨论】:
您需要将P/Invoke 降至CheckRemoteDebuggerPresent。这需要目标进程的句柄,您可以从 Process.Handle 中获取该句柄。
【讨论】:
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);
【讨论】:
我知道这是旧的,但我遇到了同样的问题并意识到如果你有指向 EnvDTE 的指针,你可以检查进程是否在 Dte.Debugger.DebuggedProcesses:
foreach (EnvDTE.Process p in Dte.Debugger.DebuggedProcesses) {
if (p.ProcessID == spawnedProcess.Id) {
// stuff
}
}
CheckRemoteDebuggerPresent 调用仅检查进程是否正在本地调试,我相信 - 它不适用于检测托管调试。
【讨论】:
我的解决方案是 Debugger.IsAttached,如下所述:http://www.fmsinc.com/free/NewTips/NET/NETtip32.asp
【讨论】: