Clipboard error -2147221040: OpenClipboard Failed

trying to get this to work, using Mike Driscoll script

import wx

########################################################################
class ClipboardPanel(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent)
        
        lbl = wx.StaticText(self, label="Enter text to copy to clipboard:")
        self.text = wx.TextCtrl(self, style=wx.TE_MULTILINE)
        copyBtn = wx.Button(self, label="Copy")
        copyBtn.Bind(wx.EVT_BUTTON, self.onCopy)
        copyFlushBtn = wx.Button(self, label="Copy and Flush")
        copyFlushBtn.Bind(wx.EVT_BUTTON, self.onCopyAndFlush)
        
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(lbl, 0, wx.ALL, 5)
        sizer.Add(self.text, 1, wx.EXPAND)
        sizer.Add(copyBtn, 0, wx.ALL|wx.CENTER, 5)
        sizer.Add(copyFlushBtn, 0, wx.ALL|wx.CENTER, 5)
        self.SetSizer(sizer)
        
    #----------------------------------------------------------------------
    def onCopy(self, event):
        """"""
        self.dataObj = wx.TextDataObject()
        self.dataObj.SetText(self.text.GetValue())
        if wx.TheClipboard.Open():
            wx.TheClipboard.SetData(self.dataObj)
            wx.TheClipboard.Close()
        else:
            wx.MessageBox("Unable to open the clipboard", "Error")
            
    #----------------------------------------------------------------------
    def onCopyAndFlush(self, event):
        """"""
        self.dataObj = wx.TextDataObject()
        self.dataObj.SetText(self.text.GetValue())
        if wx.TheClipboard.Open():
            wx.TheClipboard.SetData(self.dataObj)
            wx.TheClipboard.Flush()
        else:
            wx.MessageBox("Unable to open the clipboard", "Error")
            
        self.GetParent().Close()

########################################################################
class ClipboardFrame(wx.Frame):
    """"""

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        wx.Frame.__init__(self, None, title="Clipboard Tutorial")
        panel = ClipboardPanel(self)
        self.Show()
    
    
if __name__ == "__main__":
    app = wx.App(False)
    frame = ClipboardFrame()
    app.MainLoop()

periodically I get an error - Failed to put data on the clipboard (error -2147221040: OpenClipboard Failed)

if I paste into note pad after receiving the error
[Window Title]
Shop Error

[Content]
Failed to put data on the clipboard (error -2147221040: OpenClipboard Failed)

[OK]

This of course could be a windows thing,
I’m using win10, python 3.6.8 wx ‘4.1.0 msw (phoenix) wxWidgets 3.1.4’

Thanks in advance.

I tried your code and I don’t see issues (Windows, Python 3.6.4 64 bit,
wxPython 4.1.0).
Are you sure that you don’t have any other program working with the
clipboard?

E.g. if I insert a delay between TheClipboard.Open() and Close() and run
two instances then I can trigger the issue.

Regards,

Dietmar

1 Like

Thanks for your reply, this is an app that runs pretty much all day. The problem seems random, only 1 instance of the app needs to be running. We’re trying to copy data from cells in a grid, one by one and paste into a web site form. Putting try/except doesn’t catch the error, I’ve put a check in which seems to help a bit, but still seems random and happens on all 4 computers on site.
if wx.TheClipboard.IsOpened():
wx.TheClipboard.Close()

Ok, I see. If I call onCopy automatically often enough, then I see the error as well.
Just wait for a small time and try again. After all, TheClipboard.Open() is the same as e.g. a threading.Lock to make sure only one program uses the exclusive resource.
I would not worry about that. There may be Windows processes checking the clipboard.

I have just tried with win32clipboard and I see the problem there as well.

(Be aware that win32clipboard.OpenClipboard wil raise pywintypes.error: (5, 'OpenClipboard', 'Access denied')

    def onCopy(self, event=None):
        text = self.text.GetValue()
        window_handle = self.GetHandle()
        win32clipboard.OpenClipboard(window_handle)  # will raise an error if it fails
        try:
            win32clipboard.EmptyClipboard()
            if sys.version_info.major==2:
                is_unicode = isinstance(text, str)
            else:
                is_unicode = True
            if is_unicode:
                win32clipboard.SetClipboardData(win32clipboard.CF_UNICODETEXT, text)
            else:
                win32clipboard.SetClipboardText(text)
        finally:
            win32clipboard.CloseClipboard()
1 Like

Thanks a million for your help, if I could catch the error I could display my own message, I think the error message we’re seeing is from windows.

Oh, yes, you’re right. wx.TheClipboard.Open() should not trigger an error dialog.
As workaround you may switch to the win32clipboard code.

changed to win32clipboard as suggested and has been running for some days now without a single error, again, thanks for your help.