2011-08-26 42 views
0

我試圖寫一個簡單的Visual Studio 2010中宏搜索字符串(從剪貼板中得到)的解決方案有麻煩寫一個簡單的VS2010宏

是我到目前爲止有:

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 TemporaryMacro() 
     DTE.ExecuteCommand("Edit.FindinFiles") 
     DTE.Find.FindWhat = My.Computer.Clipboard.GetText() 
     DTE.Find.Target = vsFindTarget.vsFindTargetFiles 
     DTE.Find.MatchCase = True 
     DTE.Find.MatchWholeWord = False 
     DTE.Find.MatchInHiddenText = True 
     DTE.Find.PatternSyntax = vsFindPatternSyntax.vsFindPatternSyntaxLiteral 
     DTE.Find.SearchPath = "Entire Solution" 
     DTE.Find.SearchSubfolders = True 
     DTE.Find.FilesOfType = "" 
     DTE.Find.ResultsLocation = vsFindResultsLocation.vsFindResults2 
     DTE.Find.Action = vsFindAction.vsFindActionFindAll 
     If (DTE.Find.Execute() = vsFindResult.vsFindResultNotFound) Then 
      Throw New System.Exception("vsFindResultNotFound") 
     End If 
     DTE.Windows.Item(Constants.vsWindowKindFindReplace).Close() 
    End Sub 
End Module 

不幸的是,它不工作。當我嘗試使用它時,我在'DTE.Find.FindWhat = My.Computer.Clipboard.GetText()'這一行發現'值不在預期範圍內'錯誤。這是我的第一個視覺工作室宏,所以我有點失落。

回答

0

我測試了你的代碼,問題是GetText()返回一個空字符串。當您使用空字符串設置Find.FindWhat時,會引發錯誤。對於測試,嘗試明確地設置Find.FindWhat爲像「hello」這樣的字符串文字,然後查看代碼是否仍然崩潰(在我的測試中它沒有)。

如果不是,那麼問題是爲什麼GetTest()返回一個空字符串。一些閒逛之後,我發現了另一個線程,其中討論了同樣的事情:

Clipboard.GetText returns null (empty string)

您可能要檢查出(解決辦法是在C#)。對於VB代碼,我發現,你可能會想嘗試另一個線程:

http://www.dotnetmonster.com/Uwe/Forum.aspx/vs-net-general/10874/Clipboard-GetText-no-longer-working

看起來像一個惱人的錯誤給我。祝你好運!

0

您的GetText()失敗,因爲宏未在STA線程中運行。這聽起來不可思議,但它是這樣的。 因此,您必須包裝GetText(),以便在STA線程內調用它。 下面是一些代碼,我目前使用:

Private clipString As String = String.Empty 

Function GetClipboardText() As String 
    clipString = "" 
    Dim data = Clipboard.GetDataObject() 
    If Not data Is Nothing Then 
     clipString = data.GetData(System.Windows.Forms.DataFormats.StringFormat) 
    End If 
    ' myString = DataObj.GetText(1) 
    ' MsgBox(myString) 

    ' clipString = _ 
    ' Clipboard.GetDataObject() _ 
    ' .GetData(System.Windows.Forms.DataFormats.StringFormat) 
End Function 

Private Sub StoreClipBoardText(ByVal s As String) 
    clipString = Clipboard.GetDataObject().GetData(System.Windows.Forms.DataFormats.StringFormat) 
End Sub 

我認爲你必須做同樣的,如果你想要把東西放到剪貼板。