Skip to content

Instantly share code, notes, and snippets.

@chuongmep
Created December 6, 2025 13:20
Show Gist options
  • Select an option

  • Save chuongmep/f602d91bdbb13665bd6debf3ff79e58c to your computer and use it in GitHub Desktop.

Select an option

Save chuongmep/f602d91bdbb13665bd6debf3ff79e58c to your computer and use it in GitHub Desktop.
private static bool TryAttachVisualStudioDebugger(int processId)
{
try
{
// Get the DTE object for the current Visual Studio instance
var dte = GetCurrentVisualStudioDTE();
if (dte == null)
return false;
// Get the debugger
var debugger = dte.Debugger;
// Get local processes
var processes = debugger.LocalProcesses;
// Find the target process
foreach (EnvDTE.Process process in processes)
{
if (process.ProcessID == processId)
{
// Attach to the process with mixed mode debugging
process.Attach();
return true;
}
}
return false;
}
catch
{
// If we can't attach programmatically, return false
return false;
}
}
/// <summary>
/// Gets the DTE object for the currently running Visual Studio instance that's debugging us.
/// </summary>
private static EnvDTE.DTE GetCurrentVisualStudioDTE()
{
try
{
// Try to get the VS DTE from the Running Object Table
IRunningObjectTable rot;
IEnumMoniker enumMoniker;
int retVal = GetRunningObjectTable(0, out rot);
if (retVal != 0)
return null;
rot.EnumRunning(out enumMoniker);
enumMoniker.Reset();
IntPtr fetched = IntPtr.Zero;
IMoniker[] moniker = new IMoniker[1];
while (enumMoniker.Next(1, moniker, fetched) == 0)
{
IBindCtx bindCtx;
CreateBindCtx(0, out bindCtx);
string displayName;
moniker[0].GetDisplayName(bindCtx, null, out displayName);
// Look for Visual Studio DTE objects
if (displayName.StartsWith("!VisualStudio.DTE."))
{
object obj;
rot.GetObject(moniker[0], out obj);
if (obj is EnvDTE.DTE dte)
{
// Check if this VS instance is currently debugging
try
{
// If VS is in debug mode, it's likely the one debugging our test process
if (dte.Debugger.CurrentMode != EnvDTE.dbgDebugMode.dbgDesignMode)
{
return dte;
}
}
catch
{
// Continue searching
}
}
}
}
return null;
}
catch
{
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment