visual-studio 很棒的 Visual Studio 宏
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/523220/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Awesome Visual Studio Macros
提问by BBetances
For a small community discussion, what are some essential Visual Studio macros you use?
对于小型社区讨论,您使用了哪些基本的 Visual Studio 宏?
I just started learning about them, and want to hear what some of you can't live without.
我刚刚开始了解它们,想听听你们中的一些人离不开什么。
采纳答案by Cerebrus
I used to employ a lot of macros in VS 2002/2003. One example would be Region creation - I always like my classes to be divided into the following regions - "Private members", "Public Properties", "Public Methods" and "Private methods". So, I have a macro mapped to a shortcut key that creates these regions in any new class file.
我曾经在 VS 2002/2003 中使用过很多宏。一个例子是区域创建——我总是喜欢将我的类划分为以下区域——“私有成员”、“公共属性”、“公共方法”和“私有方法”。所以,我有一个宏映射到一个快捷键,可以在任何新的类文件中创建这些区域。
Refactoring support in VS 2005/2008 (and the facility of adding common code snippets) as well as the use of Addins like DXCore and SlickEdit allow me to work without having to create too many macros anymore.
VS 2005/2008 中的重构支持(以及添加通用代码片段的功能)以及使用 DXCore 和 SlickEdit 等插件使我无需再创建太多宏即可工作。
回答by Aardvark
I add buttons on the toolbar for the following 3 macros. Each will take the currently selected text in any file and google it (or MSDN-it, or spell-check-it). Make up a nifty icon for the toolbar for extra style-points.
我在工具栏上为以下 3 个宏添加了按钮。每个都将在任何文件中获取当前选定的文本并用谷歌搜索它(或 MSDN-it,或拼写检查)。为工具栏制作一个漂亮的图标以获得额外的样式点。
Private Const BROWSER_PATH As String = "C:\Program Files\Mozilla Firefox\firefox.exe"
Sub SearchGoogle()
    Dim cmd As String
    cmd = String.Format("{0} http://www.google.com/search?hl-en&q={1}", BROWSER_PATH, DTE.ActiveDocument.Selection.Text)
    Shell(cmd, AppWinStyle.NormalFocus)
End Sub
Sub SearchMSDN()
    Dim cmd As String
    cmd = String.Format("{0} http://www.google.com/search?hl-en&q={1}+site%3Amsdn.microsoft.com", BROWSER_PATH, DTE.ActiveDocument.Selection.Text)
    Shell(cmd, AppWinStyle.NormalFocus)
End Sub
Sub SpellCheck()
    Dim cmd As String
    cmd = String.Format("{0} http://www.spellcheck.net/cgi-bin/spell.exe?action=CHECKWORD&string={1}", BROWSER_PATH, DTE.ActiveDocument.Selection.Text)
    Shell(cmd, AppWinStyle.NormalFocus)
End Sub
回答by Ryan Lundy
Show build duration in the Output window
在输出窗口中显示构建持续时间
Put this code in your EnvironmentEvents module. This will write the duration directly to the build window for any action on a solution (build, rebuild, clean, deploy).
将此代码放在您的 EnvironmentEvents 模块中。这会将持续时间直接写入构建窗口,用于解决方案上的任何操作(构建、重建、清理、部署)。
You can change the IsBuild function to specify the actions you want to see this information for.
您可以更改 IsBuild 函数以指定要查看其信息的操作。
Dim buildStart As Date
Private Function IsBuild(ByVal scope As EnvDTE.vsBuildScope, ByVal action As EnvDTE.vsBuildAction) As Boolean
    Return scope = vsBuildScope.vsBuildScopeSolution
End Function
Private Sub BuildEvents_OnBuildBegin(ByVal Scope As EnvDTE.vsBuildScope, ByVal Action As EnvDTE.vsBuildAction) Handles BuildEvents.OnBuildBegin
    If (IsBuild(Scope, Action)) Then
        buildStart = Date.Now
    End If
End Sub
Private Sub BuildEvents_OnBuildDone(ByVal Scope As EnvDTE.vsBuildScope, ByVal Action As EnvDTE.vsBuildAction) Handles BuildEvents.OnBuildDone
    If (IsBuild(Scope, Action)) Then
        Dim buildTime = Date.Now - buildStart
        WriteToBuildWindow(String.Format("Build time: {0}", buildTime.ToString))
    End If
End Sub
Private Sub WriteToBuildWindow(ByVal message As String)
    Dim win As Window = DTE.Windows.Item(EnvDTE.Constants.vsWindowKindOutput)
    Dim ow As OutputWindow = CType(win.Object, OutputWindow)
    For Each owPane As OutputWindowPane In ow.OutputWindowPanes
        If (owPane.Name.Equals("Build")) Then
            owPane.OutputString(message)
            Exit For
        End If
    Next
