-1

I have a file browser in my project and when I click the file I would like it to open up in Visual Studio - I can do this at the moment. Then when I click another file, I would like Visual Studio to switch the focused file to the new file.

So far I have managed to open Visual Studio at the correct project and file with the following code.

Process p = new Process();
p.StartInfo.FileName = @"C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE\devenv.exe";
p.StartInfo.Arguments = projectPath+" "+ filePath;
p.Start();

I would like to be able to switch the file in Visual Studio based upon what I have clicked on in my project.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • Well, if the code is as shown, that would make sense as you start a new process every time. – ChiefTwoPencils Oct 27 '19 at 00:29
  • yea but im stuck at switching the file. – Dragon Head Oct 27 '19 at 00:31
  • 2
    For those of us that don't use Unity, *Like how Unity does it* has no meaning. Neither does *I would like to be able to switch files* with no explaination of what that means. It opens a new instance of VS because that's exactly what your code is telling it to do, and computers always do what they're told. – Ken White Oct 27 '19 at 00:36
  • So to clarify your question, the issue you're having and need guidance on, is how to open a file in an existing Visual Studio process\instance (devenv.exe). You're essentially implementing the "open [this file] with..." functionality of a context menu in explorer, right? Though you are stating which program you're intending to open this file with - This is probably a duplicate question. Though it is unclear in those questions whether a new process\instance of devenv.exe is created in their answers.. so I'm not certain enough to call this a duplicate question. – Brett Caswell Oct 27 '19 at 01:12
  • yea Im trying to open a file in an existing Visual Studio process\instance (devenv.exe). – Dragon Head Oct 27 '19 at 01:21
  • Based on my search, I find it is hard for us to switch the file. Therefore, I suggest that you could kill the current process and open another process. – Jack J Jun Oct 28 '19 at 02:29

1 Answers1

1

Found out how to do it. Getting EnvDTE.DTE instance outside Visual Studio IDE

DTE dte;

void OpenFile(string file, string project)
{
    if (dte == null)
    {
        Type visualStudioType = Type.GetTypeFromProgID("VisualStudio.DTE.16.0");
        dte = Activator.CreateInstance(visualStudioType) as DTE;
    }
    dte.ExecuteCommand("File.OpenProject", project);
    dte.ExecuteCommand("File.OpenFile", file);
    dte.MainWindow.Visible = true;
}