VS 2010 IDE 宏学习总结
生活随笔
收集整理的這篇文章主要介紹了
VS 2010 IDE 宏学习总结
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
自動添加注釋—VS2010宏的使用
? ? 在敲代碼的過程中類和函數都需要進行注釋,但總是一遍一遍的復制粘貼覺得很是麻煩,終于找到
了一個不錯的解決方法:使用宏。
不論是Office還是Foxmail以及我們所使用的VS甚至輸入法都具有宏的功能。VS2010中的宏,不僅可以錄
制模塊、還可以錄制類和代碼文件。通過設置編輯宏,然后為設置好的宏添加特定的快捷鍵,就可以在
VS2010代碼編輯器中任何位置非常方便的添加設定的注釋塊。實現過程如下:
? ??
? ? 1、打開“工具”→“宏”→“宏IDE”,進入以下界面,右擊“MyMacros”,添加模塊
? ? 命名模塊:
?
? ? 2、添加代碼并保存
? ? 雙擊所添加的模塊,進入編輯狀態,添加如下代碼:
[vb] view plain copy
Imports System ?
Imports EnvDTE ?
Imports EnvDTE80 ?
Imports EnvDTE90 ?
Imports EnvDTE90a ?
Imports EnvDTE100 ?
Imports System.Diagnostics ?
??
Public Module MyNote ?
??
? ? Sub DocumentFileHeader() ?
??
? ? ? ? Dim DocSel As EnvDTE.TextSelection ?
? ? ? ? DocSel = DTE.ActiveDocument.Selection ?
? ? ? ? DocSel.NewLine() ?
? ? ? ? DocSel.Text = "'************************************************" ?
? ? ? ? DocSel.NewLine() ?
? ? ? ? DocSel.Text = "'◇作者:吳利昌" ?
? ? ? ? DocSel.NewLine() ?
? ? ? ? DocSel.Text = "'◇小組:無" ?
? ? ? ? DocSel.NewLine() ?
? ? ? ? DocSel.Text = "'◇說明:" ?
? ? ? ? DocSel.NewLine() ?
? ? ? ? DocSel.Text = "'◇版本號:V1.0" ?
? ? ? ? DocSel.NewLine() ?
? ? ? ? DocSel.Text = "'◇創建日期:" + System.DateTime.Now.ToLongDateString ?
? ? ? ? DocSel.NewLine() ?
? ? ? ? DocSel.Text = "'*************************************************" ?
??
? ? End Sub ?
??
End Module ?
? ? 3、設置快捷鍵
? ? 打開“工具”→“選項”,選擇“鍵盤”,進行如下設置?
? ??
? ? 4、效果
[vb] view plain copy
'************************************************ ?
'◇作者:吳利昌 ?
'◇小組:無 ?
'◇說明: ?
'◇版本號:V1.0 ?
'◇創建日期:2013年6月25日 星期二 ?
'************************************************* ?
========
為VS2010編寫IDE宏
網上有不少好書,可惜其中有很多是掃描版的,摘抄加注起來很麻煩。為方便自己,也為造福大眾,我
會將自己喜愛的整理一遍,轉換成文本版。
網上有現成的工具,可以將圖片版的pdf轉換成文本,保存到ms word中。如果源圖片足夠清晰的話,文
本的識別率還是很高的。
不過對于代碼,其格式則往往比較混亂。手工在word中進行修正,麻煩不說,還容易出錯。想起曾經有
過幾次在VS2010中整理代碼,進行的操作基本上都是查找替換和格式化等等;并且,從vs中拷貝的代碼
,在word中還可以保留語法高亮(關鍵字藍色,字符串暗紅色,注釋綠色)。(不足的是,從VS2010中
拷貝的中文,在word中顯示為亂碼;而從VS2008中拷貝,則完全正常,并且語法高亮也仍然有效)
查找替換和格式化都是些重復性的勞動,因此想著法子讓電腦去做。
一開始打算使用dos批處理,但這樣一來如果仍要使用語法高亮,就要手工拷貝到VS2010,在拷貝到word
,多了一個步驟,麻煩。于是就想能不能直接在VS2010中完成。沒想到還真行。通過網絡和MSDN,知道
VS提供了一個叫做IDE宏的東西。
IDE宏原理上和VBA差不多,或者說就是應用于VS的VBA,只不過使用的VB變成.Net版的了(我不懂VB,如
果說錯了勿怪)。
下面說說編寫IDE宏的具體步驟(VS2010):
按ALT+F11或者點擊菜單:工具-》宏-》宏IDE,出現一個和VS類似的IDE窗口:
在MyMacros上右鍵添加模塊,模塊名稱隨便起(我的如上圖所示,叫TieWen,是本人的網名)。
雙擊模塊名稱,打開編輯窗口,默認的內容如下:
Imports System Imports EnvDTE Imports EnvDTE80 Imports EnvDTE90 Imports EnvDTE90a Imports EnvDTE100 Imports System.Diagnostics Public Module aaa End Module
我們所要作的,就是在Module TieWen和End Module之間寫入合適的Sub(過程,無返回值)(能否寫成
Function(有返回值)本人并未深入研究)。
我最近正在整理的書籍中源碼是基于Java的,因此給Sub取名為Macro_FormatJava,完整的代碼如下(有
點問題,多多包涵):
[vb] view plain copy 在CODE上查看代碼片派生到我的代碼片
Imports System ?
Imports System.Collections.Generic ?
Imports EnvDTE ?
Imports EnvDTE80 ?
Imports EnvDTE90 ?
Imports EnvDTE90a ?
Imports EnvDTE100 ?
Imports System.Diagnostics ?
??
Public Module TieWen ?
??
? ? Sub MergeAll(ByRef Content As String, ByVal From As String, ByVal sTo As String) ?
? ? ? ? While (Content.Contains(From)) ?
? ? ? ? ? ? Content = Content.Replace(From, sTo) ?
? ? ? ? End While ?
? ? End Sub ?
??
? ? Sub PrefixLf(ByRef Content As String, ByVal Who As String) ?
? ? ? ? Content = Content.Replace(Who, vbLf + Who) ?
? ? End Sub ?
??
? ? Sub PostfixLf(ByRef Content As String, ByVal Who As String) ?
? ? ? ? Content = Content.Replace(Who, Who + vbLf) ?
? ? End Sub ?
??
? ? Sub DTEReplaceAll(ByVal Target As EnvDTE.vsFindTarget, ByVal From As String, ByVal sTo?
As String, Optional ByVal UseRegEx As Boolean = False, Optional ByVal bLoop As Boolean =?
True) ?
??
? ? ? ? DTE.Find.FindWhat = From ?
? ? ? ? DTE.Find.ReplaceWith = sTo ?
? ? ? ? DTE.Find.Target = Target ?
? ? ? ? DTE.Find.MatchCase = True ?
? ? ? ? DTE.Find.MatchWholeWord = False ?
? ? ? ? DTE.Find.MatchInHiddenText = False ?
? ? ? ? If (UseRegEx) Then ?
? ? ? ? ? ? DTE.Find.PatternSyntax = vsFindPatternSyntax.vsFindPatternSyntaxRegExpr ?
? ? ? ? Else ?
? ? ? ? ? ? DTE.Find.PatternSyntax = vsFindPatternSyntax.vsFindPatternSyntaxLiteral ?
? ? ? ? End If ?
? ? ? ? DTE.Find.ResultsLocation = vsFindResultsLocation.vsFindResultsNone ?
? ? ? ? DTE.Find.Action = vsFindAction.vsFindActionReplaceAll ?
? ? ? ? While ((DTE.Find.Execute() <> vsFindResult.vsFindResultNotFound) And bLoop) ?
??
? ? ? ? End While ?
??
? ? End Sub ?
? ? ' 以上幾個是輔助Sub,而不是宏 ?
??
??
? ? Sub Macro_FormatJava() ?
? ? ? ? DTE.ActiveDocument.Selection.SelectAll() ?
? ? ? ? Dim Content As String ?
? ? ? ? Content = DTE.ActiveDocument.Selection.Text ?
??
??
? ? ? ? '處理開始 ?
? ? ? ? Dim operators_NeedPrefixAndPostfixSpace(),?
operators_IfIsAssignmentNeedPrefixAndPostfixSpace(), operators_NeedPrefixSpace(),?
operators_NeedPostfixSpace(), operators_NeedNoSpace(),?
operators_IfMatchedThenNeedPrefixAndPostfixSpace() ?
? ? ? ? '此處無法使用VB的Array函數 ?
? ? ? ? operators_NeedPrefixAndPostfixSpace = "public,class,interface,implements,return,:,
+,-,*,/,%,&,|,^,<<,>>,=,==,!=,<,<=,>,>=,&&,||".Split(",") ?
? ? ? ? operators_IfIsAssignmentNeedPrefixAndPostfixSpace = "+,-,*,/,%,&,|,^,<<,>>".Split
(",") ?
? ? ? ? operators_NeedPrefixSpace = "{,!,~".Split(",") ?
? ? ? ? operators_NeedPostfixSpace = ",|;".Split("|") ?
? ? ? ? operators_NeedNoSpace = "},->,::,.".Split(",") '不考慮case標簽或其它符號后緊跟::的
情形 ?
? ? ? ? operators_IfMatchedThenNeedPrefixAndPostfixSpace = "new,delete".Split(",") ?
? ? ? ? '尚未處理的符號:++、--(前后綴形式的區分比較麻煩)、()、[]、?: ?
? ? ? ? '一元操作符+、-、*、&被當作二元操作符處理了; ?
? ? ? ? For Each i In operators_NeedPrefixAndPostfixSpace ?
? ? ? ? ? ? Content = Content.Replace(i, " " + i + " ") ?
? ? ? ? Next ?
??
? ? ? ? For Each i In operators_NeedPrefixSpace ?
? ? ? ? ? ? Content = Content.Replace(i, " " + i) ?
? ? ? ? Next ?
??
? ? ? ? For Each i In operators_NeedPostfixSpace ?
? ? ? ? ? ? Content = Content.Replace(i, i + " ") ?
? ? ? ? Next ?
??
? ? ? ? Content = Content.Replace(vbTab, " ") ?
? ? ? ? '去除多余的空格 ?
? ? ? ? MergeAll(Content, " ?", " ") ?
??
? ? ? ? '合并被分開的//、/*、*/、**,必須在去除多余的空格之后調用 ?
? ? ? ? MergeAll(Content, "/ /", "//") ?
? ? ? ? MergeAll(Content, "/ *", "/*") ?
? ? ? ? MergeAll(Content, "* /", "*/") ?
? ? ? ? MergeAll(Content, "* *", "**") ?
??
? ? ? ? '必須在去除多余的空格之后調用 ?
? ? ? ? For Each i In operators_IfIsAssignmentNeedPrefixAndPostfixSpace ?
? ? ? ? ? ? Content = Content.Replace(i + " =", i + "=") ?
? ? ? ? Next ?
??
? ? ? ? '必須在去除多余的空格之后調用 ?
? ? ? ? For Each i In operators_NeedPrefixSpace ?
? ? ? ? ? ? Content = Content.Replace(i + " ", i) ?
? ? ? ? Next ?
? ? ? ? For Each i In operators_NeedPostfixSpace ?
? ? ? ? ? ? Content = Content.Replace(" " + i, i) ?
? ? ? ? Next ?
??
? ? ? ? '必須在去除多余的空格之后調用 ?
? ? ? ? For Each i In operators_NeedNoSpace ?
? ? ? ? ? ? Content = Content.Replace(" " + i, i) ?
? ? ? ? ? ? Content = Content.Replace(i + " ", i) ?
? ? ? ? Next ?
??
? ? ? ? 'operators_IfMatchedThenNeedPrefixAndPostfixSpace無需處理 ?
??
? ? ? ? Dim operators_NeedPrefixLf(), operators_NeedPostfixLf() ?
? ? ? ? '此處無法使用VB的Array函數 ?
? ? ? ? operators_NeedPrefixLf = "},if(,if( ,for(, for (,return".Split(",") ?
? ? ? ? operators_NeedPostfixLf = "{".Split(",") ?
??
? ? ? ? For Each i In operators_NeedPrefixLf ?
? ? ? ? ? ? PrefixLf(Content, i) ?
? ? ? ? Next ?
? ? ? ? For Each i In operators_NeedPostfixLf ?
? ? ? ? ? ? PostfixLf(Content, i) ?
? ? ? ? Next ?
??
? ? ? ? Content = Content.Replace(vbCrLf, vbLf) ?
? ? ? ? Content = Content.Replace(vbCr, vbLf) ?
? ? ? ? MergeAll(Content, " " + vbLf, vbLf) ?
? ? ? ? MergeAll(Content, vbLf + vbLf, vbLf) ?
??
? ? ? ? '調用ALT+F8格式化代碼(在我的機器上會自動在行尾增加空格,因此上面的替換僅為處理{}使
用,具體的去除行尾空格,已使用查找替換實現) ?
? ? ? ? DTE.ActiveDocument.Selection.Text = Content ?
? ? ? ? DTE.ActiveDocument.Selection.SelectAll() ?
? ? ? ? DTE.ExecuteCommand("Edit.FormatSelection") ?
??
? ? ? ? DTE.ActiveDocument.Selection.SelectAll() ?
??
? ? ? ? '將Tab替換成四個空格 ?
? ? ? ? '由于DTE.ActiveDocument.Selection.Text = Content會自動進行格式化, ?
? ? ? ? '所以不能用代碼進行替換再賦值,否會會導致多余的空格。 ?
? ? ? ? '通過查找替換功能實現 ?
? ? ? ? DTEReplaceAll(vsFindTarget.vsFindTargetCurrentDocumentSelection, vbTab, " ? ?") ?
? ? ? ? '結束處理 ?
? ? End Sub ?
End Module ?
?
?Sub寫好之后,就是將之應用到VS。
點擊VS的菜單:工具-》選項,切換到環境-》鍵盤:
在顯示命令包含下的輸入框中輸入先前的模塊名或Sub的名稱,等上1-2秒鐘,會將過濾后的結果刷新在
輸入框下發的列表中:
選中對應的宏(剛剛我們所編寫的Sub),然后將光標放在“按快捷鍵P”下方的輸入框中,按一個快捷
鍵,如果該快捷鍵已經被其它命令占用,會在“快捷鍵的當前使用對象U”下方的下拉框中顯示出來:
此時按Backspace,刪除快捷鍵,重新選擇一個(注意,一定要按Backspace刪除,不要直接繼續按),
直到該快捷鍵未被占用(我選到的時候ALT+T),然后點擊“分配”按鈕,點擊確定關閉選項窗口。
然后,打開一個源碼文檔,按下快捷鍵(我的是ALT+T)試試效果吧。
如果覺得不好,就修改Sub,直到自己滿意為止。
?
補充:
如果發現有些IDE已經實現的功能而自己不會寫,可以使用VS的宏記錄功能:
按Ctrl+Shift+R或者點擊菜單項“工具-〉宏-〉記錄TemporaryMacro”,然后執行VS動作(比如執行查
找替換),完畢后停止宏記錄,然后打開宏編輯器,打開RecordingModule,代碼全在這里頭。
========
VS2010編寫自定義宏
這里所說的宏可不是指#define PI 3.14159之類的,而是按下Alt + 1,Alt + 2之類的鍵盤組合之后可以
方便地插入一大串自定義的內容,如:
/*******************************************************************?
* 函數名稱:?
* 功 ? ?能:?
* 參 ? ?數:?
* 返 回 值:void?
* 創 建 人:Ajioy?
* 博 ? ?客:blog.csdn.net/ajioy?
* 電子郵箱:ajioy1206@gmail.com?
* 日 ? ?期:2013.1.8 21:18?
*******************************************************************/ ?
這在團隊開發中顯得尤為重要,當然,在網絡上發布源代碼時也起到一個簡單地版權聲明作用,而不需
要人為地花時間編寫及排版,減少了許多繁瑣而不必要的工作。
簡單地了解一下,這里談的宏(Macro)是開發工具VS2010(或VS的其它版本)自帶的,一種方便開發人
員進行注釋、版權聲明或者執行其他若干瑣碎工作的“小機器人”。重復、不辭勞苦地為我們做一些不
可缺少的小事。總之,有它的存在,生活更美好。
怎樣自己寫一個宏?
1.打開VS2010(或VS的其它版本),“Tools” --> ?"Macros"--->"Macros IDE...(Alt + F11)" 打開
宏IDE
2.在宏IDE的工具欄中"Project"->"Add Module"(或Add New Item)->Name:AjioyMacros--->"Add"
3.將初始內容替換成以下代碼
Imports System ?
Imports EnvDTE ?
Imports EnvDTE80 ?
Imports EnvDTE90 ?
Imports EnvDTE90a ?
Imports EnvDTE100 ?
Imports System.Diagnostics ?
Imports System.Text ?
Imports System.Text.RegularExpressions ?
Imports System.IO ?
Imports System.Collections.Specialized ?
??
Public Module AjioyMacros'這里要與保存的Module名保持一致,不然無法調用宏 ?
? ? Sub AddMessageBox() ?
? ? ? ? 'DESCRIPTION 增加對話框 ?
? ? ? ? ActiveDocument.Selection.Text = "MessageBox("""",""提示"");" + vbNewLine + "system
(""pause"");" ?
? ? End Sub ?
? ? Sub AddStartComment() ?
? ? ? ? 'DESCRIPTION 注釋開始 ?
? ? ? ? ActiveDocument.Selection.Text = "system(""pause"");" ?
? ? End Sub ?
? ? Public Sub FileSign() ?
? ? ? ? 'DESCRIPTION 文件簽名 ?
? ? ? ? Dim Description As New StringBuilder ?
? ? ? ? Dim BlankLine As String ?
? ? ? ? BlankLine = "//" + vbNewLine ?
? ? ? ? With Description ?
? ? ? ? ? ? .AppendFormat("//Copyright (c) 2013 Ajioy All Rights Reserved{0}",vbNewLine) ?
? ? ? ? ? ? .AppendFormat
("/****************************************************************************************
*****{0}", vbNewLine) ?
? ? ? ? ? ? .AppendFormat("*文件名:{0}{1}{2}", vbTab, DTE.ActiveDocument.Name, vbNewLine) ?
? ? ? ? ? ? .AppendFormat("*說明:{0}{1}{2}", vbTab, "", vbNewLine) ?
? ? ? ? ? ? .AppendFormat("*創建日期:{0}{1}{2}", vbTab, Date.Today.ToString("yyyy-MM-dd"),?
vbNewLine) ?
? ? ? ? ? ? .AppendFormat("*作者:{0}{1}{2}", vbTab, "Ajioy", vbNewLine) ?
? ? ? ? ? ? .AppendFormat("*版本:{0}{1}{2}", vbTab, "1.0", vbNewLine) ?
? ? ? ? ? ? .AppendFormat
("*----------------------------------------------------------------------------------------
------{0}", vbNewLine) ?
? ? ? ? ? ? .AppendFormat("*修改記錄:{0}", vbNewLine) ?
? ? ? ? ? ? .AppendFormat("*日期{0}版本{1}修改人{2}修改內容{3}", New String(vbTab, 3),?
vbTab, vbTab, vbNewLine) ?
? ? ? ? ? ? .AppendFormat("*{0}{1}", Date.Today.ToString("yyyy-MM-dd"), vbNewLine) ?
? ? ? ? ? ? .AppendFormat
("*****************************************************************************************
***/{0}", vbNewLine) ?
? ? ? ? ? ? .Append(vbNewLine) ?
? ? ? ? End With ?
? ? ? ? '插入cs文件頭部 ?
? ? ? ? Dim objSel As TextSelection ?
? ? ? ? objSel = CType(DTE.ActiveDocument.Selection, TextSelection) ?
? ? ? ? DTE.UndoContext.Open("FileSign") ?
? ? ? ? objSel.StartOfDocument(False) ?
? ? ? ? objSel.Insert(Description.ToString()) ?
? ? ? ? DTE.UndoContext.Close() ?
? ? End Sub ?
? ? Sub FunctionSign() ?
? ? ? ? 'DESCRIPTION 文件簽名 ?
? ? ? ? Dim obj ?
? ? ? ? obj = Now() ?
? ? ? ? Dim DocSel As EnvDTE.TextSelection ?
? ? ? ? DocSel = DTE.ActiveDocument.Selection ?
? ? ? ? DocSel.NewLine() ?
? ? ? ? DocSel.Text =?
"/*******************************************************************" ?
? ? ? ? DocSel.NewLine() ?
? ? ? ? DocSel.Text = "* 函數名稱:" ?
? ? ? ? DocSel.NewLine() ?
? ? ? ? DocSel.Text = "* 功 ? ?能:" ?
? ? ? ? DocSel.NewLine() ?
? ? ? ? DocSel.Text = "* 參 ? ?數:" ?
? ? ? ? DocSel.NewLine() ?
? ? ? ? DocSel.Text = "* 返 回 值:" ?
? ? ? ? DocSel.NewLine() ?
? ? ? ? DocSel.Text = "* 創 建 人:Ajioy" ?
? ? ? ? DocSel.NewLine() ?
? ? ? ? DocSel.Text = "* 博 ? ?客:blog.csdn.net/ajioy" ?
? ? ? ? DocSel.NewLine() ?
? ? ? ? DocSel.Text = "* 電子郵箱:ajioy1206@gmail.com" ?
? ? ? ? DocSel.NewLine() ?
? ? ? ? DocSel.Text = "* 日 ? ?期:" + CStr(Year(obj)) + "." + CStr(Month(obj)) + "." +?
CStr(Day(obj)) + " " + CStr(Hour(obj)) + ":" + CStr(Minute(obj))?
'System.DateTime.Now.ToLongDateString() ?
? ? ? ? DocSel.NewLine() ?
? ? ? ? DocSel.Text =?
"*******************************************************************/" ?
? ? End Sub ?
? ? Sub AddModify() ?
? ? ? ? 'DESCRIPTION 增添修改 ?
? ? ? ? Dim obj ?
? ? ? ? obj = Now() ?
? ? ? ? ActiveDocument.Selection.Text = "//Ajioy" + CStr(Year(obj)) + "." + CStr(Month
(obj)) + "." + CStr(Day(obj)) ?+" " + CStr(Hour(obj)) + ":" + CStr(Minute(obj)) + " 修改" ?
? ? End Sub ?
? ? Sub AddStartSymbol() ?
? ? ? ? 'DESCRIPTION 開始注釋 ?
? ? ? ? ActiveDocument.Selection.Text = "/*" ?
? ? End Sub ?
? ? Sub AddEndSymbol() ?
? ? ? ? 'DESCRIPTION 結束注釋 ?
? ? ? ? ActiveDocument.Selection.Text = "*/" ?
? ? End Sub ?
End Module ?
保存后關閉宏IDE
4.回到VS2010主界面,"Tools"--->"Options"--->"Environment"--->"Keyboard"--->在Show commands?
containing:下的編輯框中輸入FunctionSign(所有帶括號的那些名稱,如AddStartSymbol()...),會
看到有"Macros.Macros(或Samples).AjioyMacros.FunctionSign"的項,選中它,在Press shortcut?
keys:下自定義快捷鍵,建議用Alt + ?數字0-9和-+鍵組合,以免與編譯環境快捷鍵發生沖突,之
后"Assign",最后確定。
接下來我們可以隨便驗證一下,打開一個.cpp文件,按下Alt + 數字,看看會發生什么。
========
讓vs2010自動完成雙引號
? ?廣大碼奴們,敲碼時遇到需要輸入雙引號,方括號,圓括號是不是很煩躁,
如果有一種只需要輸入一個左邊括號,就可以自動補齊另一邊括號,并且可以自
動將光標定位到括號中間,輸入完畢后又可以方便的跳出括號的工具,那效率會
不會高很多。
? ? 百度了很久,都沒有什么好的解決方案,不是裝VA就是resharper插件,
但是也只是可以自動補齊和定位而已,想要跳出仍然需要利用鍵盤上的右方向
鍵,手部移動幅度很大有木有,完全打亂了敲碼的節奏,破壞了憂郁的氣質,好
吧,我之前一直都用鼠標來的。。。
?找不到現成的方法,只能自己動手豐衣足食了。突然發現 virtual studio是支持宏操作的,于是樓主
靈光一閃,想到了利用宏來自動實現上述功能的方法,不多說,直接上圖。
?1.工具-宏-記錄TemporaryMacro
?
2. 接下來就不用我多說了,和office中的一樣,錄制宏,比如你可以在文本編輯窗口輸入“ ( ”,“?
) ”,“ <— ”(方向鍵),然后停止錄制宏。這樣我們就有了可以自動完成雙引號并定位到中間位
置的快捷操作,依次可以得到自動完成圓括號,方括號等等的宏。這是我自己錄制的7個宏。
?
3. 接下來我們還要把這些宏和具體的快捷鍵綁定起來,這樣我們只要在鍵盤上敲打快捷鍵就可以自動完
成
??
在“顯示命令包含”中輸入“宏”,會自動顯示你剛剛錄制的所有宏,選擇一個,設置快捷鍵,注意設
置完要點“分配”
?
?
這樣一個宏就設置完了,接下來把你錄制的所有宏都設置一個你認為方便你操作的快捷鍵即可。
4.接下來和大家分享一下我的設計方案。我選取了H,J,K,L,N,M,Alt,空格這8個元素,她們在鍵盤上的位
置都在右手可以控制的范圍內,非常靈活便捷,不想錄制的朋友也可以直接粘貼我設置好的宏代碼。
Alt+H : 刪除,即backspace Sub 刪除()DTE.ActiveDocument.Selection.DeleteLeft() End SubAlt+J:輸入雙引號并定位到中間Sub 打出雙引號()DTE.ActiveDocument.Selection.Text = """"""DTE.ActiveDocument.Selection.CharLeft()End SubAlt+K:輸入圓括號并定位到中間Sub 打出括號()DTE.ActiveDocument.Selection.Text = "()"DTE.ActiveDocument.Selection.CharLeft()End SubAlt+L:輸入方括號并定位到中間 Sub 打出方括號()DTE.ActiveDocument.Selection.Text = "[]"DTE.ActiveDocument.Selection.CharLeft() End SubAlt+N:撤銷Sub 撤銷()DTE.ExecuteCommand("Edit.Undo")End SubAlt+M:反撤銷Sub 反撤銷()DTE.ExecuteCommand("Edit.Redo")End SubAlt+空格:自動跳出括號 Sub 跳出()DTE.ActiveDocument.Selection.CharRight() End Sub
Ps:
1.?
所有的vs編輯器都支持宏,所以這個方法可以用在vs各個版本上,你也可以依此在office上操作
2.事實上由于升級的微軟補丁沖突,很多vs的宏功能已經被破壞,是無法運行任何宏的。基本都是在安
裝KB2898869、KB2901126、KB2898857等更新后宏停止運行。查看了一下提供的解決方案,修改宏配置文
件,VS2010的配置文件路徑為:C:\Program Files (x86)\Common Files\microsoft shared\VSA
\9.0\VsaEnv目錄下的vsmsvr10.exe.config,在RunTime配置節添加配置項:
<AllowDComReflection enabled="1"/>即可
?
32bit和64bit的windows,以及vs不同版本的路徑和配置文件如下
?
在之前7個宏的基礎上再新加8個宏,一共15個,基本涵蓋了所有常用的操作。
alt+e:光標向上
alt+d:光標向下
alt+s:光標向左
alt+f:激活文件窗口,有時由于鼠標操作或別的問題代碼頁面會失去焦點,這個快捷鍵可以讓光標重新
出現在代碼文件上
alt+i:復制代碼段,指定行號,當前光標位置和指定行之間代碼全部選定
alt+g:指定行號,光標自動跳到改行
alt+r:將選定代碼段注釋
alt+t:將注釋代碼段解開
15個快捷鍵全部由alt帶動, s,e,d,f,r,t,g,h,j,k,l,n,m,i,空格 ? ? 充分考慮手指的擺動幅度,幾乎
可以保證最大限度的連續操作。
并不想將vs真的改造成vim,簡單,甚好。
另外vs的宏模塊全部可以導出,快捷鍵的綁定配置文件也可以導出,這樣,把這兩個文件上傳到你的微
云或百度云盤,就可以保證你的隨時隨地使用了。
??
15Macros.vb( 宏模塊文件,可導入)
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
Option Strict Off
Option Explicit Off
Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports EnvDTE90a
Imports EnvDTE100
Imports System.Diagnostics
Public Module RecordingModule
? ? Sub 打出括號()
? ? ? ? DTE.ActiveDocument.Selection.Text = "()"
? ? ? ? DTE.ActiveDocument.Selection.CharLeft()
? ? End Sub
?Sub 向右()
? ? ? ? DTE.ActiveDocument.Selection.CharRight()
?End Sub
? ? Sub 打出方括號()
? ? ? ? DTE.ActiveDocument.Selection.Text = "[]"
? ? ? ? DTE.ActiveDocument.Selection.CharLeft()
? ? End Sub
? ? Sub 打出雙引號()
? ? ? ? DTE.ActiveDocument.Selection.Text = """"""
? ? ? ? DTE.ActiveDocument.Selection.CharLeft()
? ? End Sub
? ? Sub 刪除()
? ? ? ? DTE.ActiveDocument.Selection.DeleteLeft()
? ? End Sub
? ? Sub 撤銷()
? ? ? ? DTE.ExecuteCommand("Edit.Undo")
? ? End Sub
? ? Sub 反撤銷()
? ? ? ? DTE.ExecuteCommand("Edit.Redo")
? ? End Sub
? ? Sub 向左()
? ? ? ? DTE.ActiveDocument.Selection.CharLeft()
? ? End Sub
? ? Sub 向上()
? ? ? ? DTE.ActiveDocument.Selection.LineUp()
? ? End Sub
? ? Sub 向下()
? ? ? ? DTE.ActiveDocument.Selection.LineDown()
? ? End Sub
? ? Sub 激活()
? ? ? ? ActiveDocument.Activate()
? ? End Sub
? ? Sub 轉行()
? ? ? ? Dim command As Integer
? ? ? ? command = InputBox("Enter a number: ")
? ? ? ? DTE.ActiveDocument.Selection.GotoLine(command)
? ? End Sub
? ? Sub 復制()
? ? ? ? Dim textSelection As EnvDTE.TextSelection
? ? ? ? Dim textSelectionPointSaved As TextPoint
? ? ? ? Dim command As Integer
? ? ? ? textSelection = DTE.ActiveWindow.Selection
? ? ? ? textSelectionPointSaved = textSelection.ActivePoint.CreateEditPoint()
? ? ? ? command = InputBox("Enter a number: ")
? ? ? ? selection = ActiveDocument.Selection
? ? ? ? d = selection.TopPoint.Line
? ? ? ? If ((d - command) > 0) Then
? ? ? ? ? ? For arrIdx = 1 To (d - command)
? ? ? ? ? ? ? ? selection.LineUp(True)
? ? ? ? ? ? Next
? ? ? ? ? ? textSelection.StartOfLine()
? ? ? ? ElseIf ((d - command) < 0) Then
? ? ? ? ? ? For arrIdx = 1 To (command - d)
? ? ? ? ? ? ? ? selection.LineDown(True)
? ? ? ? ? ? Next
? ? ? ? ? ? textSelection.EndOfLine()
? ? ? ? Else
? ? ? ? ? ? textSelection.StartOfLine()
? ? ? ? ? ? textSelectionPointSaved = textSelection.ActivePoint.CreateEditPoint()
? ? ? ? ? ? textSelection.EndOfLine()
? ? ? ? End If
? ? ? ? textSelection.MoveToPoint(textSelectionPointSaved, True)
? ? End Sub
?
? ? Sub 注釋()
? ? ? ? DTE.ExecuteCommand("Edit.CommentSelection")
? ? End Sub
? ? Sub 解開注釋()
? ? ? ? DTE.ExecuteCommand("Edit.UncommentSelection")
? ? End Sub
End Module
========
VS2010編寫自定義宏,定義解決方案項目折疊、展開快捷鍵
怎樣自己寫一個宏?
1.打開VS2010(或VS的其它版本),“Tools” --> ?"Macros"--->"Macros IDE...(Alt + F11)" 打開
宏IDE
2.在宏IDE的工具欄中"MyMacros"->"Add Module"->CollapseExpandAllProject
3. 將初始內容替換成以下代碼
Option Strict Off
Option Explicit Off
Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports System.Diagnostics
Public Module CollapseExpandAllProject ? ‘(特別注意:這里要與保存的Module名保持一致,不然
無法調用宏 )
? ? '-----------------------------------------------?
? ? 'Collapse All projects ?折疊
? ? 'Author:ZhangRongHua
? ? 'Date:2010-05-12
? ? '-----------------------------------------------
? ? Public Sub CollapseAllProject()
? ? ? ? lastSlashIndex = DTE.Solution.FullName.LastIndexOf("\") + 1 ?'Get the last slash?
index .
? ? ? ? solutionNameWithExtension = DTE.Solution.FullName.Substring(lastSlashIndex) ?' Get?
solution name with extension.?
? ? ? ? solutionName = solutionNameWithExtension.ToString().Substring(0,?
solutionNameWithExtension.ToString().Length - 4) ' Get the solution name without extension?
.
? ? ? ? count = 0
? ? ? ? For Each curProject As EnvDTE.Project In DTE.Solution.Projects
? ? ? ? ? ? Try
? ? ? ? ? ? ? ? DTE.ActiveWindow.Object.GetItem(solutionName + "\" +?
curProject.Name).UIHierarchyItems.Expanded = False
? ? ? ? ? ? ? ? count = count + 1
? ? ? ? ? ? Catch ex As ArgumentException
? ? ? ? ? ? ? ? Continue For
? ? ? ? ? ? End Try
? ? ? ? Next curProject
? ? End Sub
? ? '-----------------------------------------------?
? ? 'Expand All projects ?展開
? ? 'Author:ZhangRongHua
? ? 'Date:2010-05-12
? ? '-----------------------------------------------
? ? Public Sub ExpandAllProject()
? ? ? ? lastSlashIndex = DTE.Solution.FullName.LastIndexOf("\") + 1 ?'Get the last slash?
index .
? ? ? ? solutionNameWithExtension = DTE.Solution.FullName.Substring(lastSlashIndex) ?' Get?
solution name with extension.?
? ? ? ? solutionName = solutionNameWithExtension.ToString().Substring(0,?
solutionNameWithExtension.ToString().Length - 4) ' Get the solution name without extension?
.
? ? ? ? count = 0
? ? ? ? For Each curProject As EnvDTE.Project In DTE.Solution.Projects
? ? ? ? ? ? Try
? ? ? ? ? ? ? ? DTE.ActiveWindow.Object.GetItem(solutionName + "\" +?
curProject.Name).UIHierarchyItems.Expanded = True
? ? ? ? ? ? ? ? count = count + 1
? ? ? ? ? ? Catch ex As ArgumentException
? ? ? ? ? ? ? ? Continue For
? ? ? ? ? ? End Try
? ? ? ? Next curProject
? ? End Sub
End Module
保存后關閉宏IDE
4、回到VS2010主界面(注意是在VS2010主界面,不是打開了某一個解決方案的主界面),"Tools"---
>"Options"--->"Environment"--->"Keyboard"--->在Show commands containing:下的編輯框中輸入
macro(所有含macro的那些名稱),會看到
有"MyMacros.CollapseExpandAllProject.CollapseAllProject"的項,選中它,在Press shortcut?
keys:下自定義快捷鍵,建議用Alt + ?數字0-9和-+鍵組合,以免與編譯環境快捷鍵發生沖突,之
后"Assign",最后確定。
5、接下來我們可以驗證一下,打開一個解決方案,按下Alt + 數字,會執行對應操作。
注意,按下快捷鍵時,鼠標要定位到解決方案資源管理器上面,不然會報錯
參見:
http://www.cnblogs.com/zhangronghua/archive/2010/05/12/Colloapse_Expand_Macro.html
========
VS2010自定義宏注釋模板
通過宏IDE進行宏編輯從而達到在編碼時實現自動添加注釋的作用。
操作有兩個步驟:
1、編輯宏注釋
2、為宏添加快捷鍵方便操作。
下面詳說以上兩步:
1、VS2010->工具->宏(Macros)->宏IDE。
接著就是在宏編輯的IDE環境中,添加新項->新建名稱->宏編輯(參照模板)->保存->返回VS2010。
2、VS2010->工具->選項(Options)->環境下的鍵盤->在顯示命令包含:的方框中輸入第一步新建的宏注
釋的名字->選擇該宏注釋->定義快捷鍵(按個人喜歡,不要有沖突)->快捷鍵用于全局->分配->確定。
以上就已經做好了你的宏注釋模板了,在以后的個人編程和團隊工作時就可以采用這樣的方式進行統一
化注釋規則。
宏注釋模板:
Sub AddFunComment()
? ? ? ? Dim DocSel As EnvDTE.TextSelection
? ? ? ? DocSel = DTE.ActiveDocument.Selection
? ? ? ? DocSel.NewLine()
? ? ? ? DocSel.Text = ""
? ? End Sub
以上學習于http://blog.chinaunix.net/uid-21375345-id-3085290.html。
========
使用宏來完成一些煩瑣的代碼
在 Visual Studio 2012 之前的版本,當有些效果我們經常會使用但又無法單純的用一個快捷命令
來實現時,就可以通過宏來創建自己的快捷命令。但是 Microsoft 再考慮到自定義宏的維護成本過高而
且只支持VB,因此拋棄了對它的支持。
下面的演示只限于 Visual Studio 2012 之前的版本。
通過錄制宏來實現一個最簡單的功能
1. 打開 工具 / 宏 / 錄制宏
2. 在代碼編輯器中輸入
Console.WriteLine("Hi");
?
3. 點擊停止錄制宏
打開 工具 / 宏 / 宏資源管理器,找到 RecordingModule 并展開,雙擊 TemporaryMacro。這個時
候會發現編輯器光標所在的位置已經自動插入了一條 “Console.WriteLine("Hi")” 代碼。
動畫演示:如何創建一個最簡單的宏
本節只演示宏的基本功能,更多關于宏的高級用法,請見《Visual Studio 宏的高級用法》。
?
注:2014年2月之后,Windows的一次更新將導致 Visual Studio 無法運行 macro,按照該文章的方
法修改三個配置文件即可以修復。
?
========
Visual Studio 宏的高級用法
因為自 Visual Studio 2012 開始,微軟已經取消了對宏的支持,所以本篇文章所述內容只適用于?
Visual Studio 2010 或更早期版本的 VS。
在上一篇中,我已經介紹了如何編寫一個最簡單的宏,本文將進一步介紹如何用宏來實現對代碼編
輯窗口控制。在本文結束的時候,你應該能自己實現如下兩個功能,第一個用于對方法體進行 phase0?
標記;第二個可以將當前窗口中的代碼進行歸類,將所有方法、屬性、變量通過region進行分塊。
動畫演示:phase0?
動畫演示:設置 region
為什么使用宏
在計算機行業內,宏的出現由來已久,因為它能替代人們執行一些重復發生的簡單但煩瑣的事情,
所以廣受人們歡迎。在 Visual Studio 中也提供了進行宏編程的方法,從而方便開發人員錄制一些宏腳
本來擴展Visual Studio,以提高開發效率。
要想在 Visual Studio 中操作宏來操控代碼編輯窗口,就必須要了解如下幾個東東:EnvDTE、DTE
、TextSelection、EditPoint。宏可實現地遠不止是操控代碼編輯窗口,關于其它能力請見參考資源[1]
。
本文中的內容在閱讀過程中最好能結合實踐進行練習,這樣印象會更深刻。?
EnvDTE
EnvDTE 是最核心的程序集,所有后續要講到的東西都歸于它名下。
MSDN上對它的介紹:
EnvDTE 是包含 Visual Studio 內核自動化的對象和成員的用程序集包裝的 COM 庫。 在 EnvDTE80、
EnvDTE90、 EnvDTE90a 和 EnvDTE100 命名空間中包含更改和新功能。
EnvDTE80、90、100按照數字,越大的表示越新,因為Visual Stuido有好多版本,不同的版本會提
供新的功能,而這幾個版本的 EnvDTE 正是對應了這些更新,不同的版本只是在功能上做了補充,并沒
有誰能替代誰的關系,比如editPoint2 比 editPoint 可能多了某些新特性,當你要使用這些新特性的
時候,就應該使用editPoint2,否則還是使用 editPoint。
在編寫自己的擴展前,可以把EnvDTE、EnvDTE80 等全部引用進來。
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports EnvDTE90a
Imports EnvDTE100
?
DTE對象
在 Visual Studio 中, DTE 對象是自動化模型中的頂級對象,通過操作DTE對象可以獲取對?
Visual Studio 的控制,比如你可以得到當前活動的文檔、活動的窗口、活動的項目、查找與替換、向
解決方案中添加文件、執行預定義命令、錄制宏等。
DTE包含的屬性(局部)
上面只是截取了一部分,完整的請查看 MSDN?
DTE包含的方法
通過操控這些屬性和方法就可以實現強大的功能,下面的例子中通過操縱DTE對象的TextSelecion子
對象和Find子對象來調用 Visual Studio 的查找功能。
Dim selection As TextSelection = DTE.ActiveDocument.SelectionDTE.Find.MatchWholeWord = FalseDTE.Find.Action = vsFindAction.vsFindActionFindDTE.Find.Target = vsFindTarget.vsFindTargetCurrentDocumentDTE.Find.MatchCase = FalseDTE.Find.Backwards = FalseDTE.Find.MatchInHiddenText = TrueDTE.Find.PatternSyntax = vsFindPatternSyntax.vsFindPatternSyntaxLiteral'跳出輸入框,接收你的輸入what = InputBox(prompt)If (what <> "") ThenDTE.Find.FindWhat = what'相當于在當前文檔向下搜索一次Dim result = DTE.Find.Execute()If (result = vsFindResult.vsFindResultFound) Then’如果找到,就把那一行選中selection.SelectLine()End IfEnd If
? 上面的代碼并不復雜,就是簡單地對 Find 的調用和賦值。如果你正好看到這里,不仿也試著寫一
下吧~ Find 相關內容請查看參考資源[2]。
TextSelection
用于代表當前選定的區域,一個文檔有且只有一個實例,即使你在代碼中創建了多個實例,這些實
例其實都是指向同一個選定區域。對 TextSelection 的操控會直接體現在界面上。通過控制該對象可以
剪切、復制、刪除選中的文本,插入刪除空白行,大小寫轉換,定位到某個位置、格式化等。
TextSelection 的屬性
TextSelection 的方法(局部)
完整的請查看 MSDN?
?
一句話獲取 TextSelection 實例,因為 TextSelection 是針對文檔的,所以在獲取 Selection 之
前,必須先獲取文檔。如果當前文檔中并沒有選中任何文本,則 TextSelection 表示的是當前光標所在
的位置。
Dim selection As TextSelection = DTE.ActiveDocument.Selection
?
下面演示幾個例子,來說明 TextSelection 的能力。?
第一個例子將演示如何獲取當前光標所在的方法的名稱,主要通過獲取當前光標所在位置的?
CodeElement 元素來得到具體的方法信息,通過傳入 CodeElement 的參數不一致可以獲取不同塊的信息
,包括方法、枚舉、屬性、類、名稱空間等。關于 vsCMElement 的枚舉請見參考資源[4]。
復制代碼
1 Sub DemoFunctionInfo()
2 ? ? ? ? Dim selection As TextSelection = DTE.ActiveDocument.Selection
3 ? ? ? ? Dim func As CodeFunction = selection.ActivePoint.CodeElement
(vsCMElement.vsCMElementFunction)
4 ? ? ? ? If Not func Is Nothing Then
5 ? ? ? ? ? ? MsgBox(func.Name)
6 ? ? ? ? End If
7 End Sub
復制代碼
?
動畫演示:顯示方法名
第二個示例,演示如何在光標位置所在的行上下加上Region。
復制代碼
?1 ? ? Sub DemoRegion()
?2 ?
?3 ? ? ? ? '獲取 TextSelection 實例
?4 ? ? ? ? Dim selection As TextSelection = DTE.ActiveDocument.Selection
?5 ?
?6 ? ? ? ? '移動到當前光標所在行的最前面
?7 ? ? ? ? selection.StartOfLine()
?8 ? ? ? ? '在該位置插入一個新行,相當于按了下回車
?9 ? ? ? ? selection.NewLine()
10 ? ? ? ? '將光標移回到新行
11 ? ? ? ? selection.LineUp()
12 ? ? ? ? '在當前光標所在的位置開始輸入文字
13 ? ? ? ? selection.Text = "#region start"
14 ?
15 ? ? ? ? '將光標移動到下一行
16 ? ? ? ? selection.LineDown()
17 ? ? ? ? '將光標移動到行末
18 ? ? ? ? selection.EndOfLine()
19 ? ? ? ? '回車
20 ? ? ? ? selection.NewLine()
21 ? ? ? ? selection.Text = "#endregion"
22 ?
23 ? ? ? ? '格式化
24 ? ? ? ? selection.SmartFormat()
25 ?
26 ? ? End Sub
復制代碼
動畫演示:在特定行的上下添加region
再來看一個示例,用戶輸入起始和結束文字,然后自動選中位于這兩個起始結束標記之間的一段文
本。
復制代碼
?1 ? ? Sub DemoSelectTextRange()
?2 ? ? ? ? ?
?3 ? ? ? ? '獲取 TextSelection
?4 ? ? ? ? Dim selection As TextSelection = DTE.ActiveDocument.Selection
?5 ? ? ? ? Dim startLine As Integer
?6 ? ? ? ? Dim startLineOffset As Integer
?7 ? ? ? ? Dim startPoint As TextPoint
?8 ? ? ? ? Dim endLine As Integer
?9 ? ? ? ? Dim endLineOffset As Integer
10 ?
11 ? ? ? ? DTE.Find.Action = vsFindAction.vsFindActionFind
12 ? ? ? ? DTE.Find.MatchCase = False
13 ?
14 ? ? ? ? '-------------- 找到起始的文字 ----------------------
15 ? ? ? ? Dim input = InputBox("Enter a word to find as the start tag")
16 ? ? ? ? If input = "" Then
17 ? ? ? ? ? ? Exit Sub
18 ? ? ? ? End If
19 ?
20 ? ? ? ? DTE.Find.FindWhat = input
21 ? ? ? ? Dim result As vsFindResult = DTE.Find.Execute()
22 ? ? ? ? If result <> vsFindResult.vsFindResultFound Then
23 ? ? ? ? ? ? Exit Sub
24 ? ? ? ? End If
25 ?
26 ? ? ? ? startLineOffset = selection.BottomPoint.LineCharOffset
27 ? ? ? ? startLine = selection.BottomPoint.Line
28 ? ? ? ? '-----------------------------------------------------
29 ?
30 ? ? ? ? '--------------- 找到結束的文字 ----------------------
31 ? ? ? ? input = InputBox("Enter a word to find as the end tag")
32 ? ? ? ? If input = "" Then
33 ? ? ? ? ? ? Exit Sub
34 ? ? ? ? End If
35 ?
36 ? ? ? ? DTE.Find.FindWhat = input
37 ? ? ? ? result = DTE.Find.Execute()
38 ? ? ? ? If result <> vsFindResult.vsFindResultFound Then
39 ? ? ? ? ? ? Exit Sub
40 ? ? ? ? End If
41 ?
42 ? ? ? ? endLine = selection.TopPoint.Line
43 ? ? ? ? endLineOffset = selection.TopPoint.LineCharOffset
44 ? ? ? ? '-----------------------------------------------------
45 ?
46 ? ? ? ? '------------- 遍歷,記錄經過的字符數用于選中 --------
47 ? ? ? ? Dim index As Integer
48 ? ? ? ? Dim len As Integer = 0
49 ?
50 ? ? ? ? selection.GotoLine(startLine)
51 ? ? ? ? len += selection.ActivePoint.LineLength - startLineOffset
52 ? ? ? ? For index = startLine + 1 To endLine - 1
53 ? ? ? ? ? ? selection.GotoLine(index)
54 ? ? ? ? ? ? len += selection.ActivePoint.LineLength
55 ? ? ? ? Next
56 ? ? ? ? selection.GotoLine(endLine)
57 ? ? ? ? len += endLineOffset
58 ? ? ? ? '-----------------------------------------------------
59 ?
60 ? ? ? ? '設置起始位置
61 ? ? ? ? selection.MoveToLineAndOffset(startLine, startLineOffset)
62 ? ? ? ? 'True 表示鼠標跟隨移動,len 表示要移動的字符數
63 ? ? ? ? selection.CharRight(True, len)
64 ?
65 ? ? End Sub
復制代碼
?
動畫演示:選中一段文本
EditPoint
Visual Studio 除了在代碼編輯窗口中會保留代碼,還有一個叫代碼緩沖區的地方(用戶是看不到
的)也會保留代碼,但這個緩沖區中的代碼不受自動換行和虛擬空格的影響。前面我們說過?
TextSelection 只能有一個,那如果開發人員事先選中了一行代碼,而我們又在宏中不小心改變了這個?
TextSelection,那就會導致用戶的選中被丟失。另外,EditPoint提供了一些TextSelection所不具備的
操作能力。比如剪切一段文本,使用 EditPoint 的 Cut 方法只要設置起始位置然后直接傳入結束的位
置給 Cut 方法就可以完成,但是如果使用 TextSelection ,因為它的 Cut 不帶參數,所以就必須先選
中這段文本才能使用 Cut 方法。
這里補充一個小知識點,什么是虛擬空格?這個東東默認是關閉的,在 Visual Studio 開發的時候
也很少用。一般我們在寫代碼的時候,如果在一行的結尾處使用小鍵盤向右繼續移動的話,光標很快就
會自動跳轉到下一行。如果開啟之后,則永遠不會自動跳轉到下一行,你可以在任意一個位置進行編輯
。開啟的方式:工具 / 選項 / 文本編輯器 / 所有語言 -> 啟用虛擬空格。
所以如果你在項目中會存在自動換行或開啟了虛擬空格,那么想要精準的控制編輯器,還是使用?
EditPoint 吧。
下面一樣舉個例子來講解。該示例將把一個方法的位置進行移動,思路就是先剪切,然后粘貼。
復制代碼
?1 ? ?Sub DemoCut()
?2 ? ? ? ? Dim selection As TextSelection = DTE.ActiveDocument.Selection
?3 ? ? ? ? '獲取editPointer
?4 ? ? ? ? Dim edit = selection.ActivePoint.CreateEditPoint
?5 ? ? ? ? '獲取 方法
?6 ? ? ? ? Dim func As CodeFunction = selection.ActivePoint.CodeElement
(vsCMElement.vsCMElementFunction)
?7 ? ? ? ? If Not func Is Nothing Then
?8 ? ? ? ? ? ? edit.MoveToPoint(func.StartPoint)
?9 ? ? ? ? ? ? edit.Cut(func.EndPoint)
10 ?
11 ? ? ? ? ? ? edit.MoveToLineAndOffset(20, 1)
12 ? ? ? ? ? ? edit.Paste()
13 ? ? ? ? End If
14 ? ? End Sub
復制代碼
?
動畫演示:如何剪貼一個方法
Have a try
辛苦了,看到這里實在不容易。既然已經看到這了,何不來嘗試著自己寫一個呢?回到開頭的兩個
示例,看看能不能寫出來了。答案請兇猛的點擊這里。
?
參考資源
[1] 自動化與擴展性參考
[2] Find 接口
[3] 如何:控制代碼編輯器 (Visual Basic)
[4] vsCMElement 枚舉
?
本文來源于 《Visual Studio 宏的高級用法》
========
使用Visual Studio 2005 IDE的宏,自動為c#變量生成屬性
在編寫c#代碼過程中,我們經常需要做一些重復枯燥的工作。例如,編寫DTO(數據訪問對象),通常就
是為一個類定義一系列的變量和屬性。
有一些第三方的IDE輔助工具,可以為我們生成一些代碼,減少工作量。例如,Assist X就是一款很值得
推薦的工具,使用其提供的Encapsulate Field功能,可以很方便地將一個類地編寫封裝為屬性。
我今天需要介紹的如何使用Visual Studio 2005 IDE中自帶的宏實現類似的功能。
打開Visual Studio 2005 IDE,選擇“工具” > "宏" > “宏 IDE”,選擇“添加模塊”。例如,我是
在MyMacros項目中新增了一個EditorHelper模塊,代碼如下:
Imports System
Imports EnvDTE
Imports EnvDTE80
Imports System.Diagnostics
Public Module EditorHelper
? ? '為一個參數封裝一般屬性訪問器
? ? Public Sub EncapsulateField()
? ? ? ? Dim projectItem As ProjectItem = DTE.ActiveDocument.ProjectItem
? ? ? ? Dim fileCodeModel As FileCodeModel = projectItem.FileCodeModel
? ? ? ? '得到當前選定的內容
? ? ? ? Dim selectText As TextSelection = DTE.ActiveDocument.Selection
? ? ? ? '獲取到當前光標的位置
? ? ? ? Dim point As TextPoint = selectText.ActivePoint
? ? ? ? Try
? ? ? ? ? ? Dim codeElement As CodeElement = fileCodeModel.CodeElementFromPoint(point,?
vsCMElement.vsCMElementVariable)
? ? ? ? ? ? If (codeElement Is Nothing) Then
? ? ? ? ? ? ? ? Return
? ? ? ? ? ? End If
? ? ? ? ? ? Debug.Assert(codeElement.Kind = vsCMElement.vsCMElementVariable)
? ? ? ? ? ? Dim codeVar As CodeVariable = CType(codeElement, CodeVariable)
? ? ? ? ? ? Dim fieldName As String = codeVar.Name
? ? ? ? ? ? Dim codeClass As CodeClass = CType(codeVar.Parent, CodeClass)
? ? ? ? ? ? AddPropertyToClass(codeClass, fieldName, codeVar.Type)
? ? ? ? Catch ex As Exception
? ? ? ? ? ? '吃掉異常,不做處理或者提示
? ? ? ? End Try
? ? End Sub
? ? Public Sub EncapsulateAllFields()
? ? ? ? Dim projectItem As ProjectItem = DTE.ActiveDocument.ProjectItem
? ? ? ? Dim fileCodeModel As FileCodeModel = projectItem.FileCodeModel
? ? ? ? Try
? ? ? ? ? ? '得到當前選定的內容
? ? ? ? ? ? Dim selectText As TextSelection = DTE.ActiveDocument.Selection
? ? ? ? ? ? '獲取到當前光標的位置
? ? ? ? ? ? Dim point As TextPoint = selectText.ActivePoint
? ? ? ? ? ? Dim codeElement As CodeElement = fileCodeModel.CodeElementFromPoint(point,?
vsCMElement.vsCMElementClass)
? ? ? ? ? ? Dim codeClass As CodeClass = CType(codeElement, CodeClass)
? ? ? ? ? ? Dim i As Integer
? ? ? ? ? ? For i = 1 To codeClass.Members.Count
? ? ? ? ? ? ? ? '如果屬性已經定義,會拋出異常
? ? ? ? ? ? ? ? '在這里處理異常,即使新增的屬性已經定義,也可以繼續處理下面的代碼
? ? ? ? ? ? ? ? Try
? ? ? ? ? ? ? ? ? ? Dim element As CodeElement = codeClass.Members.Item(i)
? ? ? ? ? ? ? ? ? ? If (element.Kind = vsCMElement.vsCMElementVariable) Then
? ? ? ? ? ? ? ? ? ? ? ? Dim codeVariable As CodeVariable = CType(element, CodeVariable)
? ? ? ? ? ? ? ? ? ? ? ? If (Not codeVariable.IsShared) Then ? ? '靜態變量不需要增加屬性
? ? ? ? ? ? ? ? ? ? ? ? ? ? AddPropertyToClass(codeClass, codeVariable.Name,?
codeVariable.Type)
? ? ? ? ? ? ? ? ? ? ? ? End If
? ? ? ? ? ? ? ? ? ? End If
? ? ? ? ? ? ? ? Catch ex As Exception
? ? ? ? ? ? ? ? ? ? '吃掉異常
? ? ? ? ? ? ? ? End Try
? ? ? ? ? ? Next
? ? ? ? Catch ex As Exception
? ? ? ? ? ? '可能并沒有選擇有效的類定義,這時會拋出異常,忽略
? ? ? ? End Try
? ? End Sub
? ? '根據成員的名稱的類型,在類對象中插入屬性
? ? Private Sub AddPropertyToClass(ByVal codeClass As CodeClass, ByVal fieldName As String,?
ByVal fieldType As Object)
? ? ? ? '生成屬性的名稱,規則是首先字母大寫。如果變量的開頭為“_”,移除
? ? ? ? Dim propertyName As String = fieldName
? ? ? ? If (propertyName.StartsWith("_")) Then
? ? ? ? ? ? propertyName = propertyName.TrimStart("_"c)
? ? ? ? End If
? ? ? ? propertyName = propertyName.Substring(0, 1).ToUpper() & propertyName.Substring(1)
? ? ? ? '創建屬性對象
? ? ? ? '-1表示代碼插入到類的最下方
? ? ? ? 'vsCMAccess.vsCMAccessPublic表示為public
? ? ? ? Dim codeProperty As CodeProperty = codeClass.AddProperty(propertyName,?
propertyName, fieldType, -1, vsCMAccess.vsCMAccessPublic)
? ? ? ? 'Getter
? ? ? ? Dim getter As CodeFunction = codeProperty.Getter
? ? ? ? Dim getterPoint As TextPoint = getter.GetStartPoint(vsCMPart.vsCMPartBody)
? ? ? ? Dim getterEditPoint As EditPoint = getterPoint.CreateEditPoint()
? ? ? ? getterEditPoint.Delete(getter.GetEndPoint(vsCMPart.vsCMPartBody))
? ? ? ? getterEditPoint.Insert(vbCrLf) ? ? ?'插入回車符
? ? ? ? getterEditPoint.LineUp()
? ? ? ? getterEditPoint.Indent(, 4) ? ? ? ? '縮進4個位置
? ? ? ? getterEditPoint.Insert("return " & fieldName & ";")
? ? ? ? 'Setter
? ? ? ? Dim setter As CodeFunction = codeProperty.Setter
? ? ? ? Dim setterPoint As TextPoint = setter.GetStartPoint(vsCMPart.vsCMPartBody)
? ? ? ? Dim setterEditPoint As EditPoint = setterPoint.CreateEditPoint()
? ? ? ? setterEditPoint.Insert(vbCrLf) ? ? '插入回車符
? ? ? ? setterEditPoint.LineUp()
? ? ? ? setterEditPoint.Indent(, 4) ? ? ? ? '縮進4個位置
? ? ? ? setterEditPoint.Insert(fieldName & " = value;")
? ? End Sub
End Module
我定義了兩個Public方法:EncapsulateField和EncapsulateAllFields,分別用于為類的一個變量封裝
屬性,或者為類中所有的變量(非靜態)封裝屬性。
使用上面的宏的方法很簡單,選擇“工具”>“宏”>“宏資源管理器”就可以看到我們已經創建的宏方
法,如下圖所示:
假如你已經編寫了這樣一段代碼:
using System;
using System.Collections.Generic;
using System.Text;
namespace Demo
{
? ? public class Person
? ? {
? ? ? ? private int _id;
? ? ? ? private string _name;
? ? ? ? private DateTime _birthDay;
? ? }
}
將光標移到“_name”變量上,然后雙擊“EncapsulateField”宏,就運行了該宏。運行后,你可以得到
這樣的代碼:
using System;
using System.Collections.Generic;
using System.Text;
namespace Demo
{
? ? public class Person
? ? {
? ? ? ? private int _id;
? ? ? ? private string _name;
? ? ? ? private DateTime _birthDay;
? ? ? ? public string Name
? ? ? ? {
? ? ? ? ? ? get
? ? ? ? ? ? {
? ? ? ? ? ? ? ? return _name;
? ? ? ? ? ? }
? ? ? ? ? ? set
? ? ? ? ? ? {
? ? ? ? ? ? ? ? _name = value;
? ? ? ? ? ? }
? ? ? ? }
? ? }
}
可以看到“EncapsulateField”宏已經為private string _name;創建了相應的屬性。
EncapsulateAllFields宏只需要將光標放在Person類的代碼區域中,就可以正常執行。例如針對上面的
代碼,EncapsulateAllFields后可以為Person類中的每一個變量都生成相應的屬性。(注:上面的代碼
中Name屬性已經有定義,所有試圖再添加Name屬性時會拋出異常,在EncapsulateAllFields宏定義中,
已經將該異常吃掉,所以,可以正確地為所有變量生成屬性)。運行后的代碼如下:
using System;
using System.Collections.Generic;
using System.Text;
namespace Demo
{
? ? public class Person
? ? {
? ? ? ? private int _id;
? ? ? ? private string _name;
? ? ? ? private DateTime _birthDay;
? ? ? ? public string Name
? ? ? ? {
? ? ? ? ? ? get
? ? ? ? ? ? {
? ? ? ? ? ? ? ? return _name;
? ? ? ? ? ? }
? ? ? ? ? ? set
? ? ? ? ? ? {
? ? ? ? ? ? ? ? _name = value;
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? public int Id
? ? ? ? {
? ? ? ? ? ? get
? ? ? ? ? ? {
? ? ? ? ? ? ? ? return _id;
? ? ? ? ? ? }
? ? ? ? ? ? set
? ? ? ? ? ? {
? ? ? ? ? ? ? ? _id = value;
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? public System.DateTime BirthDay
? ? ? ? {
? ? ? ? ? ? get
? ? ? ? ? ? {
? ? ? ? ? ? ? ? return _birthDay;
? ? ? ? ? ? }
? ? ? ? ? ? set
? ? ? ? ? ? {
? ? ? ? ? ? ? ? _birthDay = value;
? ? ? ? ? ? }
? ? ? ? }
? ? }
}
在確認上面的宏可以正確運行的情況下,我們還可以為其定義快捷鍵,進一步提高我們的工作效率。
在Visual Studio 2005 IDE中選擇“工具” > “選項”
在“選項”對話框中選擇“環境”>“鍵盤”。
在【顯示命令包含】中輸入Encap...,可以幫你快速定位到相應的宏命令;
【新快捷鍵用于】選項中選擇“文本編輯器”;
激活【按快捷鍵】輸入框,選擇你所希望的快捷鍵,例如我這里為EncapsulateField定義的快捷鍵
為“Ctrl + `”,為EncapsulateAllFields定義的快捷鍵為“Ctrl + Shift + `”
點擊分配按鈕
你就可以在文本編輯器中盡情享用宏給你帶來的方便。
補充在Visual Studio 2003中使用的宏:
Visual Studio 2003 IDE與Visual Studio 2005 IDE在處理上稍微有些不一致的地方,需要做如下的調
整:
Imports System
Imports EnvDTE
Imports System.Diagnostics
Public Module EditorHelper
? ? '為一個參數封裝一般屬性訪問器
? ? Public Sub EncapsulateField()
? ? ? ? Dim projectItem As ProjectItem = DTE.ActiveDocument.ProjectItem
? ? ? ? Dim fileCodeModel As FileCodeModel = projectItem.FileCodeModel
? ? ? ? '得到當前選定的內容
? ? ? ? Dim selectText As TextSelection = DTE.ActiveDocument.Selection
? ? ? ? '獲取到當前光標的位置
? ? ? ? Dim point As TextPoint = selectText.ActivePoint
? ? ? ? Try
? ? ? ? ? ? Dim codeElement As CodeElement = fileCodeModel.CodeElementFromPoint(point,?
vsCMElement.vsCMElementVariable)
? ? ? ? ? ? If (codeElement Is Nothing) Then
? ? ? ? ? ? ? ? Return
? ? ? ? ? ? End If
? ? ? ? ? ? Debug.Assert(codeElement.Kind = vsCMElement.vsCMElementVariable)
? ? ? ? ? ? Dim codeVar As CodeVariable = CType(codeElement, CodeVariable)
? ? ? ? ? ? Dim fieldName As String = codeVar.Name
? ? ? ? ? ? Dim codeClass As CodeClass = CType(codeVar.Parent, CodeClass)
? ? ? ? ? ? AddPropertyToClass(codeClass, fieldName, codeVar.Type)
? ? ? ? Catch ex As Exception
? ? ? ? ? ? '吃掉異常,不做處理或者提示
? ? ? ? ? ? MsgBox(ex.Message)
? ? ? ? End Try
? ? End Sub
? ? Public Sub EncapsulateAllFields()
? ? ? ? Dim projectItem As ProjectItem = DTE.ActiveDocument.ProjectItem
? ? ? ? Dim fileCodeModel As FileCodeModel = projectItem.FileCodeModel
? ? ? ? Try
? ? ? ? ? ? '得到當前選定的內容
? ? ? ? ? ? Dim selectText As TextSelection = DTE.ActiveDocument.Selection
? ? ? ? ? ? '獲取到當前光標的位置
? ? ? ? ? ? Dim point As TextPoint = selectText.ActivePoint
? ? ? ? ? ? Dim codeElement As CodeElement = fileCodeModel.CodeElementFromPoint(point,?
vsCMElement.vsCMElementClass)
? ? ? ? ? ? Dim codeClass As CodeClass = CType(codeElement, CodeClass)
? ? ? ? ? ? Dim i As Integer
? ? ? ? ? ? For i = 1 To codeClass.Members.Count
? ? ? ? ? ? ? ? '如果屬性已經定義,會拋出異常
? ? ? ? ? ? ? ? '在這里處理異常,即使新增的屬性已經定義,也可以繼續處理下面的代碼
? ? ? ? ? ? ? ? Try
? ? ? ? ? ? ? ? ? ? Dim element As CodeElement = codeClass.Members.Item(i)
? ? ? ? ? ? ? ? ? ? If (element.Kind = vsCMElement.vsCMElementVariable) Then
? ? ? ? ? ? ? ? ? ? ? ? Dim codeVariable As CodeVariable = CType(element, CodeVariable)
? ? ? ? ? ? ? ? ? ? ? ? If (Not codeVariable.IsShared) Then ? ? '靜態變量不需要增加屬性
? ? ? ? ? ? ? ? ? ? ? ? ? ? AddPropertyToClass(codeClass, codeVariable.Name,?
codeVariable.Type)
? ? ? ? ? ? ? ? ? ? ? ? End If
? ? ? ? ? ? ? ? ? ? End If
? ? ? ? ? ? ? ? Catch ex As Exception
? ? ? ? ? ? ? ? ? ? '吃掉異常
? ? ? ? ? ? ? ? End Try
? ? ? ? ? ? Next
? ? ? ? Catch ex As Exception
? ? ? ? ? ? '可能并沒有選擇有效的類定義,這時會拋出異常,忽略
? ? ? ? ? ? MsgBox(ex.Message)
? ? ? ? End Try
? ? End Sub
? ? '根據成員的名稱的類型,在類對象中插入屬性
? ? Private Sub AddPropertyToClass(ByVal codeClass As CodeClass, ByVal fieldName As String,?
ByVal fieldType As Object)
? ? ? ? '生成屬性的名稱,規則是首先字母大寫。如果變量的開頭為“_”,移除
? ? ? ? Dim propertyName As String = fieldName
? ? ? ? If (propertyName.StartsWith("_")) Then
? ? ? ? ? ? propertyName = propertyName.TrimStart("_"c)
? ? ? ? End If
? ? ? ? propertyName = propertyName.Substring(0, 1).ToUpper() & propertyName.Substring(1)
? ? ? ? '創建屬性對象
? ? ? ? '-1表示代碼插入到類的最下方
? ? ? ? 'vsCMAccess.vsCMAccessPublic表示為public
? ? ? ? Dim codeProperty As CodeProperty = codeClass.AddProperty(propertyName,?
propertyName, fieldType, -1, vsCMAccess.vsCMAccessPublic)
? ? ? ? 'Getter
? ? ? ? Dim getter As CodeFunction = codeProperty.Getter
? ? ? ? Dim getterPoint As TextPoint = getter.GetStartPoint(vsCMPart.vsCMPartBody)
? ? ? ? Dim getterEditPoint As EditPoint = getterPoint.CreateEditPoint()
? ? ? ? getterEditPoint.Delete(getter.GetEndPoint(vsCMPart.vsCMPartBody))
? ? ? ? getterEditPoint.Insert("get{ return " & fieldName & "; }")
? ? ? ? 'Setter
? ? ? ? Dim setter As CodeFunction = codeProperty.Setter
? ? ? ? Dim setterPoint As TextPoint = setter.GetStartPoint(vsCMPart.vsCMPartBody)
? ? ? ? Dim setterEditPoint As EditPoint = setterPoint.CreateEditPoint()
? ? ? ? setterEditPoint.Delete(setter.GetEndPoint(vsCMPart.vsCMPartBody))
? ? ? ? setterEditPoint.Insert("set{ " & fieldName & " = value; }")
? ? End Sub
End Module
另外,在2003中使用EncapsulateAllFields的宏時,也需要注意一點:在使用時,光標的應該停留在類
定義的空白位置,否則使用Dim codeClass As CodeClass = CType(codeElement, CodeClass)方法不能
正確獲取到類對象(例如,如果光標在構造函數里,獲取到的是構造函數對象,這點與2005還是有所區
別的)。
========
使用宏(Macro)擴展Visual Studio IDE
雖然有很多工具可以開發.NET程序,但我相信大多數的開發人員都是用Visual Studio(簡稱VS)。VS是
微軟所提供的一款集成開發工具,其最新版本為VS 2008。
VS使用起來還不錯,不是嗎?而且它還可以被我們進行擴展,按照我們自己的需求。這的確是挺誘人的
,對吧?
認真說起來,擴展VS的IDE有很多方法,例如你可以通過創建一個所謂的"Visual Studio外接程序",這
個外接程序其實就是一個實現了IDTExtensibility2接口的程序集。
t4
關于外接程序的具體細節,不是我們這次討論的內容。你可以通過下面地址了解
http://msdn2.microsoft.com/zh-cn/library/ms165620(VS.80).aspx
?
外接程序的好處是可以比較集中地封裝大量復雜的擴展,同時也易于分發。但相對來說,所需要的能力
也較高。相對比而言,另外一個擴展方法——宏擴展——則比較適合輕量級的擴展。它的實現方式相對
較為容易。我們下面就以一個例子來說明如何創建宏,如何運行宏,實現某些有意思的事情。
我們今天要解決的問題是這樣的:
大家知道,每個解決方案或項目都有一個相對應的文件目錄。我們經常需要定位到這些目錄。以前的做
法是(以項目為例):
1)先選中該項目
2)在它屬性中,復制它的"項目文件夾"這個屬性值
3)打開"開始"=>"運行"命令,粘貼那個路徑,然后回車
這些操作沒有什么技術含量,地球人都知道怎么做。但經常這么做,顯然不符合和諧社會的要求。試想
,如果能在解決方案或者項目的快捷菜單中,就有一個命令,可以一次性做這樣的事情,那該多好啊
很多事情并不難,尤其是當我們以認真的態度正視它的時候。為了實現上述要求,我們只需要寫一個簡
單的宏。的確如此簡單!
1)通過ALT+F8 打開宏資源管理器
2)在宏資源管理器中,定位到MyMacros,右鍵中選擇"新建模塊",給新的模塊命名為
ProjectContextMenu或者其他你喜歡的名字。
3)雙擊剛才新建的模塊,把以下的代碼復制到接下來打開的一個設計器中,并保存。
Imports System
Imports EnvDTE
Imports EnvDTE80
Imports System.Diagnostics
Imports System.IO
'這個模塊主要是用來為項目添加一些特殊的上下文菜單操作
Public Module ProjectContextMenu
? ? '這個方法是定位到當前項目的目錄
? ? Public Sub NavigateToProjectPath()
? ? ? ? Dim proj As EnvDTE.Project
? ? ? ? proj = DTE.ActiveSolutionProjects(0) '定位到當前的項目
? ? ? ? Dim path As String
? ? ? ? path = System.IO.Path.GetDirectoryName(proj.FullName) '取得當前項目所在的目錄
? ? ? ? Dim process As New System.Diagnostics.Process
? ? ? ? process.Start("Explorer.exe", path) '打開資源管理器
? ? End Sub
? ? '這個方法是定位到解決方案的目錄
? ? Public Sub NavigateToSolutionPath()
? ? ? ? Dim sln As EnvDTE.Solution
? ? ? ? sln = DTE.Solution '取得當前解決方案
? ? ? ? Dim path As String
? ? ? ? path = System.IO.Path.GetDirectoryName(sln.FullName) '取得當前解決方案的目錄
? ? ? ? Dim process As New System.Diagnostics.Process
? ? ? ? process.Start("Explorer.exe", path) '打開資源管理器
? ? End Sub
End Module
這樣我們的宏就做好了,你可以直接執行那兩個方法。看,是不是很神奇呢。它打開了當前項目的文件
夾。
t3
當然,我們還差最后一步沒有完成。那就是把這兩個方法關聯到內置菜單里面去。
1)你需要通過以下路徑打開自定義工具欄的對話框。"視圖"=〉"工具欄"==〉"自定義"
2)在"自定義"對話框中,選中"上下文菜單",你會發現所有內置的快捷菜單都顯示在頂部了
t7
3)把兩個宏方法拖拽到相應的快捷菜單里面去
t6?
下面是配置好之后的效果:多出了兩個菜單,分別都指向了上面寫好的兩個方法。單擊這個菜單,就可
以很方便地定位到項目或者解決方案的根目錄,免去了復制,然后粘貼到運行窗口的勞動。
t1 t
?
附加資源:
Visual Studio自動化對象模型。如果確實有興趣的朋友可以認真看一下(要想寫出高質量的VS IDE擴展
程序或插件,必須對該模型有較深入的認識)
Vs自動化模型圖
如果你的機器上裝好了MSDN,那么也可以通過下面的導航,了解到更加詳細的信息
ms-help://MS.VSCC.v80/MS.MSDN.v80/MS.VisualStudio.v80.chs/dv_extcore/html/4173a963-7ac7-
4966-9bb7-e28a9d9f6792.htm
?
最后,你還可以下載VS Sdk進行更加深入的了解
http://download.microsoft.com/download/9/a/1/9a1b39c4-cf38-4e40-b0b8-
aac1b34fc70a/VsSDKFebruary2007.exe
分類: 其他,Microsoft .NET
========
Visual Studio 宏
https://msdn.microsoft.com/zh-cn/library/b4c73967(v=vs.100).aspxVisual Studio 2010 其他版本?
宏是組合到一起形成一個命令以自動完成某項任務的一系列命令和指令。 宏允許自動重復操作。?
Visual Studio 包括宏集成開發環境 (IDE),該開發環境專門用于創建、操作、編輯和運行宏。 宏 IDE?
與 Visual Studio IDE 相互獨立。
本節內容
如何:錄制宏
描述如何創建和錄制宏。
如何:運行宏
討論各種運行宏和傳遞參數的方法。
宏的錄制和運行問題
提供錄制和運行宏時的常見問題的解決方案。
如何:管理宏
描述如何編輯現有宏或手動創建新宏。
調試宏
討論在宏中出現錯誤時的解決方法。
如何:管理宏
描述宏資源管理器及其上下文菜單。
保存和導出宏文件
描述如何在宏 IDE 中保存和導出宏文件。
宏 IDE 與 Visual Studio IDE 之間的功能差異
描述 Visual Studio 宏和 Visual Studio 之間在擴展性模型、Document 對象、屬性、項操作、Find?
方法、項目以及工具選項方面的差異。
如何:在宏中引用 COM 和 .NET Framework 組件
描述如何使用 Tlbimp 實用工具使 Visual Studio 宏能夠引用 COM 組件。
如何:在宏中處理環境事件
討論 EnvironmentEvents 模板、OnMacrosRuntimeReset 事件和 OnStartupComplete 事件。
宏安全性和共享問題
討論與宏有關的主要安全問題:知識產權保護和病毒的預防與保護。
宏示例
列出并描述 Visual Studio 中所包括的宏示例。
相關章節
使用宏自動執行重復性操作
提供對如何使用宏以使過程或重復的擊鍵序列自動化的概述。
宏開發環境
描述宏 IDE 中的所有對話框。
Macros
提供有關 Macros 對象的詳細信息,該對象表示 Visual Studio 宏記錄器。
Visual Studio Macros Error Messages
列出與 Visual Studio 宏關聯的所有錯誤消息。
如何:使用外接程序控制宏
描述如何使用 Visual Studio 自動化模型的 Macros 對象來控制在 IDE 中記錄的宏,包括暫停和重新
激活記錄器、向所記錄的宏中寫入代碼以及確定記錄器當前是否正在運行。
========
讓Visual Studio 也支持JS代碼折疊
? ? ? Visual Studio的代碼折疊功能非常好用,#region #endregion 這個詞連搜狗的詞庫里面都出現了(不含'#'號),可見使用頻率很高,但是他不支持js的代碼折疊 : ( 最近Ext用得比較多,一寫就是上
百行JS代碼,非常不方便,想著自己寫個擴展或插件什么的,意外搜到了下面的文章,已經用宏來實現
了,本文可以理解為該文的簡單譯本,注意宏代碼部分我有所改動 : )
?
文章
? ? ? 1. ? ? ?Using #region Directive With JavaScript Files in Visual Studio
?
環境
? ? ? Microsoft Visual Studio 2008
?
正文
? ? ? 1. ? ? ?打開宏資源管理器:視圖 -> 其他窗口 -> 宏資源管理器
? ? ? 2. ? ? ?創建一個新模塊
3. 編輯宏: 選中模塊 -> 右鍵編輯
Option Strict Off Option Explicit OffImports System Imports EnvDTE Imports EnvDTE80 Imports System.Diagnostics Imports System.CollectionsPublic Module JsMacrosSub OutlineRegions()Dim selection As EnvDTE.TextSelection = DTE.ActiveDocument.SelectionConst REGION_START As String = "//#region"Const REGION_END As String = "//#endregion"selection.SelectAll()'農民伯伯 --- 自動為"//#endregion"結束的代碼添加最后一行,不然出錯If selection.Text.EndsWith(REGION_END) Thenselection.EndOfLine()selection.NewLine()selection.SelectAll()End IfDim text As String = selection.Textselection.StartOfDocument(True)Dim startIndex As IntegerDim endIndex As IntegerDim lastIndex As Integer = 0Dim startRegions As Stack = New Stack()DostartIndex = text.IndexOf(REGION_START, lastIndex)endIndex = text.IndexOf(REGION_END, lastIndex)If startIndex = -1 AndAlso endIndex = -1 ThenExit DoEnd IfIf startIndex <> -1 AndAlso startIndex < endIndex ThenstartRegions.Push(startIndex)lastIndex = startIndex + 1Else' Outline region selection.MoveToLineAndOffset(CalcLineNumber(text, CInt(startRegions.Pop())), 1)selection.MoveToLineAndOffset(CalcLineNumber(text, endIndex) + 1, 1, True)selection.OutlineSection()lastIndex = endIndex + 1End IfLoopselection.StartOfDocument()End SubPrivate Function CalcLineNumber(ByVal text As String, ByVal index As Integer)Dim lineNumber As Integer = 1Dim i As Integer = 0While i < indexIf text.Chars(i) = vbCr ThenlineNumber += 1i += 1End Ifi += 1End WhileReturn lineNumberEnd FunctionEnd Module
保存即可。這里可以省去新建宏的步驟,他會根據代碼自動給你生成一個宏的。
注意我加的代碼段,如果不加,并且你的JS最后一行為#endregion,宏將報錯,顯示“值不在
預期的范圍內”。?
?
4. 設置快捷鍵
4.1 工具 -> 選項 - > 環境 -> 鍵盤
4.2 在顯示命令包含下面的文本框中輸入宏名outli,不用輸全,下面能顯示你新建的宏
4.3 點一下 按快捷鍵 下面的文本框, 然后自定義快捷鍵組合,我定義的是Ctrl+M,Ctrl+J
,點分配(別忘了!),點確定。
?
5.效果
5.1 輸入代碼:
//aasdsadsad
//#region
//#endregion
5.2 快捷鍵Ctrl+M,Ctrl+J啟動宏,能看到系統的右下角顯示可愛的小方塊在轉動,js編輯
框顯示效果如下:
?
5.3 之后就可以用快捷鍵Ctrl+M,Ctrl+L來[展開/折疊]代碼了,注意關閉之后重新打開需要
再啟動一次宏,展開效果如下:
========
msdn相關鏈接
https://msdn.microsoft.com/zh-cn/library/aa291605(v=vs.71).aspx
debugger對象
https://msdn.microsoft.com/zh-cn/library/aa291105(v=vs.71).aspx
公共環境對象模型
https://msdn.microsoft.com/zh-cn/library/68shb4dw(VS.80).aspx
https://msdn.microsoft.com/zh-cn/library/aa301306(v=vs.71).aspx
https://msdn.microsoft.com/zh-cn/library/aa300755
總結
以上是生活随笔為你收集整理的VS 2010 IDE 宏学习总结的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: js断点和调试学习总结3
- 下一篇: XSS 代码总结