End Sub
回答by Ryan Lundy
Show the start page after you close a solution (but keep Visual Studio open)
关闭解决方案后显示起始页(但保持 Visual Studio 打开)
Put this code in your EnvironmentEvents module:
将此代码放在您的 EnvironmentEvents 模块中:
Private Sub SolutionEvents_AfterClosing() Handles SolutionEvents.AfterClosing
    DTE.ExecuteCommand("View.StartPage")
End Sub
Hide the start page after you open a solution
打开解决方案后隐藏起始页
Put this code in your EnvironmentEvents module:
将此代码放在您的 EnvironmentEvents 模块中:
Private Sub SolutionEvents_Opened() Handles SolutionEvents.Opened
    Dim startPageGuid As String = "{387CB18D-6153-4156-9257-9AC3F9207BBE}"
    Dim startPage As EnvDTE.Window = DTE.Windows.Item(startPageGuid)
    If startPage IsNot Nothing Then startPage.Close()
End Sub
These two together will cause your Start Page to hide itself when you open a solution.  When you close the solution, the Start Page comes back.
当您打开解决方案时,这两个一起将导致您的起始页隐藏自身。当您关闭解决方案时,起始页会返回。
回答by Sam Harwell
I use the following lesser-known shortcuts very often:
我经常使用以下鲜为人知的快捷方式:
- Ctrl+Enter: Insert a blank line above the current line (and place the cursor there)
- Ctrl+Shift+Enter: Insert a blank line below the current line (and place the cursor there)
- Ctrl+Shift+V: Cycles the clipboard ring
- Ctrl+Enter:在当前行上方插入一个空行(并将光标放在那里)
- Ctrl+Shift+Enter:在当前行下方插入一个空行(并将光标放在那里)
- Ctrl+Shift+V:循环剪贴板环
回答by Ryan Lundy
Outlining: Collapse to definitions but expand regions
大纲:折叠到定义但扩展区域
Are you working in one of those shops that insists on regions around everything, so that when you collapse to definitions, you can't see any code?
您是否在那些坚持围绕所有区域设置区域的商店之一工作,以便当您折叠到定义时,您看不到任何代码?
What you really need is a collapse-to-definitions-but-expand-regions macro, like this one:
您真正需要的是一个折叠到定义但扩展区域的宏,如下所示:
Sub CollapseToDefinitionsButExpandAllRegions()
    DTE.ExecuteCommand("Edit.CollapsetoDefinitions")
    DTE.SuppressUI = True
    Dim objSelection As TextSelection = DTE.ActiveDocument.Selection
    objSelection.StartOfDocument()
    Do While objSelection.FindText("#region", 
        vsFindOptions.vsFindOptionsMatchInHiddenText)
    Loop
    objSelection.StartOfDocument()
    DTE.SuppressUI = False
End Sub
Put this in a regular macro module, assign it to a hot key, and your code is back.
把它放在一个普通的宏模块中,将它分配给一个热键,你的代码就回来了。
(Except...if you work with some really nefarious individuals who put regions insidemethods, this will unfortunately expand those methods. If anybody knows a way to write this to avoid that, feel free to edit.)
(除了……如果您与一些将区域放入方法中的真正邪恶的人一起工作,不幸的是,这将扩展这些方法。如果有人知道如何编写它以避免这种情况,请随时进行编辑。)
回答by si618
Insert GUID, great for WiX work, add to menu as button or as key shortcut.
插入 GUID,非常适合 WiX 工作,作为按钮或快捷键添加到菜单中。
Sub InsertGuid()
    Dim objTextSelection As TextSelection
    objTextSelection = CType(DTE.ActiveDocument.Selection(), EnvDTE.TextSelection)
    objTextSelection.Text = System.Guid.NewGuid.ToString.ToUpper(New System.Globalization.CultureInfo("en", False))
End Sub
Organise usings for all .cs files in a solution - Original Author:djpark.
组织解决方案中所有 .cs 文件的使用 -原作者:djpark。
Sub OrganizeSolution()
    Dim sol As Solution = DTE.Solution
    For i As Integer = 1 To sol.Projects.Count
        OrganizeProject(sol.Projects.Item(i))
    Next
End Sub
Private Sub OrganizeProject(ByVal proj As Project)
    For i As Integer = 1 To proj.ProjectItems.Count
        OrganizeProjectItem(proj.ProjectItems.Item(i))
    Next
