Accessing the clipboard
The clipboard is a system resource used to pass user data between applications in the operating system. This is most often associated with copying and pasting actions in an application. This recipe will show some basics on putting and getting data from the clipboard.
How to do it…
- Let's first define a helper function to get some text from the clipboard, as follows:
def GetClipboardText(): text_obj = wx.TextDataObject() rtext = "" if wx.TheClipboard.IsOpened() or wx.TheClipboard.Open(): if wx.TheClipboard.GetData(text_obj): rtext = text_obj.GetText() wx.TheClipboard.Close() return rtext
- Now, let's do the reverse and define a helper function to put text into the clipboard, as done with the following code:
def SetClipboardText(text): data_o = wx.TextDataObject() data_o.SetText(text) if wx.TheClipboard.IsOpened() or wx.TheClipboard.Open(): wx.TheClipboard.SetData(data_o) wx.TheClipboard.Close()
How it works…
Both functions work by creating TextDataObject
, which provides a platform-independent way to represent the systems' native data format. Then, TheClipboard
object is opened, and it is used to either get data from the clipboard of the given type or put data in the clipboard from the application. This can be boiled down to a simple three step process for any clipboard interaction:
- Open clipboard
- Set or get
DataObject
- Close the clipboard
Closing the clipboard after using is very important; it may prevent other processes from accessing it. The clipboard should only be kept open momentarily.
There's more…
The clipboard supports many other datatypes besides plain text, which can be used based on the situation and needs of the application.
Datatypes |
Description |
---|---|
|
This is a bitmap data from the clipboard (drag and drop) |
|
This is a base class to represent application-specific data |
|
This is a base class to create other data object types |
|
This is a base class to support multiple formats |
|
This is the data object for filenames |
|
This is the HTML-formatted text container |
|
This is the URL container data object |
See also
- Take a look at the next recipe in this chapter, Supporting drag and drop, for more on how clipboard data objects can be used to transfer data between controls.