I’d like to be able to automatically attach a debugger, something like: System.Diagnostics.Debugger.Launch(), except rather than the current process to another named process. I’ve got a process name and PID to identify the other process.
Is this possible?
Edit:
GSerjooffered the correct solution. I’d like to share a few thoughts on how to improve it (and an explanation). I hope my improved answer will be useful to to others who experience the same problem.Attaching the VS Debugger to a Process
Manually
Processes.Debug.Or, within Visual Studio, select
Debug > Attach to Process....Results will vary depending on whether you have access to the source code.
Automatically with C#
First of all, add a reference to EnvDTE to your project (right click on the references folder in the solution explorer, add reference). In the following code, I’ll only show the unusual using directives; the normal ones such as
using Systemare omitted.Because you are interacting with COM you need to make sure to decorate your
Mainmethod (the entry point of your application) with theSTAThreadAttribute.Then, you need to define the
IOleMessageFilterInterface that will allow you to interact with the defined COM methods (note theComImportAttribute). We need to access the message filter so we can retry if the Visual Studio COM component blocks one of our calls.Now, we need to implement this interface in order to handle incoming messages:
I defined the return values as constants for better readability and refactored the whole thing a bit to get rid of some of the duplication from the MSDN example, so I hope you’ll find it self-explanatory.
extern int CoRegisterMessageFilteris our connection to the unmanaged message filter code – you can read up on the extern keyword at MSDN.Now all that’s left is some code illustrating the usage: