Determine which process is locking the clipboard

前端 未结 4 537
一生所求
一生所求 2020-12-29 04:58

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

相关标签:
4条回答
  • 2020-12-29 05:50

    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();
    }
    
    0 讨论(0)
  • 2020-12-29 05:50

    To diagnose something like this I would suggest starting with Process Explorer, http://technet.microsoft.com/en-us/sysinternals/bb896653

    0 讨论(0)
  • 2020-12-29 05:51

    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!

    0 讨论(0)
  • 2020-12-29 05:52

    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();
    }
    
    0 讨论(0)
提交回复
热议问题