Friday, March 23, 2007

Access the clipboard from a visual studio macro

Visual Studio macros can save a lot of time,
automating the workspace,
but when you try to access the clipboard,
the following error pops up :
Current thread must be set to singe threat apartment (STA) mode before OLE calls can be made. Ensure that your main function has STAThreatAttribute marked on it.
Not so nice,

The trick to solve this is create a new thread, have the STA flag set and let that thread access the clipboard.

I created a new macro module modClipboard with the following functions :

Private clipText As String

Public Property ClipboardText() As String
Get
RunThread(AddressOf GetClipboardText)
Return clipText
End Get
Set(ByVal value As String)
clipText = value
RunThread(AddressOf CopyToClipboard)
End Set
End Property

Private Function RunThread(ByVal fct As Threading.ThreadStart)
Dim thread As New Threading.Thread(fct)
thread.ApartmentState = Threading.ApartmentState.STA

thread.Start()
thread.Join()
End Function

Private Sub GetClipboardText()
clipText = Clipboard.GetText()
End Sub

Private Sub CopyToClipboard()
'The second parameter is required
Clipboard.SetDataObject(clipText, True)
End Sub

The module variable (cliptext) is required to transfer the data between the threads.

And now we can call the property in our other functions :
 
Copy to clipboard :
ClipboardText = "Whatever you want"

Get the clipboard data :
  strClipboard = ClipboardText

1 comment:

Anonymous said...
This comment has been removed by a blog administrator.