Dinesh
Dinesh

Reputation: 2066

How to clear the clipboard contents using C#

I have an application where I am using the clipboard for copy and paste operations. For copying I have used this code:

Clipboard.Clear();
const byte VK_CONTROL = 0x11;
keybd_event(VK_CONTROL, 0, 0, 0);
keybd_event(0x43, 0, 0, 0); // Send the C key (43 is "C")
keybd_event(0x43, 0, CONST_KEYEVENTF_KEYUP, 0);
keybd_event(VK_CONTROL, 0, CONST_KEYEVENTF_KEYUP, 0);

But it's giving an error saying Unable to perform the clipboard action, and I am unable to paste it. It's throwing an exception.

How do I fix this issue or are there some other ways to clear the clipboard content before we copy?

Upvotes: 1

Views: 13622

Answers (4)

Taylor
Taylor

Reputation: 1

I know this is an older thread but I came upon this problem and it was very irritating. Was able to resolve using this. Inside of Class

[DllImport("user32.dll")]static extern IntPtr GetOpenClipboardWindow();

[DllImport("user32.dll")]private static extern bool OpenClipboard(IntPtr hWndNewOwner);

[DllImport("user32.dll")]static extern bool EmptyClipboard();

[DllImport("user32.dll", SetLastError=true)]static extern bool CloseClipboard();

Where I wanted to Clear the Clipboard

IntPtr handleWnd = GetOpenClipboardWindow();
OpenClipboard(handleWnd);
EmptyClipboard();
CloseClipboard();

Upvotes: 0

Dinesh
Dinesh

Reputation: 2066

I have done it using Win32 API calls (EmptyClipboard function).

Upvotes: 1

Jesper Fyhr Knudsen
Jesper Fyhr Knudsen

Reputation: 7917

Use:

Clipboard.SetText("some string");
Clipboard.GetText();

See the MSDN article Clipboard Class (System.Windows.Forms).

Upvotes: 2

Homam
Homam

Reputation: 23841

Clipboard.Clear()

MSDN

Upvotes: 0

Related Questions