Using the clipboard
Sorry that I have not made a post in a while, but I have been very busy at work lately fixing bugs in the Whidbey object model, as well as working to get a new way of writing wizards ready (more info on that in a few days).
Not too long ago I was browsing the net, and found a code snip that I sent to somebody describing how to use the clipboard from a macro. Because of the way the Macros IDE runs macros on behalf of Visual Studio, there are some problems when trying to access some features of the .NET frameworks. An example of this problem is when trying to access the clipboard. If you were to run this code:
Sub GetCBData()
Dim o As System.Windows.Forms.IDataObject
Dim s As String
o = System.Windows.Forms.Clipboard.GetDataObject()
s = o.GetData(System.Windows.Forms.DataFormats.StringFormat)
MsgBox(s)
End Sub
You would get back an “Object reference not set to an instance of an object.” exception. How do you work around it? You will need to create a new thread, and set the clipboard from within that thread. Here is a class to do just such a thing:
Public Class MacroClipBoard
Dim str As String
Function GetFromProxy() As String
Dim t As New System.Threading.Thread(AddressOf GetFrom)
t.Start()
t.Join()
Return str
End Function
Sub CopyToProxy(ByVal s As String)
str = s
Dim t As New System.Threading.Thread(AddressOf CopyTo)
t.Start()
While (t.IsAlive)
'Do nothing. Wait for the thread to do its work.
End While
t.Join()
End Sub
Sub GetFrom()
Dim o As System.Windows.Forms.IDataObject
o = System.Windows.Forms.Clipboard.GetDataObject()
str = o.GetData(System.Windows.Forms.DataFormats.StringFormat)
End Sub
Sub CopyTo()
System.Windows.Forms.Clipboard.SetDataObject(str, True)
End Sub
End Class
To use this class, you would run code such as this:
Sub testcb()
Dim macroCB As New MacroClipBoard
macroCB.CopyToProxy("Some random string")
MsgBox(macroCB.GetFromProxy)
End Sub
This code only works with string data types, but you could easily modify it to return other types such as bitmaps.
Edit 2/16: I made a small change to the CopyToProxy function, replacing the strike-through text with “t.Join()”