How do I attach Visual Studio to a process that is not started yet?
Asked Answered
O

8

120

I have .NET program that can't be run from Visual Studio for some reasons (Excel file created from an Excel 2010 template project) for which I need to debug startup events.

If I want to debug events that comes after program initialisation there is no problem. I run the program from the explorer, attach the process to Visual Studio and add some breakpoints in the code. But here, I need to put breakpoints on the startup events. I need to be able to attach processes to Visual Studio, not depending on a PID, but on a specific process name or whatever other solution that would work.

Of course adding a Thread.Sleep(1000) in my startup events to give me some time to attach the process in Visual Studio is out of the question!

Octodecillion answered 17/11, 2011 at 13:9 Comment(0)
D
113

Actually you can; you don't attach to it, you start it. On the properties of your project, on the Debugging tab, specify the path of the program you want to attach to in the "Command" textbox.

You can also enter any command-line arguments for the program in the "Command Arguments" box:

enter image description here

Ensure that "Attach" is set to "No".

Demetra answered 17/11, 2011 at 13:21 Comment(6)
Good solution, but just note that hitting F5 does not work in this case. Instead rightclick the concerning project and click 'Debug > Start new instance' from the context menu.Cromwell
In order for F5 to work, your project has to be the Starting Project in the solution. To do that, in the solution explorer right click on the project and select "Set as startup project".Demetra
Also if your program has some external dependencies you need to change "Working Directory" as well.Irreplaceable
It may be required to check "Enable native code debugging" (project properties → DebugEnable Debuggers ).Lucid
And how do you do this for an entire solution with 40 projects?Patio
@TonyTannous You don't attach debuggers to solutions, you attach them to individual executables/processes. I would highly doubt all 40 projects are exes, so as long as the libraries you're trying to debug are referenced in your executable, you can debug that one.Malliemallin
C
50

Follow these steps if you have Visual Studio 2017-2022:

  1. File > Open > Project/Solution
  2. Choose your .exe
  3. Debug > Start Debugging

You will have to tell Visual Studio where the debugging symbols are if it doesn't find them automatically.

This is easier than other suggestions: you don't have to mess with project properties, and no extensions are needed.

Chazan answered 18/7, 2017 at 15:52 Comment(4)
quick easy able to do in 5 seconds, I love it. ThanksHolton
My exe was launched, but no breakpoint could be set. What should I do?Revenuer
How does one "Choose your .exe" in this scenario? My EXE is not a product of the VS solution.Zusman
@Zusman You should be able to select the .exe in the "Open Project/Solution" dialog window. You'll notice that the dialog window's "All Project Files" file filter (which is the default filter) includes *.exeChazan
R
29

I was debugging a C++ plugin in an externally spawned process that crashed by throwing an exception at startup and this worked perfectly for me:

Add the free Reattach Extension for Visual Studio. Ask it to reattach to the process name before it is launched. It will pop a modal dialog saying it is waiting for the process name to launch.

Now launch the process and the Visual Studio debugger will attach immediately, catching exceptions and hitting breakpoints.

Rating answered 14/10, 2014 at 20:42 Comment(3)
A thousand times yes!Ithunn
I got a deadlock. It requested admin auth when my target was launched, and after typing pwd and restarting vs, Reattach was gone. Only vs without admin auth contains Reattach.Revenuer
Doesn't work for me. It still attaches way too late, after the crash already happened. It seems to check for existing processes once every second, which is completely pointless for this application.Ewald
H
19

I found this answer when I was looking for something similar. In my case, I couldn't simply use the executable as my project's startup program because it needed to be started in a very specific environment that I couldn't reproduce easily (namly: started from cygwin).

I took a look at the Reattach Extension as suggested by mrstrange and also the very similar Attach To Anything extension... but my executable seemed to close too quickly for the extensions to notify and attach.

