Setting the Clipboard

From IronPython Cookbook

(Difference between revisions)
(New page: Inspired by a blog entry from [http://thepowershellguy.com/blogs/posh/archive/2007/02/20/using-ironpython-from-powershell-part-2-clipboard-sta-mode.aspx The Powershell Guy]. The clipboard...)
 
(2 intermediate revisions not shown)
Line 18: Line 18:
-
You can then import ''SetText'', and call ''SetText('Some text')'' to put text on the clipboard.
+
You can then import ''SetText'', and call ''SetText('Some text')'' to put text on the clipboard, even from apps running from multi-threaded apartment.  For more information on the clipboard, including setting images and custom datatypes [http://www.voidspace.org.uk/ironpython/winforms/part8.shtml Windows Forms Tutorial: The Clipboard].
 +
 
 +
 
 +
Back to [[Contents]].

Current revision as of 23:42, 31 May 2007

Inspired by a blog entry from The Powershell Guy.

The clipboard can only be set from an STA thread. Powershell runs as an MTA. The following code uses the System.Windows.Forms.Clipboard class from a thread launched as an STA.

import clr
import System
from System.Threading import Thread, ThreadStart
clr.AddReference("System.Windows.Forms")

def SetText(text):
    def thread_proc():
        System.Windows.Forms.Clipboard.SetText(text)

    t = Thread(ThreadStart(thread_proc))
    t.ApartmentState = System.Threading.ApartmentState.STA
    t.Start()


You can then import SetText, and call SetText('Some text') to put text on the clipboard, even from apps running from multi-threaded apartment. For more information on the clipboard, including setting images and custom datatypes Windows Forms Tutorial: The Clipboard.


Back to Contents.

TOOLBOX
LANGUAGES