How do I backup and restore the system clipboard in C#?

Posted by gtaborga on Stack Overflow See other posts from Stack Overflow or by gtaborga
Published on 2010-04-05T14:34:57Z Indexed on 2010/04/05 16:13 UTC
Read the original article Hit count: 653

Filed under:
|
|
|

Hey everyone,

I will do my best to explain in detail what I'm trying to achieve.

I'm using C# with IntPtr window handles to perform a CTRL-C copy operation on an external application from my own C# application. I had to do this because there was no way of accessing the text directly using GET_TEXT. I'm then using the text content of that copy within my application. The problem here is that I have now overwritten the clipboard.

What I would like to be able to do is:

  1. Backup the original contents of the clipboard which could have been set by any application other than my own.
  2. Then perform the copy and store the value into my application.
  3. Then restore the original contents of the clipboard so that the user still has access to his/her original clipboard data.

This is the code I have tried so far:

private void GetClipboardText() {

text = "";

IDataObject backupClipboad = Clipboard.GetDataObject();

KeyboardInput input = new KeyboardInput(this);
input.Copy(dialogHandle); // Performs a CTRL-C (copy) operation

IDataObject clipboard = Clipboard.GetDataObject(); 
if (clipboard.GetDataPresent(DataFormats.Text))
{
    // Retrieves the text from the clipboard
    text = clipboard.GetData(DataFormats.Text) as string;
}

if (backupClipboad != null) 
{
    Clipboard.SetDataObject(backupClipboad, true); // throws exception
}

}

I am using the System.Windows.Clipboard and not the System.Windows.Forms.Clipboard. The reason for this was that when I performed the CTRL-C, the Clipboard class from System.Windows.Forms did not return any data, but the system clipboard did.

I looked into some of the low level user32 calls like OpenClipboard, EmptyClipboard, and CloseClipboard hoping that they would help my do this but so far I keep getting COM exceptions when trying to restore.

I thought perhaps this had to do with the OpenClipboard parameter which is expecting an IntPtr window handle of the application which wants to take control of the clipboard. Since I mentioned that my application does not have a GUI this is a challenge. I wasn't sure what to pass here. Maybe someone can shed some light on that?

Am I using the Clipboard class incorrectly? Is there a clear way to obtain the IntPtr window handle of an application with no GUI? Does anyone know of a better way to backup and restore the system clipboard?

© Stack Overflow or respective owner

Related posts about clipboard

Related posts about backup