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

Monday, March 5, 2007

Lost the menu in Vista?

Can't find the things you want to do in Vista?

The menu gone with the wind?

Don't fear, in most programs, you can just press the Alt key to make the trusted menus visible.

This will not work in all programs,
but it will work in a good number of them (mediaplayer, Internet Explorer, folder windows, ... )
but not in office 2007