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?
Use:
Clipboard.SetText("some string");
Clipboard.GetText();
See the MSDN article Clipboard Class (System.Windows.Forms).
I have done it using Win32 API calls (EmptyClipboard function).
Clipboard.Clear()
MSDN
An easy way to clear the contents it to replace it with just a space character:
public static void Clear()
{
Thread STAThread = new Thread(
delegate ()
{
System.Windows.Forms.Clipboard.SetText(" ");
});
STAThread.SetApartmentState(ApartmentState.STA);
STAThread.Start();
STAThread.Join();
}
精彩评论