I've been working on a program that uses mouse and keyboard simulation and often has to grab/set clipboard data.
I've ran into the problem apparently many people runs into, the clipboard is being used by another process so "Clipboard.SetDataObject" throws the exception "Requested Clipboard operation did not succeed."
private void CheckSetClipboard(string s)
{
IntPtr ClipWindow = GetOpenClipboardWindow();
if (ClipWindow != null && ClipWindow != (IntPtr)0)
{
uint wid;
GetWindowThreadProcessId(ClipWindow, out wid);
Process p = Process.GetProcessById((int)wid);
Console.WriteLine("Process using Clipboard: " + p.ProcessName);
} else {
Console.WriteLine("ClipWindow:" + ClipWindow.ToString());
}
OpenClipboard(IntPtr.Zero);
EmptyClipboard();
CloseClipboard();
try { Clipboard.SetDataObject(s, true, 10, 50); }
catch{// Clipboard.SetDataObject(s, true, 10, 50);
}
}
I tried a few solutions as the code above shows but eventually the error pops up again. This time I decided to go full ham on it and got the process name of the process using the clipboard..
This is what the console showed:
Process using Clipboard: Idle
How is Idle.exe using the clipboard?
Can I even kill that process to release the clipboard?
Am I doing something wrong?
In the end, I just want to be able to do clipboard operations without failures. Ctrl+c and Ctrl+v never fails, why does my c# code does?
More info:
The data i'm passing into the clipboard is "-0.09261441" or similar numbers.
The error always occurs on the catch{...} part.
[SOLVED] Thanks to Hans, I was able to figure it out. I misinterpreted the tip and sample code on pinvoke. Those two clipboard operations in that try{}catch{} were apparently conflicting in some way. The proper way would have been to use try{}catch{try{}catch{}} which I didn't use and didn't test.
My problems seems to have solved themselves for now when I commented out the second clipboard operation.