開發 ASP.NET 應用時,頻繁使用「偵錯 → 附加至處理序」選擇 w3wp.exe (IIS 6.0+) 或 aspnet_wp.exe (IIS 5.0) 極為繁瑣。透過 VS 巨集自動化此流程,一鍵完成附加,大幅提升效率。
在 巨集總管 中建立新巨集模組(如 DebuggerMacros),貼入以下程式碼:
Imports System
Imports EnvDTE
Imports EnvDTE80
Imports System.Diagnostics
Public Module Debugger
Public Sub AttachToWebServer()
Dim aspNetWp As String = "aspnet_wp.exe"
Dim w3wp As String = "w3wp.exe"
If Not AttachToProcess(aspNetWp) Then
If Not AttachToProcess(w3wp) Then
MsgBox(String.Format("找不到處理序 {0} 或 {1}", aspNetWp, w3wp), vbExclamation, "附加至 Web Server 巨集")
End If
End If
End Sub
Private Function AttachToProcess(ByVal processName As String) As Boolean
Dim processes As EnvDTE.Processes = DTE.Debugger.LocalProcesses
Dim processFound As Boolean = False
For Each proc As EnvDTE.Process In processes
' 處理序名稱格式為 "C:\Windows\System32\inetsrv\w3wp.exe",取檔名部分比對
If proc.Name.Substring(proc.Name.LastIndexOf("\"c) + 1).Equals(processName, StringComparison.OrdinalIgnoreCase) Then
proc.Attach()
processFound = True
Exit For
End If
Next
Return processFound
End Function
End Module
Macros.Debugger.AttachToWebServer 綁定熱鍵。w3wp.exe 或 aspnet_wp.exe。InputBox 或自訂表單)。DTE.Debugger.RemoteProcesses 連接遠端伺服器。DTE.ExecuteCommand("Debug.StartWithoutDebugging") 實現「建置→啟動→附加」一鍵流程。w3wp.exe,但模組載入路徑不同。