How to handle a blocked clipboard and other oddities

前端 未结 8 2017
闹比i
闹比i 2020-12-02 10:03

Over the course of the last couple of hours I have been tracking down a fairly specific bug with that occurs because another application has the clipboard open. Essentially

8条回答
  •  庸人自扰
    2020-12-02 10:25

    By making use of Jeff Roe's code (Jeff's Code)

    [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 void btnCopy_Click(object sender, EventArgs e)
    {
        try
        {
            Clipboard.Clear();
            Clipboard.SetText(textBox1.Text);
        }
        catch (Exception ex)
        {
            string msg = ex.Message;
            msg += Environment.NewLine;
            msg += Environment.NewLine;
            msg += "The problem:";
            msg += Environment.NewLine;
            msg += getOpenClipboardWindowText();
            MessageBox.Show(msg);
        }
    }
    
    private string getOpenClipboardWindowText()
    {
        IntPtr hwnd = GetOpenClipboardWindow();
        StringBuilder sb = new StringBuilder(501);
        GetWindowText(hwnd.ToInt32(), sb, 500);
        return sb.ToString();
        // example:
        // skype_plugin_core_proxy_window: 02490E80
    }
    

    you are able to handle the error in a pretty handy way.

    I have managed to reduce the frequency of the error by making use of System.Windows.Forms.Clipboard Instead of System.Windows.Clipboard.

    I stress that this doesn't fix the problem but it has reduced the occurrence for my application.

提交回复
热议问题