#728 – Using the Clipboard to Transfer Other Types of Data

As with drag-and-drop, you can transfer data between two running WPF applications in a variety of formats, using the clipboard.

The full list of data formats that you can specify is listed as a set of static fields in the System.Windows.DataFormats class.  Keep in mind that these are just labels used by the two applications to communicate with each other what data format is being transfered.

Below is an example of transfering some Xaml data between two applications using the clipboard.

On the copy side:

        private void btnCopy_Click(object sender, RoutedEventArgs e)
        {
            string xaml = XamlWriter.Save(e.Source);
            DataObject data = new DataObject(DataFormats.Xaml, xaml);

            Clipboard.SetDataObject(data);
        }

On the paste side:

        private void btnPaste_Click(object sender, RoutedEventArgs e)
        {
            IDataObject data = Clipboard.GetDataObject();
            if (data.GetDataPresent(DataFormats.Xaml))
            {
                string xaml = (string)data.GetData(DataFormats.Xaml);
                MessageBox.Show(xaml);
            }
        }

728-001
728-002

Advertisements

#720 – Discovering What Kind of Data Is on the Clipboard

You can use one of several static methods in the Clipboard class to find out what type of data is currently on the Windows clipboard.

There are several methods that check for a specific format (ContainsAudioContainsFileDropListContainsImage, and ContainsText).  You can also use the ContainsData method to check for a specific format.

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            StringBuilder sbCB = new StringBuilder();

            // Check for some specific formats
            if (Clipboard.ContainsAudio())
                sbCB.Append("Audio ");

            if (Clipboard.ContainsFileDropList())
                sbCB.Append("FileDropList ");

            if (Clipboard.ContainsImage())
                sbCB.Append("Image ");

            if (Clipboard.ContainsText())
                sbCB.Append("Text ");

            // Can also check for specific formats
            // (See System.Windows.DataFormats for full list)
            if (Clipboard.ContainsData(DataFormats.CommaSeparatedValue))
                sbCB.Append("CommaSeparatedValue ");

            if (Clipboard.ContainsData(DataFormats.EnhancedMetafile))
                sbCB.Append("EnhancedMetafile ");

            lblInfo.Content = "Clipboard contains: " + sbCB.ToString();
        }

720-001
720-002