How can I retrieve data from a clipboard with sparse ASP.NET code?
QUESTION POSED ON: 12 SEP 2005
QUESTION ANSWERED BY: Andrew Young
I would use C# for this solution, as I have found it normally requires a little less code.
- Create a new C# ASP.NET Web application.
- Add a new Web form.
- Put a button, two textboxes and a label on the form.
- Create a new class library.
- Be sure to add a reference to the System.Windows.Forms.dll namespace.
The .NET framework contains a Clipboard class, which resides within this namespace. You can store data on the clipboard using the IDataObject interface of the same namespace, and you can also retrieve data from the clipboard via this interface. Take a look at the members of this interface in your object browser; the names are self-explanatory. The example below will copy the text from TextBox1 to the clipboard, and use the Clipboard class to access the data and assign it to TextBox2 of the same form.
Place a method in your new class, something like this:
public String returnData()
{
IDataObject d = Clipboard.GetDataObject();
if(d.GetDataPresent(DataFormats.Bitmap))
{
return "Bitmap data on clipboard!!";
}
else if(d.GetDataPresent(DataFormats.Text))
{
return (String)d.GetData(DataFormats.Text);
}
else
{
return "Unknown format of data is Contained on the clipboard.";
}
}
You are instantiating an IDataObject reference via the GetDataObject member of the Clipboard class. The Clipboard class is derived directly from the Object class. You can now derive all of the members of the IDataObject interface, such as SetData, GetData and GetDataPresent.
Remember to cast the return value for the text to a string, and build your class library before instantiating any reference to it in the code-behind C# page of your Web form.
Add a reference to your new class library in your application, and make sure that the namespace(DLL), has been added to the "bin" directory of your application. Let's pretend that we called the namespace "GetClipData" and left the class name defaulted. Put something like this in the button of your code-behind page:
private void Button1_Click(object sender, System.EventArgs e)
{
if (TextBox1.Text == "")
{
Label1.Text = "No text entered in text box";
TextBox2.Text = "";
}
else
{
Clipboard.SetDataObject(TextBox1.Text);
GetClipData.Class1 rt = new GetClipData.Class1();
if(rt == null)
{
TextBox2.Text = "Error instantiating object";
Label1.Text = "Unsuccessful";
}
else
{
TextBox2.Text = rt.returnData();
Label1.Text = "Success!!!";
}
}
}//end button
Of course, you could have just done all of this within the code of your button without creating a class, but it's up to you. I always opt for the most encapsulated approach in ASP.NET, since it keeps your code much cleaner and reusable.
|
 |
|