有没有办法检测调试器是否从C#连接到另一个进程?
我有一个程序,有没有办法检测调试器是否从C#连接到另一个进程?,c#,debugging,C#,Debugging,我有一个程序,Process.Start()另一个程序,它在N秒后关闭 有时我选择将调试器附加到已启动的程序。在这种情况下,我不希望进程在N秒后关闭 我希望宿主程序检测是否连接了调试器,以便它可以选择不关闭调试器 澄清:我不想检测调试器是否连接到我的进程,我想检测调试器是否连接到我生成的进程。您需要深入了解。这需要目标进程的句柄,您可以从process.handle获得该句柄。我知道这是旧的,但我遇到了相同的问题,并意识到如果您有指向EnvDTE的指针,您可以检查该进程是否处于: if(Syst
Process.Start()
另一个程序,它在N秒后关闭
有时我选择将调试器附加到已启动的程序。在这种情况下,我不希望进程在N秒后关闭
我希望宿主程序检测是否连接了调试器,以便它可以选择不关闭调试器
澄清:我不想检测调试器是否连接到我的进程,我想检测调试器是否连接到我生成的进程。您需要深入了解。这需要目标进程的句柄,您可以从process.handle获得该句柄。我知道这是旧的,但我遇到了相同的问题,并意识到如果您有指向EnvDTE的指针,您可以检查该进程是否处于:
if(System.Diagnostics.Debugger.IsAttached)
{
// ...
}
CheckRemoteDebuggerPresent调用仅检查进程是否正在进行本机调试,我相信-它无法检测托管调试。我的解决方案是Debugger.I如下所述:当前进程正在调试吗? 正在调试另一个进程吗?
这难道不告诉我调试器是否连接到主机进程吗?我正在寻找一种方法来确定生成的进程是否正在调试。我明白了,很抱歉误解了您的问题。我相信衍生过程是唯一可以查询这些信息的过程。如果设置某种形式的进程间通信,则允许原始进程轮询调试器状态。
foreach (EnvDTE.Process p in Dte.Debugger.DebuggedProcesses) {
if (p.ProcessID == spawnedProcess.Id) {
// stuff
}
}
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);