VS 2010 IDE 宏学习总结
生活随笔
收集整理的這篇文章主要介紹了
VS 2010 IDE 宏学习总结
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
自動(dòng)添加注釋—VS2010宏的使用
? ? 在敲代碼的過程中類和函數(shù)都需要進(jìn)行注釋,但總是一遍一遍的復(fù)制粘貼覺得很是麻煩,終于找到
了一個(gè)不錯(cuò)的解決方法:使用宏。
不論是Office還是Foxmail以及我們所使用的VS甚至輸入法都具有宏的功能。VS2010中的宏,不僅可以錄
制模塊、還可以錄制類和代碼文件。通過設(shè)置編輯宏,然后為設(shè)置好的宏添加特定的快捷鍵,就可以在
VS2010代碼編輯器中任何位置非常方便的添加設(shè)定的注釋塊。實(shí)現(xiàn)過程如下:
? ??
? ? 1、打開“工具”→“宏”→“宏IDE”,進(jìn)入以下界面,右擊“MyMacros”,添加模塊
? ? 命名模塊:
?
? ? 2、添加代碼并保存
? ? 雙擊所添加的模塊,進(jìn)入編輯狀態(tài),添加如下代碼:
[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 = "'◇版本號(hào):V1.0" ?
? ? ? ? DocSel.NewLine() ?
? ? ? ? DocSel.Text = "'◇創(chuàng)建日期:" + System.DateTime.Now.ToLongDateString ?
? ? ? ? DocSel.NewLine() ?
? ? ? ? DocSel.Text = "'*************************************************" ?
??
? ? End Sub ?
??
End Module ?
? ? 3、設(shè)置快捷鍵
? ? 打開“工具”→“選項(xiàng)”,選擇“鍵盤”,進(jìn)行如下設(shè)置?
? ??
? ? 4、效果
[vb] view plain copy
'************************************************ ?
'◇作者:吳利昌 ?
'◇小組:無 ?
'◇說明: ?
'◇版本號(hào):V1.0 ?
'◇創(chuàng)建日期:2013年6月25日 星期二 ?
'************************************************* ?
========
為VS2010編寫IDE宏
網(wǎng)上有不少好書,可惜其中有很多是掃描版的,摘抄加注起來很麻煩。為方便自己,也為造福大眾,我
會(huì)將自己喜愛的整理一遍,轉(zhuǎn)換成文本版。
網(wǎng)上有現(xiàn)成的工具,可以將圖片版的pdf轉(zhuǎn)換成文本,保存到ms word中。如果源圖片足夠清晰的話,文
本的識(shí)別率還是很高的。
不過對(duì)于代碼,其格式則往往比較混亂。手工在word中進(jìn)行修正,麻煩不說,還容易出錯(cuò)。想起曾經(jīng)有
過幾次在VS2010中整理代碼,進(jìn)行的操作基本上都是查找替換和格式化等等;并且,從vs中拷貝的代碼
,在word中還可以保留語法高亮(關(guān)鍵字藍(lán)色,字符串暗紅色,注釋綠色)。(不足的是,從VS2010中
拷貝的中文,在word中顯示為亂碼;而從VS2008中拷貝,則完全正常,并且語法高亮也仍然有效)
查找替換和格式化都是些重復(fù)性的勞動(dòng),因此想著法子讓電腦去做。
一開始打算使用dos批處理,但這樣一來如果仍要使用語法高亮,就要手工拷貝到VS2010,在拷貝到word
,多了一個(gè)步驟,麻煩。于是就想能不能直接在VS2010中完成。沒想到還真行。通過網(wǎng)絡(luò)和MSDN,知道
VS提供了一個(gè)叫做IDE宏的東西。
IDE宏原理上和VBA差不多,或者說就是應(yīng)用于VS的VBA,只不過使用的VB變成.Net版的了(我不懂VB,如
果說錯(cuò)了勿怪)。
下面說說編寫IDE宏的具體步驟(VS2010):
按ALT+F11或者點(diǎn)擊菜單:工具-》宏-》宏IDE,出現(xiàn)一個(gè)和VS類似的IDE窗口:
在MyMacros上右鍵添加模塊,模塊名稱隨便起(我的如上圖所示,叫TieWen,是本人的網(wǎng)名)。
雙擊模塊名稱,打開編輯窗口,默認(rèn)的內(nèi)容如下:
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,完整的代碼如下(有
點(diǎn)問題,多多包涵):
[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 ?
? ? ' 以上幾個(gè)是輔助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函數(shù) ?
? ? ? ? operators_NeedPrefixAndPostfixSpace = "public,class,interface,implements,return,:,
+,-,*,/,%,&,|,^,<<,>>,=,==,!=,<,<=,>,>=,&&,||".Split(",") ?
? ? ? ? operators_IfIsAssignmentNeedPrefixAndPostfixSpace = "+,-,*,/,%,&,|,^,<<,>>".Split
(",") ?
? ? ? ? operators_NeedPrefixSpace = "{,!,~".Split(",") ?
? ? ? ? operators_NeedPostfixSpace = ",|;".Split("|") ?
? ? ? ? operators_NeedNoSpace = "},->,::,.".Split(",") '不考慮case標(biāo)簽或其它符號(hào)后緊跟::的
情形 ?
? ? ? ? operators_IfMatchedThenNeedPrefixAndPostfixSpace = "new,delete".Split(",") ?
? ? ? ? '尚未處理的符號(hào):++、--(前后綴形式的區(qū)分比較麻煩)、()、[]、?: ?
? ? ? ? '一元操作符+、-、*、&被當(dāng)作二元操作符處理了; ?
? ? ? ? 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, " ?", " ") ?
??
? ? ? ? '合并被分開的//、/*、*/、**,必須在去除多余的空格之后調(diào)用 ?
? ? ? ? MergeAll(Content, "/ /", "//") ?
? ? ? ? MergeAll(Content, "/ *", "/*") ?
? ? ? ? MergeAll(Content, "* /", "*/") ?
? ? ? ? MergeAll(Content, "* *", "**") ?
??
? ? ? ? '必須在去除多余的空格之后調(diào)用 ?
? ? ? ? For Each i In operators_IfIsAssignmentNeedPrefixAndPostfixSpace ?
? ? ? ? ? ? Content = Content.Replace(i + " =", i + "=") ?
? ? ? ? Next ?
??
? ? ? ? '必須在去除多余的空格之后調(diào)用 ?
? ? ? ? For Each i In operators_NeedPrefixSpace ?
? ? ? ? ? ? Content = Content.Replace(i + " ", i) ?
? ? ? ? Next ?
? ? ? ? For Each i In operators_NeedPostfixSpace ?
? ? ? ? ? ? Content = Content.Replace(" " + i, i) ?
? ? ? ? Next ?
??
? ? ? ? '必須在去除多余的空格之后調(diào)用 ?
? ? ? ? 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函數(shù) ?
? ? ? ? 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) ?
??
? ? ? ? '調(diào)用ALT+F8格式化代碼(在我的機(jī)器上會(huì)自動(dòng)在行尾增加空格,因此上面的替換僅為處理{}使
用,具體的去除行尾空格,已使用查找替換實(shí)現(xiàn)) ?
? ? ? ? DTE.ActiveDocument.Selection.Text = Content ?
? ? ? ? DTE.ActiveDocument.Selection.SelectAll() ?
? ? ? ? DTE.ExecuteCommand("Edit.FormatSelection") ?
??
? ? ? ? DTE.ActiveDocument.Selection.SelectAll() ?
??
? ? ? ? '將Tab替換成四個(gè)空格 ?
? ? ? ? '由于DTE.ActiveDocument.Selection.Text = Content會(huì)自動(dòng)進(jìn)行格式化, ?
? ? ? ? '所以不能用代碼進(jìn)行替換再賦值,否會(huì)會(huì)導(dǎo)致多余的空格。 ?
? ? ? ? '通過查找替換功能實(shí)現(xiàn) ?
? ? ? ? DTEReplaceAll(vsFindTarget.vsFindTargetCurrentDocumentSelection, vbTab, " ? ?") ?
? ? ? ? '結(jié)束處理 ?
? ? End Sub ?
End Module ?
?
?Sub寫好之后,就是將之應(yīng)用到VS。
點(diǎn)擊VS的菜單:工具-》選項(xiàng),切換到環(huán)境-》鍵盤:
在顯示命令包含下的輸入框中輸入先前的模塊名或Sub的名稱,等上1-2秒鐘,會(huì)將過濾后的結(jié)果刷新在
輸入框下發(fā)的列表中:
選中對(duì)應(yīng)的宏(剛剛我們所編寫的Sub),然后將光標(biāo)放在“按快捷鍵P”下方的輸入框中,按一個(gè)快捷
鍵,如果該快捷鍵已經(jīng)被其它命令占用,會(huì)在“快捷鍵的當(dāng)前使用對(duì)象U”下方的下拉框中顯示出來:
此時(shí)按Backspace,刪除快捷鍵,重新選擇一個(gè)(注意,一定要按Backspace刪除,不要直接繼續(xù)按),
直到該快捷鍵未被占用(我選到的時(shí)候ALT+T),然后點(diǎn)擊“分配”按鈕,點(diǎn)擊確定關(guān)閉選項(xiàng)窗口。
然后,打開一個(gè)源碼文檔,按下快捷鍵(我的是ALT+T)試試效果吧。
如果覺得不好,就修改Sub,直到自己滿意為止。
?
補(bǔ)充:
如果發(fā)現(xiàn)有些IDE已經(jīng)實(shí)現(xiàn)的功能而自己不會(huì)寫,可以使用VS的宏記錄功能:
按Ctrl+Shift+R或者點(diǎn)擊菜單項(xiàng)“工具-〉宏-〉記錄TemporaryMacro”,然后執(zhí)行VS動(dòng)作(比如執(zhí)行查
找替換),完畢后停止宏記錄,然后打開宏編輯器,打開RecordingModule,代碼全在這里頭。
========
VS2010編寫自定義宏
這里所說的宏可不是指#define PI 3.14159之類的,而是按下Alt + 1,Alt + 2之類的鍵盤組合之后可以
方便地插入一大串自定義的內(nèi)容,如:
/*******************************************************************?
* 函數(shù)名稱:?
* 功 ? ?能:?
* 參 ? ?數(shù):?
* 返 回 值:void?
* 創(chuàng) 建 人:Ajioy?
* 博 ? ?客:blog.csdn.net/ajioy?
* 電子郵箱:ajioy1206@gmail.com?
* 日 ? ?期:2013.1.8 21:18?
*******************************************************************/ ?
這在團(tuán)隊(duì)開發(fā)中顯得尤為重要,當(dāng)然,在網(wǎng)絡(luò)上發(fā)布源代碼時(shí)也起到一個(gè)簡(jiǎn)單地版權(quán)聲明作用,而不需
要人為地花時(shí)間編寫及排版,減少了許多繁瑣而不必要的工作。
簡(jiǎn)單地了解一下,這里談的宏(Macro)是開發(fā)工具VS2010(或VS的其它版本)自帶的,一種方便開發(fā)人
員進(jìn)行注釋、版權(quán)聲明或者執(zhí)行其他若干瑣碎工作的“小機(jī)器人”。重復(fù)、不辭勞苦地為我們做一些不
可缺少的小事。總之,有它的存在,生活更美好。
怎樣自己寫一個(gè)宏?
1.打開VS2010(或VS的其它版本),“Tools” --> ?"Macros"--->"Macros IDE...(Alt + F11)" 打開
宏IDE
2.在宏IDE的工具欄中"Project"->"Add Module"(或Add New Item)->Name:AjioyMacros--->"Add"
3.將初始內(nèi)容替換成以下代碼
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名保持一致,不然無法調(diào)用宏 ?
? ? Sub AddMessageBox() ?
? ? ? ? 'DESCRIPTION 增加對(duì)話框 ?
? ? ? ? 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("*創(chuàng)建日期:{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}修改人{(lán)2}修改內(nèi)容{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 = "* 函數(shù)名稱:" ?
? ? ? ? DocSel.NewLine() ?
? ? ? ? DocSel.Text = "* 功 ? ?能:" ?
? ? ? ? DocSel.NewLine() ?
? ? ? ? DocSel.Text = "* 參 ? ?數(shù):" ?
? ? ? ? DocSel.NewLine() ?
? ? ? ? DocSel.Text = "* 返 回 值:" ?
? ? ? ? DocSel.NewLine() ?
? ? ? ? DocSel.Text = "* 創(chuàng) 建 人: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 結(jié)束注釋 ?
? ? ? ? ActiveDocument.Selection.Text = "*/" ?
? ? End Sub ?
End Module ?
保存后關(guān)閉宏IDE
4.回到VS2010主界面,"Tools"--->"Options"--->"Environment"--->"Keyboard"--->在Show commands?
containing:下的編輯框中輸入FunctionSign(所有帶括號(hào)的那些名稱,如AddStartSymbol()...),會(huì)
看到有"Macros.Macros(或Samples).AjioyMacros.FunctionSign"的項(xiàng),選中它,在Press shortcut?
keys:下自定義快捷鍵,建議用Alt + ?數(shù)字0-9和-+鍵組合,以免與編譯環(huán)境快捷鍵發(fā)生沖突,之
后"Assign",最后確定。
接下來我們可以隨便驗(yàn)證一下,打開一個(gè).cpp文件,按下Alt + 數(shù)字,看看會(huì)發(fā)生什么。
========
讓vs2010自動(dòng)完成雙引號(hào)
? ?廣大碼奴們,敲碼時(shí)遇到需要輸入雙引號(hào),方括號(hào),圓括號(hào)是不是很煩躁,
如果有一種只需要輸入一個(gè)左邊括號(hào),就可以自動(dòng)補(bǔ)齊另一邊括號(hào),并且可以自
動(dòng)將光標(biāo)定位到括號(hào)中間,輸入完畢后又可以方便的跳出括號(hào)的工具,那效率會(huì)
不會(huì)高很多。
? ? 百度了很久,都沒有什么好的解決方案,不是裝VA就是resharper插件,
但是也只是可以自動(dòng)補(bǔ)齊和定位而已,想要跳出仍然需要利用鍵盤上的右方向
鍵,手部移動(dòng)幅度很大有木有,完全打亂了敲碼的節(jié)奏,破壞了憂郁的氣質(zhì),好
吧,我之前一直都用鼠標(biāo)來的。。。
?找不到現(xiàn)成的方法,只能自己動(dòng)手豐衣足食了。突然發(fā)現(xiàn) virtual studio是支持宏操作的,于是樓主
靈光一閃,想到了利用宏來自動(dòng)實(shí)現(xiàn)上述功能的方法,不多說,直接上圖。
?1.工具-宏-記錄TemporaryMacro
?
2. 接下來就不用我多說了,和office中的一樣,錄制宏,比如你可以在文本編輯窗口輸入“ ( ”,“?
) ”,“ <— ”(方向鍵),然后停止錄制宏。這樣我們就有了可以自動(dòng)完成雙引號(hào)并定位到中間位
置的快捷操作,依次可以得到自動(dòng)完成圓括號(hào),方括號(hào)等等的宏。這是我自己錄制的7個(gè)宏。
?
3. 接下來我們還要把這些宏和具體的快捷鍵綁定起來,這樣我們只要在鍵盤上敲打快捷鍵就可以自動(dòng)完
成
??
在“顯示命令包含”中輸入“宏”,會(huì)自動(dòng)顯示你剛剛錄制的所有宏,選擇一個(gè),設(shè)置快捷鍵,注意設(shè)
置完要點(diǎn)“分配”
?
?
這樣一個(gè)宏就設(shè)置完了,接下來把你錄制的所有宏都設(shè)置一個(gè)你認(rèn)為方便你操作的快捷鍵即可。
4.接下來和大家分享一下我的設(shè)計(jì)方案。我選取了H,J,K,L,N,M,Alt,空格這8個(gè)元素,她們?cè)阪I盤上的位
置都在右手可以控制的范圍內(nèi),非常靈活便捷,不想錄制的朋友也可以直接粘貼我設(shè)置好的宏代碼。
Alt+H : 刪除,即backspace Sub 刪除()DTE.ActiveDocument.Selection.DeleteLeft() End SubAlt+J:輸入雙引號(hào)并定位到中間Sub 打出雙引號(hào)()DTE.ActiveDocument.Selection.Text = """"""DTE.ActiveDocument.Selection.CharLeft()End SubAlt+K:輸入圓括號(hào)并定位到中間Sub 打出括號(hào)()DTE.ActiveDocument.Selection.Text = "()"DTE.ActiveDocument.Selection.CharLeft()End SubAlt+L:輸入方括號(hào)并定位到中間 Sub 打出方括號(hào)()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+空格:自動(dòng)跳出括號(hào) Sub 跳出()DTE.ActiveDocument.Selection.CharRight() End Sub
Ps:
1.?
所有的vs編輯器都支持宏,所以這個(gè)方法可以用在vs各個(gè)版本上,你也可以依此在office上操作
2.事實(shí)上由于升級(jí)的微軟補(bǔ)丁沖突,很多vs的宏功能已經(jīng)被破壞,是無法運(yùn)行任何宏的。基本都是在安
裝KB2898869、KB2901126、KB2898857等更新后宏停止運(yùn)行。查看了一下提供的解決方案,修改宏配置文
件,VS2010的配置文件路徑為:C:\Program Files (x86)\Common Files\microsoft shared\VSA
\9.0\VsaEnv目錄下的vsmsvr10.exe.config,在RunTime配置節(jié)添加配置項(xiàng):
<AllowDComReflection enabled="1"/>即可
?
32bit和64bit的windows,以及vs不同版本的路徑和配置文件如下
?
在之前7個(gè)宏的基礎(chǔ)上再新加8個(gè)宏,一共15個(gè),基本涵蓋了所有常用的操作。
alt+e:光標(biāo)向上
alt+d:光標(biāo)向下
alt+s:光標(biāo)向左
alt+f:激活文件窗口,有時(shí)由于鼠標(biāo)操作或別的問題代碼頁面會(huì)失去焦點(diǎn),這個(gè)快捷鍵可以讓光標(biāo)重新
出現(xiàn)在代碼文件上
alt+i:復(fù)制代碼段,指定行號(hào),當(dāng)前光標(biāo)位置和指定行之間代碼全部選定
alt+g:指定行號(hào),光標(biāo)自動(dòng)跳到改行
alt+r:將選定代碼段注釋
alt+t:將注釋代碼段解開
15個(gè)快捷鍵全部由alt帶動(dòng), s,e,d,f,r,t,g,h,j,k,l,n,m,i,空格 ? ? 充分考慮手指的擺動(dòng)幅度,幾乎
可以保證最大限度的連續(xù)操作。
并不想將vs真的改造成vim,簡(jiǎn)單,甚好。
另外vs的宏模塊全部可以導(dǎo)出,快捷鍵的綁定配置文件也可以導(dǎo)出,這樣,把這兩個(gè)文件上傳到你的微
云或百度云盤,就可以保證你的隨時(shí)隨地使用了。
??
15Macros.vb( 宏模塊文件,可導(dǎo)入)
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
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 打出括號(hào)()
? ? ? ? DTE.ActiveDocument.Selection.Text = "()"
? ? ? ? DTE.ActiveDocument.Selection.CharLeft()
? ? End Sub
?Sub 向右()
? ? ? ? DTE.ActiveDocument.Selection.CharRight()
?End Sub
? ? Sub 打出方括號(hào)()
? ? ? ? DTE.ActiveDocument.Selection.Text = "[]"
? ? ? ? DTE.ActiveDocument.Selection.CharLeft()
? ? End Sub
? ? Sub 打出雙引號(hào)()
? ? ? ? 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 轉(zhuǎn)行()
? ? ? ? Dim command As Integer
? ? ? ? command = InputBox("Enter a number: ")
? ? ? ? DTE.ActiveDocument.Selection.GotoLine(command)
? ? End Sub
? ? Sub 復(fù)制()
? ? ? ? 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編寫自定義宏,定義解決方案項(xiàng)目折疊、展開快捷鍵
怎樣自己寫一個(gè)宏?
1.打開VS2010(或VS的其它版本),“Tools” --> ?"Macros"--->"Macros IDE...(Alt + F11)" 打開
宏IDE
2.在宏IDE的工具欄中"MyMacros"->"Add Module"->CollapseExpandAllProject
3. 將初始內(nèi)容替換成以下代碼
Option Strict Off
Option Explicit Off
Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports System.Diagnostics
Public Module CollapseExpandAllProject ? ‘(特別注意:這里要與保存的Module名保持一致,不然
無法調(diào)用宏 )
? ? '-----------------------------------------------?
? ? '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
保存后關(guān)閉宏IDE
4、回到VS2010主界面(注意是在VS2010主界面,不是打開了某一個(gè)解決方案的主界面),"Tools"---
>"Options"--->"Environment"--->"Keyboard"--->在Show commands containing:下的編輯框中輸入
macro(所有含macro的那些名稱),會(huì)看到
有"MyMacros.CollapseExpandAllProject.CollapseAllProject"的項(xiàng),選中它,在Press shortcut?
keys:下自定義快捷鍵,建議用Alt + ?數(shù)字0-9和-+鍵組合,以免與編譯環(huán)境快捷鍵發(fā)生沖突,之
后"Assign",最后確定。
5、接下來我們可以驗(yàn)證一下,打開一個(gè)解決方案,按下Alt + 數(shù)字,會(huì)執(zhí)行對(duì)應(yīng)操作。
注意,按下快捷鍵時(shí),鼠標(biāo)要定位到解決方案資源管理器上面,不然會(huì)報(bào)錯(cuò)
參見:
http://www.cnblogs.com/zhangronghua/archive/2010/05/12/Colloapse_Expand_Macro.html
========
VS2010自定義宏注釋模板
通過宏IDE進(jìn)行宏編輯從而達(dá)到在編碼時(shí)實(shí)現(xiàn)自動(dòng)添加注釋的作用。
操作有兩個(gè)步驟:
1、編輯宏注釋
2、為宏添加快捷鍵方便操作。
下面詳說以上兩步:
1、VS2010->工具->宏(Macros)->宏IDE。
接著就是在宏編輯的IDE環(huán)境中,添加新項(xiàng)->新建名稱->宏編輯(參照模板)->保存->返回VS2010。
2、VS2010->工具->選項(xiàng)(Options)->環(huán)境下的鍵盤->在顯示命令包含:的方框中輸入第一步新建的宏注
釋的名字->選擇該宏注釋->定義快捷鍵(按個(gè)人喜歡,不要有沖突)->快捷鍵用于全局->分配->確定。
以上就已經(jīng)做好了你的宏注釋模板了,在以后的個(gè)人編程和團(tuán)隊(duì)工作時(shí)就可以采用這樣的方式進(jìn)行統(tǒng)一
化注釋規(guī)則。
宏注釋模板:
Sub AddFunComment()
? ? ? ? Dim DocSel As EnvDTE.TextSelection
? ? ? ? DocSel = DTE.ActiveDocument.Selection
? ? ? ? DocSel.NewLine()
? ? ? ? DocSel.Text = ""
? ? End Sub
以上學(xué)習(xí)于http://blog.chinaunix.net/uid-21375345-id-3085290.html。
========
使用宏來完成一些煩瑣的代碼
在 Visual Studio 2012 之前的版本,當(dāng)有些效果我們經(jīng)常會(huì)使用但又無法單純的用一個(gè)快捷命令
來實(shí)現(xiàn)時(shí),就可以通過宏來創(chuàng)建自己的快捷命令。但是 Microsoft 再考慮到自定義宏的維護(hù)成本過高而
且只支持VB,因此拋棄了對(duì)它的支持。
下面的演示只限于 Visual Studio 2012 之前的版本。
通過錄制宏來實(shí)現(xiàn)一個(gè)最簡(jiǎn)單的功能
1. 打開 工具 / 宏 / 錄制宏
2. 在代碼編輯器中輸入
Console.WriteLine("Hi");
?
3. 點(diǎn)擊停止錄制宏
打開 工具 / 宏 / 宏資源管理器,找到 RecordingModule 并展開,雙擊 TemporaryMacro。這個(gè)時(shí)
候會(huì)發(fā)現(xiàn)編輯器光標(biāo)所在的位置已經(jīng)自動(dòng)插入了一條 “Console.WriteLine("Hi")” 代碼。
動(dòng)畫演示:如何創(chuàng)建一個(gè)最簡(jiǎn)單的宏
本節(jié)只演示宏的基本功能,更多關(guān)于宏的高級(jí)用法,請(qǐng)見《Visual Studio 宏的高級(jí)用法》。
?
注:2014年2月之后,Windows的一次更新將導(dǎo)致 Visual Studio 無法運(yùn)行 macro,按照該文章的方
法修改三個(gè)配置文件即可以修復(fù)。
?
========
Visual Studio 宏的高級(jí)用法
因?yàn)樽?Visual Studio 2012 開始,微軟已經(jīng)取消了對(duì)宏的支持,所以本篇文章所述內(nèi)容只適用于?
Visual Studio 2010 或更早期版本的 VS。
在上一篇中,我已經(jīng)介紹了如何編寫一個(gè)最簡(jiǎn)單的宏,本文將進(jìn)一步介紹如何用宏來實(shí)現(xiàn)對(duì)代碼編
輯窗口控制。在本文結(jié)束的時(shí)候,你應(yīng)該能自己實(shí)現(xiàn)如下兩個(gè)功能,第一個(gè)用于對(duì)方法體進(jìn)行 phase0?
標(biāo)記;第二個(gè)可以將當(dāng)前窗口中的代碼進(jìn)行歸類,將所有方法、屬性、變量通過region進(jìn)行分塊。
動(dòng)畫演示:phase0?
動(dòng)畫演示:設(shè)置 region
為什么使用宏
在計(jì)算機(jī)行業(yè)內(nèi),宏的出現(xiàn)由來已久,因?yàn)樗芴娲藗儓?zhí)行一些重復(fù)發(fā)生的簡(jiǎn)單但煩瑣的事情,
所以廣受人們歡迎。在 Visual Studio 中也提供了進(jìn)行宏編程的方法,從而方便開發(fā)人員錄制一些宏腳
本來擴(kuò)展Visual Studio,以提高開發(fā)效率。
要想在 Visual Studio 中操作宏來操控代碼編輯窗口,就必須要了解如下幾個(gè)東東:EnvDTE、DTE
、TextSelection、EditPoint。宏可實(shí)現(xiàn)地遠(yuǎn)不止是操控代碼編輯窗口,關(guān)于其它能力請(qǐng)見參考資源[1]
。
本文中的內(nèi)容在閱讀過程中最好能結(jié)合實(shí)踐進(jìn)行練習(xí),這樣印象會(huì)更深刻。?
EnvDTE
EnvDTE 是最核心的程序集,所有后續(xù)要講到的東西都?xì)w于它名下。
MSDN上對(duì)它的介紹:
EnvDTE 是包含 Visual Studio 內(nèi)核自動(dòng)化的對(duì)象和成員的用程序集包裝的 COM 庫。 在 EnvDTE80、
EnvDTE90、 EnvDTE90a 和 EnvDTE100 命名空間中包含更改和新功能。
EnvDTE80、90、100按照數(shù)字,越大的表示越新,因?yàn)閂isual Stuido有好多版本,不同的版本會(huì)提
供新的功能,而這幾個(gè)版本的 EnvDTE 正是對(duì)應(yīng)了這些更新,不同的版本只是在功能上做了補(bǔ)充,并沒
有誰能替代誰的關(guān)系,比如editPoint2 比 editPoint 可能多了某些新特性,當(dāng)你要使用這些新特性的
時(shí)候,就應(yīng)該使用editPoint2,否則還是使用 editPoint。
在編寫自己的擴(kuò)展前,可以把EnvDTE、EnvDTE80 等全部引用進(jìn)來。
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports EnvDTE90a
Imports EnvDTE100
?
DTE對(duì)象
在 Visual Studio 中, DTE 對(duì)象是自動(dòng)化模型中的頂級(jí)對(duì)象,通過操作DTE對(duì)象可以獲取對(duì)?
Visual Studio 的控制,比如你可以得到當(dāng)前活動(dòng)的文檔、活動(dòng)的窗口、活動(dòng)的項(xiàng)目、查找與替換、向
解決方案中添加文件、執(zhí)行預(yù)定義命令、錄制宏等。
DTE包含的屬性(局部)
上面只是截取了一部分,完整的請(qǐng)查看 MSDN?
DTE包含的方法
通過操控這些屬性和方法就可以實(shí)現(xiàn)強(qiáng)大的功能,下面的例子中通過操縱DTE對(duì)象的TextSelecion子
對(duì)象和Find子對(duì)象來調(diào)用 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'相當(dāng)于在當(dāng)前文檔向下搜索一次Dim result = DTE.Find.Execute()If (result = vsFindResult.vsFindResultFound) Then’如果找到,就把那一行選中selection.SelectLine()End IfEnd If
? 上面的代碼并不復(fù)雜,就是簡(jiǎn)單地對(duì) Find 的調(diào)用和賦值。如果你正好看到這里,不仿也試著寫一
下吧~ Find 相關(guān)內(nèi)容請(qǐng)查看參考資源[2]。
TextSelection
用于代表當(dāng)前選定的區(qū)域,一個(gè)文檔有且只有一個(gè)實(shí)例,即使你在代碼中創(chuàng)建了多個(gè)實(shí)例,這些實(shí)
例其實(shí)都是指向同一個(gè)選定區(qū)域。對(duì) TextSelection 的操控會(huì)直接體現(xiàn)在界面上。通過控制該對(duì)象可以
剪切、復(fù)制、刪除選中的文本,插入刪除空白行,大小寫轉(zhuǎn)換,定位到某個(gè)位置、格式化等。
TextSelection 的屬性
TextSelection 的方法(局部)
完整的請(qǐng)查看 MSDN?
?
一句話獲取 TextSelection 實(shí)例,因?yàn)?TextSelection 是針對(duì)文檔的,所以在獲取 Selection 之
前,必須先獲取文檔。如果當(dāng)前文檔中并沒有選中任何文本,則 TextSelection 表示的是當(dāng)前光標(biāo)所在
的位置。
Dim selection As TextSelection = DTE.ActiveDocument.Selection
?
下面演示幾個(gè)例子,來說明 TextSelection 的能力。?
第一個(gè)例子將演示如何獲取當(dāng)前光標(biāo)所在的方法的名稱,主要通過獲取當(dāng)前光標(biāo)所在位置的?
CodeElement 元素來得到具體的方法信息,通過傳入 CodeElement 的參數(shù)不一致可以獲取不同塊的信息
,包括方法、枚舉、屬性、類、名稱空間等。關(guān)于 vsCMElement 的枚舉請(qǐng)見參考資源[4]。
復(fù)制代碼
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
復(fù)制代碼
?
動(dòng)畫演示:顯示方法名
第二個(gè)示例,演示如何在光標(biāo)位置所在的行上下加上Region。
復(fù)制代碼
?1 ? ? Sub DemoRegion()
?2 ?
?3 ? ? ? ? '獲取 TextSelection 實(shí)例
?4 ? ? ? ? Dim selection As TextSelection = DTE.ActiveDocument.Selection
?5 ?
?6 ? ? ? ? '移動(dòng)到當(dāng)前光標(biāo)所在行的最前面
?7 ? ? ? ? selection.StartOfLine()
?8 ? ? ? ? '在該位置插入一個(gè)新行,相當(dāng)于按了下回車
?9 ? ? ? ? selection.NewLine()
10 ? ? ? ? '將光標(biāo)移回到新行
11 ? ? ? ? selection.LineUp()
12 ? ? ? ? '在當(dāng)前光標(biāo)所在的位置開始輸入文字
13 ? ? ? ? selection.Text = "#region start"
14 ?
15 ? ? ? ? '將光標(biāo)移動(dòng)到下一行
16 ? ? ? ? selection.LineDown()
17 ? ? ? ? '將光標(biāo)移動(dòng)到行末
18 ? ? ? ? selection.EndOfLine()
19 ? ? ? ? '回車
20 ? ? ? ? selection.NewLine()
21 ? ? ? ? selection.Text = "#endregion"
22 ?
23 ? ? ? ? '格式化
24 ? ? ? ? selection.SmartFormat()
25 ?
26 ? ? End Sub
復(fù)制代碼
動(dòng)畫演示:在特定行的上下添加region
再來看一個(gè)示例,用戶輸入起始和結(jié)束文字,然后自動(dòng)選中位于這兩個(gè)起始結(jié)束標(biāo)記之間的一段文
本。
復(fù)制代碼
?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 ? ? ? ? '--------------- 找到結(jié)束的文字 ----------------------
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 ? ? ? ? '------------- 遍歷,記錄經(jīng)過的字符數(shù)用于選中 --------
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 ? ? ? ? '設(shè)置起始位置
61 ? ? ? ? selection.MoveToLineAndOffset(startLine, startLineOffset)
62 ? ? ? ? 'True 表示鼠標(biāo)跟隨移動(dòng),len 表示要移動(dòng)的字符數(shù)
63 ? ? ? ? selection.CharRight(True, len)
64 ?
65 ? ? End Sub
復(fù)制代碼
?
動(dòng)畫演示:選中一段文本
EditPoint
Visual Studio 除了在代碼編輯窗口中會(huì)保留代碼,還有一個(gè)叫代碼緩沖區(qū)的地方(用戶是看不到
的)也會(huì)保留代碼,但這個(gè)緩沖區(qū)中的代碼不受自動(dòng)換行和虛擬空格的影響。前面我們說過?
TextSelection 只能有一個(gè),那如果開發(fā)人員事先選中了一行代碼,而我們又在宏中不小心改變了這個(gè)?
TextSelection,那就會(huì)導(dǎo)致用戶的選中被丟失。另外,EditPoint提供了一些TextSelection所不具備的
操作能力。比如剪切一段文本,使用 EditPoint 的 Cut 方法只要設(shè)置起始位置然后直接傳入結(jié)束的位
置給 Cut 方法就可以完成,但是如果使用 TextSelection ,因?yàn)樗?Cut 不帶參數(shù),所以就必須先選
中這段文本才能使用 Cut 方法。
這里補(bǔ)充一個(gè)小知識(shí)點(diǎn),什么是虛擬空格?這個(gè)東東默認(rèn)是關(guān)閉的,在 Visual Studio 開發(fā)的時(shí)候
也很少用。一般我們?cè)趯懘a的時(shí)候,如果在一行的結(jié)尾處使用小鍵盤向右繼續(xù)移動(dòng)的話,光標(biāo)很快就
會(huì)自動(dòng)跳轉(zhuǎn)到下一行。如果開啟之后,則永遠(yuǎn)不會(huì)自動(dòng)跳轉(zhuǎn)到下一行,你可以在任意一個(gè)位置進(jìn)行編輯
。開啟的方式:工具 / 選項(xiàng) / 文本編輯器 / 所有語言 -> 啟用虛擬空格。
所以如果你在項(xiàng)目中會(huì)存在自動(dòng)換行或開啟了虛擬空格,那么想要精準(zhǔn)的控制編輯器,還是使用?
EditPoint 吧。
下面一樣舉個(gè)例子來講解。該示例將把一個(gè)方法的位置進(jìn)行移動(dòng),思路就是先剪切,然后粘貼。
復(fù)制代碼
?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
復(fù)制代碼
?
動(dòng)畫演示:如何剪貼一個(gè)方法
Have a try
辛苦了,看到這里實(shí)在不容易。既然已經(jīng)看到這了,何不來嘗試著自己寫一個(gè)呢?回到開頭的兩個(gè)
示例,看看能不能寫出來了。答案請(qǐng)兇猛的點(diǎn)擊這里。
?
參考資源
[1] 自動(dòng)化與擴(kuò)展性參考
[2] Find 接口
[3] 如何:控制代碼編輯器 (Visual Basic)
[4] vsCMElement 枚舉
?
本文來源于 《Visual Studio 宏的高級(jí)用法》
========
使用Visual Studio 2005 IDE的宏,自動(dòng)為c#變量生成屬性
在編寫c#代碼過程中,我們經(jīng)常需要做一些重復(fù)枯燥的工作。例如,編寫DTO(數(shù)據(jù)訪問對(duì)象),通常就
是為一個(gè)類定義一系列的變量和屬性。
有一些第三方的IDE輔助工具,可以為我們生成一些代碼,減少工作量。例如,Assist X就是一款很值得
推薦的工具,使用其提供的Encapsulate Field功能,可以很方便地將一個(gè)類地編寫封裝為屬性。
我今天需要介紹的如何使用Visual Studio 2005 IDE中自帶的宏實(shí)現(xiàn)類似的功能。
打開Visual Studio 2005 IDE,選擇“工具” > "宏" > “宏 IDE”,選擇“添加模塊”。例如,我是
在MyMacros項(xiàng)目中新增了一個(gè)EditorHelper模塊,代碼如下:
Imports System
Imports EnvDTE
Imports EnvDTE80
Imports System.Diagnostics
Public Module EditorHelper
? ? '為一個(gè)參數(shù)封裝一般屬性訪問器
? ? Public Sub EncapsulateField()
? ? ? ? Dim projectItem As ProjectItem = DTE.ActiveDocument.ProjectItem
? ? ? ? Dim fileCodeModel As FileCodeModel = projectItem.FileCodeModel
? ? ? ? '得到當(dāng)前選定的內(nèi)容
? ? ? ? Dim selectText As TextSelection = DTE.ActiveDocument.Selection
? ? ? ? '獲取到當(dāng)前光標(biāo)的位置
? ? ? ? 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
? ? ? ? ? ? '得到當(dāng)前選定的內(nèi)容
? ? ? ? ? ? Dim selectText As TextSelection = DTE.ActiveDocument.Selection
? ? ? ? ? ? '獲取到當(dāng)前光標(biāo)的位置
? ? ? ? ? ? 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
? ? ? ? ? ? ? ? '如果屬性已經(jīng)定義,會(huì)拋出異常
? ? ? ? ? ? ? ? '在這里處理異常,即使新增的屬性已經(jīng)定義,也可以繼續(xù)處理下面的代碼
? ? ? ? ? ? ? ? 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 ? ? '靜態(tài)變量不需要增加屬性
? ? ? ? ? ? ? ? ? ? ? ? ? ? AddPropertyToClass(codeClass, codeVariable.Name,?
codeVariable.Type)
? ? ? ? ? ? ? ? ? ? ? ? End If
? ? ? ? ? ? ? ? ? ? End If
? ? ? ? ? ? ? ? Catch ex As Exception
? ? ? ? ? ? ? ? ? ? '吃掉異常
? ? ? ? ? ? ? ? End Try
? ? ? ? ? ? Next
? ? ? ? Catch ex As Exception
? ? ? ? ? ? '可能并沒有選擇有效的類定義,這時(shí)會(huì)拋出異常,忽略
? ? ? ? End Try
? ? End Sub
? ? '根據(jù)成員的名稱的類型,在類對(duì)象中插入屬性
? ? Private Sub AddPropertyToClass(ByVal codeClass As CodeClass, ByVal fieldName As String,?
ByVal fieldType As Object)
? ? ? ? '生成屬性的名稱,規(guī)則是首先字母大寫。如果變量的開頭為“_”,移除
? ? ? ? Dim propertyName As String = fieldName
? ? ? ? If (propertyName.StartsWith("_")) Then
? ? ? ? ? ? propertyName = propertyName.TrimStart("_"c)
? ? ? ? End If
? ? ? ? propertyName = propertyName.Substring(0, 1).ToUpper() & propertyName.Substring(1)
? ? ? ? '創(chuàng)建屬性對(duì)象
? ? ? ? '-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) ? ? ? ? '縮進(jìn)4個(gè)位置
? ? ? ? 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) ? ? ? ? '縮進(jìn)4個(gè)位置
? ? ? ? setterEditPoint.Insert(fieldName & " = value;")
? ? End Sub
End Module
我定義了兩個(gè)Public方法:EncapsulateField和EncapsulateAllFields,分別用于為類的一個(gè)變量封裝
屬性,或者為類中所有的變量(非靜態(tài))封裝屬性。
使用上面的宏的方法很簡(jiǎn)單,選擇“工具”>“宏”>“宏資源管理器”就可以看到我們已經(jīng)創(chuàng)建的宏方
法,如下圖所示:
假如你已經(jīng)編寫了這樣一段代碼:
using System;
using System.Collections.Generic;
using System.Text;
namespace Demo
{
? ? public class Person
? ? {
? ? ? ? private int _id;
? ? ? ? private string _name;
? ? ? ? private DateTime _birthDay;
? ? }
}
將光標(biāo)移到“_name”變量上,然后雙擊“EncapsulateField”宏,就運(yùn)行了該宏。運(yùn)行后,你可以得到
這樣的代碼:
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”宏已經(jīng)為private string _name;創(chuàng)建了相應(yīng)的屬性。
EncapsulateAllFields宏只需要將光標(biāo)放在Person類的代碼區(qū)域中,就可以正常執(zhí)行。例如針對(duì)上面的
代碼,EncapsulateAllFields后可以為Person類中的每一個(gè)變量都生成相應(yīng)的屬性。(注:上面的代碼
中Name屬性已經(jīng)有定義,所有試圖再添加Name屬性時(shí)會(huì)拋出異常,在EncapsulateAllFields宏定義中,
已經(jīng)將該異常吃掉,所以,可以正確地為所有變量生成屬性)。運(yùn)行后的代碼如下:
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;
? ? ? ? ? ? }
? ? ? ? }
? ? }
}
在確認(rèn)上面的宏可以正確運(yùn)行的情況下,我們還可以為其定義快捷鍵,進(jìn)一步提高我們的工作效率。
在Visual Studio 2005 IDE中選擇“工具” > “選項(xiàng)”
在“選項(xiàng)”對(duì)話框中選擇“環(huán)境”>“鍵盤”。
在【顯示命令包含】中輸入Encap...,可以幫你快速定位到相應(yīng)的宏命令;
【新快捷鍵用于】選項(xiàng)中選擇“文本編輯器”;
激活【按快捷鍵】輸入框,選擇你所希望的快捷鍵,例如我這里為EncapsulateField定義的快捷鍵
為“Ctrl + `”,為EncapsulateAllFields定義的快捷鍵為“Ctrl + Shift + `”
點(diǎn)擊分配按鈕
你就可以在文本編輯器中盡情享用宏給你帶來的方便。
補(bǔ)充在Visual Studio 2003中使用的宏:
Visual Studio 2003 IDE與Visual Studio 2005 IDE在處理上稍微有些不一致的地方,需要做如下的調(diào)
整:
Imports System
Imports EnvDTE
Imports System.Diagnostics
Public Module EditorHelper
? ? '為一個(gè)參數(shù)封裝一般屬性訪問器
? ? Public Sub EncapsulateField()
? ? ? ? Dim projectItem As ProjectItem = DTE.ActiveDocument.ProjectItem
? ? ? ? Dim fileCodeModel As FileCodeModel = projectItem.FileCodeModel
? ? ? ? '得到當(dāng)前選定的內(nèi)容
? ? ? ? Dim selectText As TextSelection = DTE.ActiveDocument.Selection
? ? ? ? '獲取到當(dāng)前光標(biāo)的位置
? ? ? ? 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
? ? ? ? ? ? '得到當(dāng)前選定的內(nèi)容
? ? ? ? ? ? Dim selectText As TextSelection = DTE.ActiveDocument.Selection
? ? ? ? ? ? '獲取到當(dāng)前光標(biāo)的位置
? ? ? ? ? ? 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
? ? ? ? ? ? ? ? '如果屬性已經(jīng)定義,會(huì)拋出異常
? ? ? ? ? ? ? ? '在這里處理異常,即使新增的屬性已經(jīng)定義,也可以繼續(xù)處理下面的代碼
? ? ? ? ? ? ? ? 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 ? ? '靜態(tài)變量不需要增加屬性
? ? ? ? ? ? ? ? ? ? ? ? ? ? AddPropertyToClass(codeClass, codeVariable.Name,?
codeVariable.Type)
? ? ? ? ? ? ? ? ? ? ? ? End If
? ? ? ? ? ? ? ? ? ? End If
? ? ? ? ? ? ? ? Catch ex As Exception
? ? ? ? ? ? ? ? ? ? '吃掉異常
? ? ? ? ? ? ? ? End Try
? ? ? ? ? ? Next
? ? ? ? Catch ex As Exception
? ? ? ? ? ? '可能并沒有選擇有效的類定義,這時(shí)會(huì)拋出異常,忽略
? ? ? ? ? ? MsgBox(ex.Message)
? ? ? ? End Try
? ? End Sub
? ? '根據(jù)成員的名稱的類型,在類對(duì)象中插入屬性
? ? Private Sub AddPropertyToClass(ByVal codeClass As CodeClass, ByVal fieldName As String,?
ByVal fieldType As Object)
? ? ? ? '生成屬性的名稱,規(guī)則是首先字母大寫。如果變量的開頭為“_”,移除
? ? ? ? Dim propertyName As String = fieldName
? ? ? ? If (propertyName.StartsWith("_")) Then
? ? ? ? ? ? propertyName = propertyName.TrimStart("_"c)
? ? ? ? End If
? ? ? ? propertyName = propertyName.Substring(0, 1).ToUpper() & propertyName.Substring(1)
? ? ? ? '創(chuàng)建屬性對(duì)象
? ? ? ? '-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的宏時(shí),也需要注意一點(diǎn):在使用時(shí),光標(biāo)的應(yīng)該停留在類
定義的空白位置,否則使用Dim codeClass As CodeClass = CType(codeElement, CodeClass)方法不能
正確獲取到類對(duì)象(例如,如果光標(biāo)在構(gòu)造函數(shù)里,獲取到的是構(gòu)造函數(shù)對(duì)象,這點(diǎn)與2005還是有所區(qū)
別的)。
========
使用宏(Macro)擴(kuò)展Visual Studio IDE
雖然有很多工具可以開發(fā).NET程序,但我相信大多數(shù)的開發(fā)人員都是用Visual Studio(簡(jiǎn)稱VS)。VS是
微軟所提供的一款集成開發(fā)工具,其最新版本為VS 2008。
VS使用起來還不錯(cuò),不是嗎?而且它還可以被我們進(jìn)行擴(kuò)展,按照我們自己的需求。這的確是挺誘人的
,對(duì)吧?
認(rèn)真說起來,擴(kuò)展VS的IDE有很多方法,例如你可以通過創(chuàng)建一個(gè)所謂的"Visual Studio外接程序",這
個(gè)外接程序其實(shí)就是一個(gè)實(shí)現(xiàn)了IDTExtensibility2接口的程序集。
t4
關(guān)于外接程序的具體細(xì)節(jié),不是我們這次討論的內(nèi)容。你可以通過下面地址了解
http://msdn2.microsoft.com/zh-cn/library/ms165620(VS.80).aspx
?
外接程序的好處是可以比較集中地封裝大量復(fù)雜的擴(kuò)展,同時(shí)也易于分發(fā)。但相對(duì)來說,所需要的能力
也較高。相對(duì)比而言,另外一個(gè)擴(kuò)展方法——宏擴(kuò)展——?jiǎng)t比較適合輕量級(jí)的擴(kuò)展。它的實(shí)現(xiàn)方式相對(duì)
較為容易。我們下面就以一個(gè)例子來說明如何創(chuàng)建宏,如何運(yùn)行宏,實(shí)現(xiàn)某些有意思的事情。
我們今天要解決的問題是這樣的:
大家知道,每個(gè)解決方案或項(xiàng)目都有一個(gè)相對(duì)應(yīng)的文件目錄。我們經(jīng)常需要定位到這些目錄。以前的做
法是(以項(xiàng)目為例):
1)先選中該項(xiàng)目
2)在它屬性中,復(fù)制它的"項(xiàng)目文件夾"這個(gè)屬性值
3)打開"開始"=>"運(yùn)行"命令,粘貼那個(gè)路徑,然后回車
這些操作沒有什么技術(shù)含量,地球人都知道怎么做。但經(jīng)常這么做,顯然不符合和諧社會(huì)的要求。試想
,如果能在解決方案或者項(xiàng)目的快捷菜單中,就有一個(gè)命令,可以一次性做這樣的事情,那該多好啊
很多事情并不難,尤其是當(dāng)我們以認(rèn)真的態(tài)度正視它的時(shí)候。為了實(shí)現(xiàn)上述要求,我們只需要寫一個(gè)簡(jiǎn)
單的宏。的確如此簡(jiǎn)單!
1)通過ALT+F8 打開宏資源管理器
2)在宏資源管理器中,定位到MyMacros,右鍵中選擇"新建模塊",給新的模塊命名為
ProjectContextMenu或者其他你喜歡的名字。
3)雙擊剛才新建的模塊,把以下的代碼復(fù)制到接下來打開的一個(gè)設(shè)計(jì)器中,并保存。
Imports System
Imports EnvDTE
Imports EnvDTE80
Imports System.Diagnostics
Imports System.IO
'這個(gè)模塊主要是用來為項(xiàng)目添加一些特殊的上下文菜單操作
Public Module ProjectContextMenu
? ? '這個(gè)方法是定位到當(dāng)前項(xiàng)目的目錄
? ? Public Sub NavigateToProjectPath()
? ? ? ? Dim proj As EnvDTE.Project
? ? ? ? proj = DTE.ActiveSolutionProjects(0) '定位到當(dāng)前的項(xiàng)目
? ? ? ? Dim path As String
? ? ? ? path = System.IO.Path.GetDirectoryName(proj.FullName) '取得當(dāng)前項(xiàng)目所在的目錄
? ? ? ? Dim process As New System.Diagnostics.Process
? ? ? ? process.Start("Explorer.exe", path) '打開資源管理器
? ? End Sub
? ? '這個(gè)方法是定位到解決方案的目錄
? ? Public Sub NavigateToSolutionPath()
? ? ? ? Dim sln As EnvDTE.Solution
? ? ? ? sln = DTE.Solution '取得當(dāng)前解決方案
? ? ? ? Dim path As String
? ? ? ? path = System.IO.Path.GetDirectoryName(sln.FullName) '取得當(dāng)前解決方案的目錄
? ? ? ? Dim process As New System.Diagnostics.Process
? ? ? ? process.Start("Explorer.exe", path) '打開資源管理器
? ? End Sub
End Module
這樣我們的宏就做好了,你可以直接執(zhí)行那兩個(gè)方法。看,是不是很神奇呢。它打開了當(dāng)前項(xiàng)目的文件
夾。
t3
當(dāng)然,我們還差最后一步?jīng)]有完成。那就是把這兩個(gè)方法關(guān)聯(lián)到內(nèi)置菜單里面去。
1)你需要通過以下路徑打開自定義工具欄的對(duì)話框。"視圖"=〉"工具欄"==〉"自定義"
2)在"自定義"對(duì)話框中,選中"上下文菜單",你會(huì)發(fā)現(xiàn)所有內(nèi)置的快捷菜單都顯示在頂部了
t7
3)把兩個(gè)宏方法拖拽到相應(yīng)的快捷菜單里面去
t6?
下面是配置好之后的效果:多出了兩個(gè)菜單,分別都指向了上面寫好的兩個(gè)方法。單擊這個(gè)菜單,就可
以很方便地定位到項(xiàng)目或者解決方案的根目錄,免去了復(fù)制,然后粘貼到運(yùn)行窗口的勞動(dòng)。
t1 t
?
附加資源:
Visual Studio自動(dòng)化對(duì)象模型。如果確實(shí)有興趣的朋友可以認(rèn)真看一下(要想寫出高質(zhì)量的VS IDE擴(kuò)展
程序或插件,必須對(duì)該模型有較深入的認(rèn)識(shí))
Vs自動(dòng)化模型圖
如果你的機(jī)器上裝好了MSDN,那么也可以通過下面的導(dǎo)航,了解到更加詳細(xì)的信息
ms-help://MS.VSCC.v80/MS.MSDN.v80/MS.VisualStudio.v80.chs/dv_extcore/html/4173a963-7ac7-
4966-9bb7-e28a9d9f6792.htm
?
最后,你還可以下載VS Sdk進(jìn)行更加深入的了解
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 其他版本?
宏是組合到一起形成一個(gè)命令以自動(dòng)完成某項(xiàng)任務(wù)的一系列命令和指令。 宏允許自動(dòng)重復(fù)操作。?
Visual Studio 包括宏集成開發(fā)環(huán)境 (IDE),該開發(fā)環(huán)境專門用于創(chuàng)建、操作、編輯和運(yùn)行宏。 宏 IDE?
與 Visual Studio IDE 相互獨(dú)立。
本節(jié)內(nèi)容
如何:錄制宏
描述如何創(chuàng)建和錄制宏。
如何:運(yùn)行宏
討論各種運(yùn)行宏和傳遞參數(shù)的方法。
宏的錄制和運(yùn)行問題
提供錄制和運(yùn)行宏時(shí)的常見問題的解決方案。
如何:管理宏
描述如何編輯現(xiàn)有宏或手動(dòng)創(chuàng)建新宏。
調(diào)試宏
討論在宏中出現(xiàn)錯(cuò)誤時(shí)的解決方法。
如何:管理宏
描述宏資源管理器及其上下文菜單。
保存和導(dǎo)出宏文件
描述如何在宏 IDE 中保存和導(dǎo)出宏文件。
宏 IDE 與 Visual Studio IDE 之間的功能差異
描述 Visual Studio 宏和 Visual Studio 之間在擴(kuò)展性模型、Document 對(duì)象、屬性、項(xiàng)操作、Find?
方法、項(xiàng)目以及工具選項(xiàng)方面的差異。
如何:在宏中引用 COM 和 .NET Framework 組件
描述如何使用 Tlbimp 實(shí)用工具使 Visual Studio 宏能夠引用 COM 組件。
如何:在宏中處理環(huán)境事件
討論 EnvironmentEvents 模板、OnMacrosRuntimeReset 事件和 OnStartupComplete 事件。
宏安全性和共享問題
討論與宏有關(guān)的主要安全問題:知識(shí)產(chǎn)權(quán)保護(hù)和病毒的預(yù)防與保護(hù)。
宏示例
列出并描述 Visual Studio 中所包括的宏示例。
相關(guān)章節(jié)
使用宏自動(dòng)執(zhí)行重復(fù)性操作
提供對(duì)如何使用宏以使過程或重復(fù)的擊鍵序列自動(dòng)化的概述。
宏開發(fā)環(huán)境
描述宏 IDE 中的所有對(duì)話框。
Macros
提供有關(guān) Macros 對(duì)象的詳細(xì)信息,該對(duì)象表示 Visual Studio 宏記錄器。
Visual Studio Macros Error Messages
列出與 Visual Studio 宏關(guān)聯(lián)的所有錯(cuò)誤消息。
如何:使用外接程序控制宏
描述如何使用 Visual Studio 自動(dòng)化模型的 Macros 對(duì)象來控制在 IDE 中記錄的宏,包括暫停和重新
激活記錄器、向所記錄的宏中寫入代碼以及確定記錄器當(dāng)前是否正在運(yùn)行。
========
讓Visual Studio 也支持JS代碼折疊
? ? ? Visual Studio的代碼折疊功能非常好用,#region #endregion 這個(gè)詞連搜狗的詞庫里面都出現(xiàn)了(不含'#'號(hào)),可見使用頻率很高,但是他不支持js的代碼折疊 : ( 最近Ext用得比較多,一寫就是上
百行JS代碼,非常不方便,想著自己寫個(gè)擴(kuò)展或插件什么的,意外搜到了下面的文章,已經(jīng)用宏來實(shí)現(xiàn)
了,本文可以理解為該文的簡(jiǎn)單譯本,注意宏代碼部分我有所改動(dòng) : )
?
文章
? ? ? 1. ? ? ?Using #region Directive With JavaScript Files in Visual Studio
?
環(huán)境
? ? ? Microsoft Visual Studio 2008
?
正文
? ? ? 1. ? ? ?打開宏資源管理器:視圖 -> 其他窗口 -> 宏資源管理器
? ? ? 2. ? ? ?創(chuàng)建一個(gè)新模塊
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()'農(nóng)民伯伯 --- 自動(dòng)為"//#endregion"結(jié)束的代碼添加最后一行,不然出錯(cuò)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
保存即可。這里可以省去新建宏的步驟,他會(huì)根據(jù)代碼自動(dòng)給你生成一個(gè)宏的。
注意我加的代碼段,如果不加,并且你的JS最后一行為#endregion,宏將報(bào)錯(cuò),顯示“值不在
預(yù)期的范圍內(nèi)”。?
?
4. 設(shè)置快捷鍵
4.1 工具 -> 選項(xiàng) - > 環(huán)境 -> 鍵盤
4.2 在顯示命令包含下面的文本框中輸入宏名outli,不用輸全,下面能顯示你新建的宏
4.3 點(diǎn)一下 按快捷鍵 下面的文本框, 然后自定義快捷鍵組合,我定義的是Ctrl+M,Ctrl+J
,點(diǎn)分配(別忘了!),點(diǎn)確定。
?
5.效果
5.1 輸入代碼:
//aasdsadsad
//#region
//#endregion
5.2 快捷鍵Ctrl+M,Ctrl+J啟動(dòng)宏,能看到系統(tǒng)的右下角顯示可愛的小方塊在轉(zhuǎn)動(dòng),js編輯
框顯示效果如下:
?
5.3 之后就可以用快捷鍵Ctrl+M,Ctrl+L來[展開/折疊]代碼了,注意關(guān)閉之后重新打開需要
再啟動(dòng)一次宏,展開效果如下:
========
msdn相關(guān)鏈接
https://msdn.microsoft.com/zh-cn/library/aa291605(v=vs.71).aspx
debugger對(duì)象
https://msdn.microsoft.com/zh-cn/library/aa291105(v=vs.71).aspx
公共環(huán)境對(duì)象模型
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
總結(jié)
以上是生活随笔為你收集整理的VS 2010 IDE 宏学习总结的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: js断点和调试学习总结3
- 下一篇: XSS 代码总结