在开发过程中,经常需要调试运行中的程序。对于Visual Studio用户来说,通常的做法是使用“附加到进程”功能。然而,这个过程可能会变得繁琐,尤其是当应用程序名称以英文字母表后半部分的常见字母开头时,或者当长时间工作在一个项目上,选择错误的进程变得容易。
为了简化这个过程,可以编写一个宏,这个宏会自动找到启动项目的输出文件路径,并附加到对应的进程。这样,就不需要手动在进程列表中搜索并选择应用程序了。
JustAttach 宏是一个Visual Studio宏,它会自动附加到解决方案的启动项目的输出文件路径对应的进程。以下是如何使用这个宏的步骤:
现在,每当需要附加到进程时,只需按下设置的快捷键,宏就会自动执行。
以下是JustAttach宏的完整代码。这个宏首先找到启动项目的输出文件路径,然后附加到对应的进程。
Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports System.Diagnostics
Public Module SenthilMacros
Public Sub JustAttach()
Dim solutionBuild As SolutionBuild = DTE.Solution.SolutionBuild
Dim startupProjectName As String = solutionBuild.StartupProjects(0)
If String.IsNullOrEmpty(startupProjectName) Then
MsgBox("Could not attach because the startup project could not be determined", MsgBoxStyle.Critical, "Failed to Attach")
Return
End If
Dim startupProject As Project = FindProject(startupProjectName.Trim())
Dim outputFilePath As String = FindOutputFileForProject(startupProject)
If String.IsNullOrEmpty(outputFilePath) Then
MsgBox("Could not attach because output file path for the startup project could not be determined", MsgBoxStyle.Critical, "Failed to Attach")
Return
End If
Attach(outputFilePath)
End Sub
Private Sub Attach(ByVal file As String)
Dim process As EnvDTE.Process
For Each process In DTE.Debugger.LocalProcesses
If process.Name = file Then
process.Attach()
Return
End If
Next
MsgBox("Could not attach because " + file + " is not found in the list of running processes", MsgBoxStyle.Critical, "Failed to Attach")
End Sub
Private Function FindProject(ByVal projectName As String) As Project
Dim project As Project
For Each project In DTE.Solution.Projects
If project.UniqueName = projectName Then
Return project
End If
Next
End Function
Private Function FindOutputFileForProject(ByVal project As Project) As String
Dim fileName As String = _
project.Properties.Item("OutputFileName").Value.ToString()
Dim projectPath As String = _
project.Properties.Item("LocalPath").Value.ToString()
Dim config As Configuration = _
project.ConfigurationManager.ActiveConfiguration
Dim buildPath = config.Properties.Item("OutputPath").Value.ToString()
If String.IsNullOrEmpty(fileName) Or String.IsNullOrEmpty(projectPath) Then
Return ""
End If
Dim folderPath As String = System.IO.Path.Combine(projectPath, buildPath)
Return System.IO.Path.Combine(folderPath, fileName)
End Function
End Module