I have a peculiar error where some process occasionally appears to be using the clipboard when my application goes to handle copy & paste operations. There are some ret
Based on Jeff Roe's answer, but shows how to get the text length, so could be > 500. Also handles case where window is not found.
[System.Runtime.InteropServices.DllImport("user32.dll")]
static extern IntPtr GetOpenClipboardWindow();
[System.Runtime.InteropServices.DllImport("user32.dll")]
static extern int GetWindowText(int hwnd, StringBuilder text, int count);
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern int GetWindowTextLength(int hwnd);
private static string GetOpenClipboardWindowText()
{
var hwnd = GetOpenClipboardWindow();
if (hwnd == IntPtr.Zero)
{
return "Unknown";
}
var int32Handle = hwnd.ToInt32();
var len = GetWindowTextLength(int32Handle);
var sb = new StringBuilder(len);
GetWindowText(int32Handle, sb, len);
return sb.ToString();
}
To diagnose something like this I would suggest starting with Process Explorer, http://technet.microsoft.com/en-us/sysinternals/bb896653
I've wrapped my solution into an easy-to-use method (and some declarations):
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr GetOpenClipboardWindow();
[DllImport("user32.dll", SetLastError = true)]
static extern int GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);
private static Process GetProcessLockingClipboard()
{
int processId;
GetWindowThreadProcessId(GetOpenClipboardWindow(), out processId);
return Process.GetProcessById(processId);
}
Enjoy!
Here's a similar solution, but this gives you a string you can show the user:
[System.Runtime.InteropServices.DllImport("user32.dll")]
static extern IntPtr GetOpenClipboardWindow();
[System.Runtime.InteropServices.DllImport("user32.dll")]
static extern int GetWindowText(int hwnd, StringBuilder text, int count);
private string getOpenClipboardWindowText()
{
IntPtr hwnd = GetOpenClipboardWindow();
StringBuilder sb = new StringBuilder(501);
GetWindowText(hwnd.ToInt32(), sb, 500);
return sb.ToString();
}