Clipboard Class
Definition
Provides methods to place data on and retrieve data from the system Clipboard. This class cannot be inherited.
Examples
The following code example uses Clipboard methods to place data on and retrieve it from the system Clipboard. This code assumes button1 , button2 , textBox1 , and textBox2 have been created and placed on the form.
The button1_Click method calls SetDataObject to take selected text from the text box and place it on the system Clipboard.
The button2_Click method calls GetDataObject to retrieve data from the system Clipboard. The code uses IDataObject and DataFormats to extract the data returned and displays the data in textBox2 .
Remarks
For a list of predefined formats to use with the Clipboard class, see the DataFormats class.
Call SetDataObject to put data on the Clipboard, replacing its current contents. To place a persistent copy of the data on the Clipboard, set the copy parameter to true .
To place data on the Clipboard in multiple formats, use the DataObject class or an IDataObject implementation. Place data on the Clipboard in multiple formats to maximize the possibility that a target application, whose format requirements you might not know, can successfully retrieve the data.
Call GetDataObject to retrieve data from the Clipboard. The data is returned as an object that implements the IDataObject interface. Use the methods specified by IDataObject and fields in DataFormats to extract the data from the object. If you do not know the format of the data you retrieved, call the GetFormats method of the IDataObject interface to get a list of all formats that data is stored in. Then call the GetData method of the IDataObject interface, and specify a format that your application can use.
In .NET Framework 2.0, the Clipboard class provides additional methods that make it easier to work with the system Clipboard. Call the Clear method to remove all data from the Clipboard. To add data of a particular format to the Clipboard, replacing the existing data, call the appropriate Set Format method, such as SetText, or call the SetData method to specify the format. To retrieve data of a particular format from the Clipboard, first call the appropriate Contains Format method (such as ContainsText) method to determine whether the Clipboard contains data in that format, and then call the appropriate Get Format method (such as GetText) to retrieve the data if the Clipboard contains it. To specify the format in these operations, call the ContainsData and GetData methods instead.
All Windows-based applications share the system Clipboard, so the contents are subject to change when you switch to another application.
An object must be serializable for it to be put on the Clipboard. If you pass a non-serializable object to a Clipboard method, the method will fail without throwing an exception. See System.Runtime.Serialization for more information on serialization. If your target application requires a very specific data format, the headers added to the data in the serialization process may prevent the application from recognizing your data. To preserve your data format, add your data as a Byte array to a MemoryStream and pass the MemoryStream to the SetData method.
The Clipboard class can only be used in threads set to single thread apartment (STA) mode. To use this class, ensure that your Main method is marked with the STAThreadAttribute attribute.
Special considerations may be necessary when using the metafile format with the Clipboard. Due to a limitation in the current implementation of the DataObject class, the metafile format used by the .NET Framework may not be recognized by applications that use an older metafile format. In this case, you must interoperate with the Win32 Clipboard application programming interfaces (APIs).
Methods
Removes all data from the Clipboard.
Indicates whether there is data on the Clipboard in the WaveAudio format.
Indicates whether there is data on the Clipboard that is in the specified format or can be converted to that format.
Indicates whether there is data on the Clipboard that is in the FileDrop format or can be converted to that format.
Indicates whether there is data on the Clipboard that is in the Bitmap format or can be converted to that format.
Indicates whether there is data on the Clipboard in the Text or UnicodeText format, depending on the operating system.
Indicates whether there is text data on the Clipboard in the format indicated by the specified TextDataFormat value.
Retrieves an audio stream from the Clipboard.
Retrieves data from the Clipboard in the specified format.
Retrieves the data that is currently on the system Clipboard.
Retrieves a collection of file names from the Clipboard.
Retrieves an image from the Clipboard.
Retrieves text data from the Clipboard in the Text or UnicodeText format, depending on the operating system.
Retrieves text data from the Clipboard in the format indicated by the specified TextDataFormat value.
Clears the Clipboard and then adds a Byte array in the WaveAudio format after converting it to a Stream.
Clears the Clipboard and then adds a Stream in the WaveAudio format.
Clears the Clipboard and then adds data in the specified format.
Clears the Clipboard and then places nonpersistent data on it.
Clears the Clipboard and then places data on it and specifies whether the data should remain after the application exits.
Clears the Clipboard and then attempts to place data on it the specified number of times and with the specified delay between attempts, optionally leaving the data on the Clipboard after the application exits.
Clears the Clipboard and then adds a collection of file names in the FileDrop format.
Clears the Clipboard and then adds an Image in the Bitmap format.
Clears the Clipboard and then adds text data in the Text or UnicodeText format, depending on the operating system.
Clears the Clipboard and then adds text data in the format indicated by the specified TextDataFormat value.
Clipboard Класс
Определение
Предоставляет методы для помещения данных в системный буфер обмена и извлечения данных из системного буфера обмена. Provides methods to place data on and retrieve data from the system Clipboard. Этот класс не наследуется. This class cannot be inherited.
Примеры
В следующем примере кода используются Clipboard методы для размещения и извлечения данных из системного буфера обмена. The following code example uses Clipboard methods to place data on and retrieve it from the system Clipboard. В этом коде предполагается button1 , button2 , textBox1 , и textBox2 они были созданы и помещены в форму. This code assumes button1 , button2 , textBox1 , and textBox2 have been created and placed on the form.
button1_Click Метод вызывает SetDataObject , чтобы взять выбранный текст из текстового поля и поместить его в буфер обмена системы. The button1_Click method calls SetDataObject to take selected text from the text box and place it on the system Clipboard.
button2_Click Метод вызывает GetDataObject для получения данных из системного буфера обмена. The button2_Click method calls GetDataObject to retrieve data from the system Clipboard. Код использует IDataObject и DataFormats для извлечения возвращаемых данных и отображает их в textBox2 . The code uses IDataObject and DataFormats to extract the data returned and displays the data in textBox2 .
Комментарии
Список стандартных форматов, используемых с Clipboard классом, см. в разделе DataFormats класс. For a list of predefined formats to use with the Clipboard class, see the DataFormats class.
Вызовите SetDataObject , чтобы разместить данные в буфере обмена, заменив его текущее содержимое. Call SetDataObject to put data on the Clipboard, replacing its current contents. Чтобы поместить постоянную копию данных в буфер обмена, присвойте copy параметру значение true . To place a persistent copy of the data on the Clipboard, set the copy parameter to true .
Чтобы поместить данные в буфер обмена в нескольких форматах, используйте DataObject класс или IDataObject реализацию. To place data on the Clipboard in multiple formats, use the DataObject class or an IDataObject implementation. Разместите данные в буфере обмена в нескольких форматах, чтобы максимально увеличить вероятность того, что целевое приложение, требования к формату которого могут быть незнакомы, может успешно получить данные. Place data on the Clipboard in multiple formats to maximize the possibility that a target application, whose format requirements you might not know, can successfully retrieve the data.
Вызовите метод GetDataObject , чтобы получить данные из буфера обмена. Call GetDataObject to retrieve data from the Clipboard. Данные возвращаются в виде объекта, реализующего IDataObject интерфейс. The data is returned as an object that implements the IDataObject interface. Используйте методы, заданные IDataObject полями и в, DataFormats для извлечения данных из объекта. Use the methods specified by IDataObject and fields in DataFormats to extract the data from the object. Если вы не знакомы с форматом полученных данных, вызовите GetFormats метод IDataObject интерфейса, чтобы получить список всех форматов, в которых хранятся данные. If you do not know the format of the data you retrieved, call the GetFormats method of the IDataObject interface to get a list of all formats that data is stored in. Затем вызовите GetData метод IDataObject интерфейса и укажите формат, который может использоваться приложением. Then call the GetData method of the IDataObject interface, and specify a format that your application can use.
В платформа .NET Framework 2,0 Clipboard класс предоставляет дополнительные методы, упрощающие работу с системным буфером обмена. In .NET Framework 2.0, the Clipboard class provides additional methods that make it easier to work with the system Clipboard. Вызовите Clear метод, чтобы удалить все данные из буфера обмена. Call the Clear method to remove all data from the Clipboard. Чтобы добавить данные определенного формата в буфер обмена, заменив существующие данные, вызовите соответствующий Set метод Format , например SetText , или вызовите SetData метод, чтобы указать формат. To add data of a particular format to the Clipboard, replacing the existing data, call the appropriate Set Format method, such as SetText, or call the SetData method to specify the format. Чтобы получить данные определенного формата из буфера обмена, сначала вызовите соответствующий метод Contains Format (например,), ContainsText чтобы определить, содержит ли буфер обмена данные в этом формате, а затем вызовите соответствующий метод Get Format (например, GetText ), чтобы получить данные, если буфер обмена содержит его. To retrieve data of a particular format from the Clipboard, first call the appropriate Contains Format method (such as ContainsText) method to determine whether the Clipboard contains data in that format, and then call the appropriate Get Format method (such as GetText) to retrieve the data if the Clipboard contains it. Чтобы указать формат в этих операциях, вызовите ContainsData GetData вместо них методы и. To specify the format in these operations, call the ContainsData and GetData methods instead.
Все приложения на основе Windows совместно используют системный буфер обмена, поэтому содержимое может измениться при переключении на другое приложение. All Windows-based applications share the system Clipboard, so the contents are subject to change when you switch to another application.
Объект должен быть сериализуемым, чтобы его можно было разместить в буфере обмена. An object must be serializable for it to be put on the Clipboard. Если передать несериализуемый объект в метод буфера обмена, метод завершится с ошибкой, не вызывая исключение. If you pass a non-serializable object to a Clipboard method, the method will fail without throwing an exception. System.Runtime.SerializationДополнительные сведения о сериализации см. в разделе. See System.Runtime.Serialization for more information on serialization. Если целевому приложению требуется специальный формат данных, то заголовки, добавленные к данным в процессе сериализации, могут помешать приложению распознать ваши данные. If your target application requires a very specific data format, the headers added to the data in the serialization process may prevent the application from recognizing your data. Чтобы сохранить формат данных, добавьте данные в Byte массив MemoryStream и передайте MemoryStream SetData методу. To preserve your data format, add your data as a Byte array to a MemoryStream and pass the MemoryStream to the SetData method.
ClipboardКласс может использоваться только в потоках, для которых установлен режим апартамента однопотокового подразделения (STA). The Clipboard class can only be used in threads set to single thread apartment (STA) mode. Чтобы использовать этот класс, убедитесь, что ваш Main метод помечен STAThreadAttribute атрибутом. To use this class, ensure that your Main method is marked with the STAThreadAttribute attribute.
При использовании формата метафайлов с буфером обмена могут потребоваться особые соображения. Special considerations may be necessary when using the metafile format with the Clipboard. Из-за ограничения в текущей реализации DataObject класса формат метафайла, используемый платформа .NET Framework, может не располагаться приложениями, использующими более старый формат метафайла. Due to a limitation in the current implementation of the DataObject class, the metafile format used by the .NET Framework may not be recognized by applications that use an older metafile format. В этом случае необходимо взаимодействовать с интерфейсами прикладного программирования (API) буфера Win32. In this case, you must interoperate with the Win32 Clipboard application programming interfaces (APIs).
Методы
Удаляет все данные из буфера обмена. Removes all data from the Clipboard.
Показывает, имеются ли в буфере обмена данные в формате WaveAudio. Indicates whether there is data on the Clipboard in the WaveAudio format.
Указывает, имеются ли в буфере обмена данные в указанном формате и могут ли они быть преобразованы в этот формат. Indicates whether there is data on the Clipboard that is in the specified format or can be converted to that format.
Указывает, имеются ли в буфере обмена данные в формате FileDrop и могут ли они быть преобразованы в этот формат. Indicates whether there is data on the Clipboard that is in the FileDrop format or can be converted to that format.
Указывает, имеются ли в буфере обмена данные в формате Bitmap и могут ли они быть преобразованы в этот формат. Indicates whether there is data on the Clipboard that is in the Bitmap format or can be converted to that format.
Показывает, имеются ли в буфере обмена данные в формате Text или UnicodeText в зависимости от операционной системы. Indicates whether there is data on the Clipboard in the Text or UnicodeText format, depending on the operating system.
Показывает, имеются ли в буфере обмена текстовые данные в формате, указываемом заданным значением TextDataFormat. Indicates whether there is text data on the Clipboard in the format indicated by the specified TextDataFormat value.
Получает аудиопоток из буфера обмена. Retrieves an audio stream from the Clipboard.
Извлекает данные из буфера обмена в указанном формате. Retrieves data from the Clipboard in the specified format.
Извлекает данные, которые находятся в данный момент в системном буфере обмена. Retrieves the data that is currently on the system Clipboard.
Извлекает из буфера обмена коллекцию имен файлов. Retrieves a collection of file names from the Clipboard.
Получает изображения из буфера обмена. Retrieves an image from the Clipboard.
В зависимости от операционной системы извлекает текстовые данные из буфера обмена в формате Text или UnicodeText. Retrieves text data from the Clipboard in the Text or UnicodeText format, depending on the operating system.
Извлекает текстовые данные из буфера обмена в формате, указанном заданным значением TextDataFormat. Retrieves text data from the Clipboard in the format indicated by the specified TextDataFormat value.
Очищает буфер обмена и добавляет массив Byte в формате обмена в формате WaveAudio после его преобразования в Stream. Clears the Clipboard and then adds a Byte array in the WaveAudio format after converting it to a Stream.
Очищает буфер обмена и добавляет Stream в формате WaveAudio. Clears the Clipboard and then adds a Stream in the WaveAudio format.
Очищает буфер обмена и добавляет данные в указанном формате. Clears the Clipboard and then adds data in the specified format.
Очищает буфер обмена и помещает в него несохраняемые данные. Clears the Clipboard and then places nonpersistent data on it.
Очищает буфер обмена и помещает данные в него и указывает, должны ли данные оставаться в буфере после выхода из приложения. Clears the Clipboard and then places data on it and specifies whether the data should remain after the application exits.
Очищает буфер обмена и пытается поместить данные в него указанное число раз и с заданной задержкой между попытками, оставляя при необходимости данные в буфере обмена после выхода из приложения. Clears the Clipboard and then attempts to place data on it the specified number of times and with the specified delay between attempts, optionally leaving the data on the Clipboard after the application exits.
Очищает буфер обмена и добавляет коллекцию имен файлов в формате FileDrop. Clears the Clipboard and then adds a collection of file names in the FileDrop format.
Очищает буфер обмена и добавляет Image в формате Bitmap. Clears the Clipboard and then adds an Image in the Bitmap format.
Очищает буфер обмена и добавляет и добавляет текстовые данныев формате Text или UnicodeText в зависимости от операционной системы. Clears the Clipboard and then adds text data in the Text or UnicodeText format, depending on the operating system.
Очищает буфер обмена и добавляет текстовые данные в формате, указанном заданным значением TextDataFormat. Clears the Clipboard and then adds text data in the format indicated by the specified TextDataFormat value.