What finally helped me was this: https://mcmap.net/q/182935/-visual-studio-auto-attach-to-a-process-when-the-process-is-spawned, which references the MSDN article How to: Launch the Debugger Automatically, which in-turn lists the following steps:

  1. Start the Registry Editor (regedit).
  2. In the Registry Editor, open the HKEY_LOCAL_MACHINE folder.
  3. Navigate to HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\currentversion\image file execution options.
  4. In the Image File Execution Options folder, locate the name of the application you want to debug, such as myapp.exe. If you cannot find the application you want to debug:
    a. Right-click the Image File Execution Options folder, and on the shortcut menu, click New Key.
    b. Right-click the new key, and on the shortcut menu, click Rename. c. Edit the key name to the name of your application; myapp.exe, in this example.
  5. Right-click the myapp.exe folder, and on the shortcut menu, click New String Value.
  6. Right-click the new string value, and on the shortcut menu, click Rename.
  7. Change the name to debugger.
  8. Right-click the new string value, and on the shortcut menu, click Modify. The Edit String dialog box appears.
  9. In the Value data box, type vsjitdebugger.exe.
  10. Click OK.
  11. From the Registry menu, click Exit.
  12. The directory containing vsjitdebugger.exe must be in your system path. To add it to the system path, follow these steps:
    a. Open the Control Panel in Classic view, and double-click System.
    b. Click Advanced System Settings.
    c. In System Properties, click the Advanced tab.
    d. On the Advanced tab, click Environment Variables.
    e. In the Environment Variables dialog box, under System variables, select Path, then click the Edit button.
    f. In the Edit System Variable dialog box, add the directory to the Variable value box. Use a semicolon to separate it from other entries in the list.
    g. Click OK to close the Edit System Variable dialog box.
    h. Click OK to close the Environment Variables dialog box.
    i. Click OK to close the System Properties dialog box.
  13. Now, use any method to start your application. Visual Studio will start and load the application.

Hope that this helps anyone else in the future!

Harker answered 11/5, 2016 at 15:12 Comment(5)
Here are the instructions for this same process with newer versions of VS (up to 2019): learn.microsoft.com/en-us/visualstudio/debugger/…Hut
thanks both of you. I did so, but I get the "Visual Studio just-in-time debugger was not notified that the application correctly started" error. For this I started investigating more, further reading: #6677661Gambrill
more reading on just in time debugger learn.microsoft.com/en-us/visualstudio/debugger/…Gambrill
You may also have to set HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AeDebug\Auto (REG_SZ) to 1 developercommunity.visualstudio.com/t/…Lemons
Point 12. (vsjitdebugger.exe to PATH) may be ommitted if an absolute path is providedLemons
A
18

You can start the debugger from your code via

public static void Main(string[] args)
{
  System.Diagnostics.Debugger.Launch();
}

But don't for get to remove this line before shipping your application. Maybe you want to use compiler flags to be sure:

    public static void Main(string[] args)
    {
      #if debug
      System.Diagnostics.Debugger.Launch();
      #endif
    }
Aparejo answered 24/1, 2020 at 7:7 Comment(1)
This should be the accepted answer for all cases where you are waiting for some external process to launch your application.Bullwhip
Z
6

You can show a MessageBox, this would block the application, then you attach or reattach the debugger to the process and click ok to continue:

MessageBox.Show("Attach process to debugger and click ok!");

you can add it to the Form constructor (if you use winforms), so this would be executed before anything else, except for the initialization of components:

public MainForm()
{
    InitializeComponent();
    MessageBox.Show("Attach process to debugger and click ok!");
}

When you finish your debugging, comment out that line.

Zakarias answered 3/4, 2018 at 13:49 Comment(0)
T
4

One little solution that might suit many people.

  • in the first line of code that the exe will run, add this command

    System.Threading.Thread.Sleep(20000)

That will make the exe sleep for 20 seconds before it starts processing anything. Then you have 20 seconds to attach to the process, which can be done quickly with ctrl+alt+p, then find the process, then enter to attach.

Not much of an answer but worked a treat for me :--)

Tillage answered 11/3, 2018 at 19:25 Comment(1)
I had to debug a CGI written in "C" for which I had the source code. I was a simple and easy solution to have time to attach to the background process.Tramroad
Y
3

If there's no process then Visual Studio can't attach to it.

However, you can set the startup program of your project to be something other than the output of your project.

Yaker answered 17/11, 2011 at 13:12 Comment(2)
I already investigated if what I want to do is right, and actually it is. My situation is not a usual Visual Studio debugging case. I have a Excel 2010 template project developed in Visual Studio and the template sheets have startup events. I run this template from Visual Studio, add some data in my Excel sheets and save the file on the disk. Then the only way I can open this file that also relies on the template assembly, is to open it from the explorer, therefore I cannot debug the startup events in this case and of course I have some data processing on startup like databinding.Octodecillion
It may be required to check "Enable native code debugging" (project properties → DebugEnable Debuggers ).Lucid

© 2022 - 2024 — McMap. All rights reserved.