forked from gitextensions/gitextensions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVisualStudioIntegration.cs
100 lines (79 loc) · 3.04 KB
/
VisualStudioIntegration.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using EnvDTE;
namespace GitUI
{
internal static class VisualStudioIntegration
{
public static bool TryOpenFile(string filePath)
{
ThreadHelper.ThrowIfNotOnUIThread();
if (!File.Exists(filePath))
{
// When opening the context menu, we disable this item if the file does not exist.
// So, we should not experience this situation in practice (barring some exotic race conditions).
return false;
}
foreach (DTE dte in GetVisualStudioInstances())
{
ProjectItem projectItem = dte.Solution.FindProjectItem(filePath);
if (projectItem != null)
{
// Open the file
dte.ExecuteCommand("File.OpenFile", filePath);
// Bring the Visual Studio window to the front of the desktop
NativeMethods.SetForegroundWindow(new IntPtr(dte.MainWindow.HWnd));
return true;
}
}
return false;
}
public static bool IsVisualStudioRunning => GetVisualStudioInstances().Any();
private static IEnumerable<DTE> GetVisualStudioInstances()
{
int retVal = NativeMethods.GetRunningObjectTable(0, out IRunningObjectTable rot);
if (retVal != 0)
{
yield break;
}
rot.EnumRunning(out IEnumMoniker enumMoniker);
const int count = 1;
var moniker = new IMoniker[count];
while (enumMoniker.Next(count, moniker, pceltFetched: IntPtr.Zero) == 0)
{
NativeMethods.CreateBindCtx(0, out IBindCtx bindCtx);
string? displayName = null;
try
{
moniker[0].GetDisplayName(bindCtx, null, out displayName);
}
catch (UnauthorizedAccessException)
{
// Some ROT objects require elevated permissions.
}
// Display name example: "!VisualStudio.DTE.16.0:73424"
if (displayName?.StartsWith("!VisualStudio") == true)
{
rot.GetObject(moniker[0], out object obj);
if (obj is DTE dte)
{
yield return dte;
}
}
}
}
private static class NativeMethods
{
[DllImport("user32.dll")]
public static extern bool SetForegroundWindow(IntPtr hwnd);
[DllImport("ole32.dll")]
public static extern void CreateBindCtx(int reserved, out IBindCtx ppbc);
[DllImport("ole32.dll")]
public static extern int GetRunningObjectTable(int reserved, out IRunningObjectTable prot);
}
}
}