Clipboard.GetImage()返回null

时间:2015-09-08 15:36:32

标签: c# winforms clipboard

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

如果我在Clipboard.GetImage()之后立即拨打Clipboard.SetImage()它工作正常,这会让我相信它可能是一个范围问题,或者Clipboard正在抓取参考而不是来自图像的底层字节。我是否必须将原始图像字节放在共享位置?我检查了MSDN definition for GetImage,以确保我做得正确。

    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);
        }
    }

0 个答案:

没有答案