End Sub
Private Sub OrganizeProjectItem(ByVal projectItem As ProjectItem)
    Dim fileIsOpen As Boolean = False
    If projectItem.Kind = Constants.vsProjectItemKindPhysicalFile Then
        'If this is a c# file             
        If projectItem.Name.LastIndexOf(".cs") = projectItem.Name.Length - 3 Then
            'Set flag to true if file is already open                 
            fileIsOpen = projectItem.IsOpen
            Dim window As Window = projectItem.Open(Constants.vsViewKindCode)
            window.Activate()
            projectItem.Document.DTE.ExecuteCommand("Edit.RemoveAndSort")
            'Only close the file if it was not already open                 
            If Not fileIsOpen Then
                window.Close(vsSaveChanges.vsSaveChangesYes)
            End If
        End If
    End If
    'Be sure to apply RemoveAndSort on all of the ProjectItems.         
    If Not projectItem.ProjectItems Is Nothing Then
        For i As Integer = 1 To projectItem.ProjectItems.Count
            OrganizeProjectItem(projectItem.ProjectItems.Item(i))
        Next
    End If
    'Apply RemoveAndSort on a SubProject if it exists.         
    If Not projectItem.SubProject Is Nothing Then
        OrganizeProject(projectItem.SubProject)
    End If
End Sub
回答by Olivier Payen
Collapse all nodesof the Solution panel, very useful especially for big projects:
折叠解决方案面板的所有节点,特别是对于大项目非常有用:
    Public Module CollapseAllNodes
    Sub RunCollapseAllNodes()
        Dim UIHSolutionExplorer As UIHierarchy
        UIHSolutionExplorer = DTE.Windows.Item(Constants.vsext_wk_SProjectWindow).Object()
        ' Check if there is any open solution 
        If (UIHSolutionExplorer.UIHierarchyItems.Count = 0) Then
            Return
        End If
        ' Get the top node (the name of the solution) 
        Dim UIHSolutionRootNode As UIHierarchyItem
        UIHSolutionRootNode = UIHSolutionExplorer.UIHierarchyItems.Item(1)
        CloseRecursif(UIHSolutionRootNode)
        ' Select the solution node, or else when you click 
        ' on the solution windows scrollbar, it will synchronize the open document 
        ' with the tree and pop out the corresponding node which is probably not 
        ' what you want. 
        UIHSolutionRootNode.Select(vsUISelectionType.vsUISelectionTypeSelect)
    End Sub
    Function CloseRecursif(ByRef element)
        For Each UIHChild In element.UIHierarchyItems()
            CloseRecursif(UIHChild)
            If (UIHChild.UIHierarchyItems.Expanded = True) Then
                UIHChild.UIHierarchyItems.Expanded = False
            End If
        Next
    End Function
End Module
回答by Glenn Lang
I use Jeff's FormatToHtmlmacros if I'm going to be pasting a code example into a blog post or an email.
如果我要将代码示例粘贴到博客文章或电子邮件中,我会使用 Jeff 的FormatToHtml宏。
回答by womp
I work with dual monitors, and I find Sharon's layout-switching macro (from a 1 monitor to a 2 monitor layout) totally invaluable. When you need to be referencing a web page or other program while typing a bit of code, Ctrl-Alt-1 to switch to a one monitor layout for your Visual Studio windows. Once you're done, Ctrl-Alt-2 to switch to your two monitor layout and get all your windows back. Awesome!
我使用双显示器工作,我发现 Sharon 的布局切换宏(从 1 显示器到 2 显示器布局)完全无价。当您需要在键入一些代码时引用网页或其他程序时,请按 Ctrl-Alt-1 切换到 Visual Studio 窗口的单监视器布局。完成后,Ctrl-Alt-2 切换到您的两个显示器布局并恢复所有窗口。惊人的!
http://www.invisible-city.com/sharon/2008/06/workstation-hack-visual-studio-on-2.html
http://www.invisible-city.com/sharon/2008/06/workstation-hack-visual-studio-on-2.html
回答by Benjol
Not a macro on its own, but useful:
本身不是宏,但很有用:
Public Sub WriteToOutputWindow(ByVal pane as String, ByVal Msg As String)
    Dim owPane As OutputWindowPane
    Dim win As Window = DTE.Windows.Item(EnvDTE.Constants.vsWindowKindOutput)
    Dim ow As OutputWindow = win.Object
    Try
        owPane = ow.OutputWindowPanes.Item(pane)
    Catch
        owPane = ow.OutputWindowPanes.Add(pane)
    End Try
    If Not owPane Is Nothing Then
        owPane.Activate()
        owPane.OutputString(Msg & vbCrLf)
    End If
End Sub

