Clipboard.GetImage()返回null

MrW*_*Wuf 3 c# clipboard winforms

我有一个DataGridView包含一个Image列和一些文本列.我有一个非常简单的处理程序,允许用户从单元格中复制文本或图像,并将图像和文本粘贴到它们中.复制/粘贴在文本上正常工作,但粘贴不适用于图像.(注意:如果我粘贴从另一个应用程序放置在剪贴板上的图像,如Paint,那么它工作正常)

如果我立即调用它Clipboard.GetImage()Clipboard.SetImage()它工作正常,这使我相信它可能是一个范围问题或者Clipboard是从图像中获取引用而不是底层字节.我是否必须将原始图像字节放在共享位置?我检查了GetImageMSDN定义,以确保我正确地执行了它.

    private void dataGridView_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.V && e.Modifiers == Keys.Control)
        {
            if (Clipboard.ContainsImage())
            {
                Image img = Clipboard.GetImage();  // always returns null

                if (cell.ColumnIndex == _imageCol)
                    cell.Value = img;
            }

            if (Clipboard.ContainsText())
            {
                if (cell.ColumnIndex != _imageCol)
                    cell.Value = Clipboard.GetText(); // always works
            }
        }

        if (e.KeyCode == Keys.C && e.Modifiers == Keys.Control)
        {
            DataGridViewCell cell = dataGridView1.SelectedCells[0];

            if (cell.ColumnIndex == _imageCol)
            {
                Clipboard.SetImage((Image)cell.Value);
                Image img2 = Clipboard.GetImage();  // successfully returns the Image
            }
            else
                Clipboard.SetText((string)cell.Value);
        }
    }
Run Code Online (Sandbox Code Playgroud)

Han*_*ant 6

你不指望的是DataGridView 实现了复制/粘贴.使用与使用相同的快捷键,Ctrl + C和Ctrl + V. 所以它看起来就像你将图像放在剪贴板上后一样,但DGV也会这样做并覆盖剪贴板内容.不幸的是,它不复制图像,只复制文本.图像列的空字符串.

你必须告诉它你处理了击键:

    private void dataGridView1_KeyDown(object sender, KeyEventArgs e) {
        if (e.KeyCode == Keys.V && e.Modifiers == Keys.Control) {
            // etc...
            e.Handled = true;
        }

        if (e.KeyCode == Keys.C && e.Modifiers == Keys.Control) {
            // etc...
            e.Handled = true;
        }
    }
Run Code Online (Sandbox Code Playgroud)