Showing posts with label clipboard. Show all posts
Showing posts with label clipboard. Show all posts

Wednesday, July 16, 2008

Clipboard problems

Today I when I copied some text,
I couldn't paste it anywhere.

Usually I just use the shortcut keys,
but to test it now, I used the contextmenus.
Copy (or cut) appeared just fine, but when I wanted to paste,
the item was grayed out in the menu.

Looking for the clipboard viewer,
I located it in c:\windows\system32 folder, named clipbrd.exe.

As I started it, it gave me the following error :
The ClipBook service is unavailable or is not started.
Contact your system administrator to have this service started.


All fine and well, but what a weird error, looking at the clipbook service description I found :
Enables ClipBook Viewer to store information and share it with remote computers.


Not exactly what I needed, as remote computers or the clipbook viewer were not my target.

So I just clicked OK,
and tested the viewer,
and 'lo and behold my clipboard functions were working again and I could copy and paste as I wanted.

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