Using the ClipBoard in a MacroUse Threading to Access Clipboard in Macro | | How do I access the Clipboard in a Macro? Just using GetData and SetDataObject does not work. This article will show you how.
You would think that the Clipboard object would work the same in a Macro as it does in an application. That would not be correct. If you simply try to use the clipboard in a Macro, your code will fail due to the way that macros work at the behest of the IDE. The error you will get is the old "object not set to an instance of an object" message. Therefore, to make a long story short, you need to create a separate thread to access the Clipboard.
First, make sure that the following Imports are present in the Macro Module that you will use for your sample macro to access the Clipboard.
Imports System.Threading
Imports System.Windows.Forms
|
Next, place the following module level variable in the module.
Private clipString As String = String.Empty
|
Next, create a method in the Module to retrieve the contents of the Clipboard as follows:
Public Sub GetClipboard()
Dim cbThread As Threading.Thread = _
New Threading.Thread(AddressOf GetClipboardText)
With cbThread
.ApartmentState = ApartmentState.STA
.IsBackground = True
.Start()
' Wait for clipboard action
.Join()
End With
cbThread = Nothing
' at this point, the contents of the Clipboard will be in the
' module level variable clipString
End Sub
|
Finally, create a method that will place text on the Clipboard as shown below:
Public Sub SetClipboard(ByVal text As String)
' put the results back on the clipboard
Dim ClipBoardThread As Threading.Thread = _
New Threading.Thread(AddressOf PutTextOnClipboard)
With ClipBoardThread
.ApartmentState = ApartmentState.STA
.IsBackground = True
.Start()
' Wait for clipboard action
.Join()
End With
ClipBoardThread = Nothing
End Sub
|
The following methods are called by the two threads created in the code shown above.
Sub GetClipboardText()
clipString = _
Clipboard.GetDataObject() _
.GetData(System.Windows.Forms.DataFormats.StringFormat)
End Sub
Sub PutTextOnClipboard()
Clipboard.SetDataObject(clipString, True)
End Sub
|
Have you tried our newest product, Visual Class Organizer? You'll be amazed how easy it is to keep the code in your code windows organized. TRY IT FREE FOR 30 DAYS BY CLICKING HERE.
If you are developing in C# and haven't tried CSharpCompleter, you are wasting valuable time typing hundreds of braces {} daily needlessly. Try CSharpCompleter for 30 DAYS FREE.
| Ask a Question, or give your feedback on my articles or products by going to the KnowDotNet Forum or by clicking on My Blog. |  | |