Setting the Clipboard

From IronPython Cookbook

Revision as of 23:42, 31 May 2007 by MichaelFoord (Talk | contribs)
(diff) ← Older revision | Current revision (diff) | Newer revision → (diff)

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

def SetText(text):
    def thread_proc():

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

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.