Reputation: 4850
Mysterious clipboard issue:
I have an application under development that launches an external application (as a System.Diagnostics.Process object) which is expected to copy some data (text) to the clipboard. When the external app closes, the client application retrieves the text from the clipboard.
The problem is that although once the external application has copied the text to the clipboard I can paste it into, say, notepad, the client app is getting an empty string from the clipboard.
external app code:
private void btn1_Click(object sender, EventArgs e)
{
//copy text pane to clipboard
DataObject obj = new DataObject();
obj.SetData(tbText.Text);
System.Windows.Forms.Clipboard.SetDataObject(obj);
}
Client app code:
string returnedValues = string.Empty;
System.Windows.Forms.IDataObject data = System.Windows.Forms.Clipboard.GetDataObject();
if (data != null && data.GetDataPresent(System.Windows.Forms.DataFormats.Text) == true)
{
returnedValues = (string) data.GetData(System.Windows.Forms.DataFormats.Text, true));
}
The data object is always null, even though the clipboard has the text in it and I can paste it into other applications.
Can anyone point me at the flaw in the client app code? Why is 'data' always null, even though there is data on the clipboard?
Upvotes: 2
Views: 2449
Reputation: 12195
For text, you really should use SetText()
and GetText()
. And make sure that overwriting the current content of the clipboard is what the user expects in your scenario. If not, you should use interprocess communication instead, see e.g. What is the simplest method of inter-process communication between 2 C# processes?
Upvotes: 0
Reputation: 2674
When all your clipboard has is an string copied as text, you have to retrieve it as
Clipboard.GetText()
and to retrieve other types of objects you can use GetData()
Upvotes: 1