How to paste text or image from clipboard in C# and VB.NET

Sample C#

public string PasteTextFromClipboard()
{
	var dataObject = System.Windows.Forms.Clipboard.GetDataObject();
	var o = System.Windows.Forms.Clipboard.GetDataObject();
	if (o != null)
	{
		return dataObject != null && dataObject.GetDataPresent(DataFormats.Text) ? o.GetData(DataFormats.Text).ToString() : "";
	}
	return String.Empty;
}

public Image PasteImageFromClipboard()
{
	var dataObject = System.Windows.Forms.Clipboard.GetDataObject();
	if (dataObject == null || !dataObject.GetDataPresent(DataFormats.Bitmap)) return (null);
	var o = System.Windows.Forms.Clipboard.GetDataObject();
	if (o != null)
	{
		return ((Bitmap) o.GetData(DataFormats.Bitmap));
	}
	return (null);
}

Sample VB.NET

Public Function PasteTextFromClipboard() As String
	Dim dataObject = System.Windows.Forms.Clipboard.GetDataObject()
	Dim o = System.Windows.Forms.Clipboard.GetDataObject()
	If o IsNot Nothing Then
		Return If(dataObject IsNot Nothing AndAlso dataObject.GetDataPresent(DataFormats.Text), o.GetData(DataFormats.Text).ToString(), "")
	End If
	Return [String].Empty
End Function

Public Function PasteImageFromClipboard() As Image
	Dim dataObject = System.Windows.Forms.Clipboard.GetDataObject()
	If dataObject Is Nothing OrElse Not dataObject.GetDataPresent(DataFormats.Bitmap) Then
		Return (Nothing)
	End If
	Dim o = System.Windows.Forms.Clipboard.GetDataObject()
	If o IsNot Nothing Then
		Return DirectCast(o.GetData(DataFormats.Bitmap), Bitmap)
	End If
	Return (Nothing)
End Function

One thought on “How to paste text or image from clipboard in C# and VB.NET

Leave a Reply