本文整理汇总了C#中DataObject.SetData方法的典型用法代码示例。如果您正苦于以下问题:C# DataObject.SetData方法的具体用法?C# DataObject.SetData怎么用?C# DataObject.SetData使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类DataObject
的用法示例。
在下文中一共展示了DataObject.SetData方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: _CreateDataObject
internal static DataObject _CreateDataObject(TextEditor This, bool isDragDrop)
{
DataObject dataObject;
// Create the data object for drag and drop.
//
(new UIPermission(UIPermissionClipboard.AllClipboard)).Assert();//BlessedAssert
try
{
dataObject = new DataObject();
}
finally
{
UIPermission.RevertAssert();
}
// Get plain text and copy it into the data object.
string textString = This.Selection.Text;
if (textString != String.Empty)
{
// Copy plain text into data object.
// ConfirmDataFormatSetting rasies a public event - could throw recoverable exception.
if (ConfirmDataFormatSetting(This.UiScope, dataObject, DataFormats.Text))
{
CriticalSetDataWrapper(dataObject,DataFormats.Text, textString);
}
// Copy unicode text into data object.
// ConfirmDataFormatSetting rasies a public event - could throw recoverable exception.
if (ConfirmDataFormatSetting(This.UiScope, dataObject, DataFormats.UnicodeText))
{
CriticalSetDataWrapper(dataObject,DataFormats.UnicodeText, textString);
}
}
// Get the rtf and xaml text and then copy it into the data object after confirm data format.
// We do this only if our content is rich
if (This.AcceptsRichContent)
{
// This ensures that in the confines of partial trust RTF is not enabled.
// We use unmanaged code permission over clipboard permission since
// the latter is available in intranet zone and this is something that will
// fail in intranet too.
if (SecurityHelper.CheckUnmanagedCodePermission())
{
// In FullTrust we allow all rich formats on the clipboard
Stream wpfContainerMemory = null;
// null wpfContainerMemory on entry means that container is optional
// and will be not created when there is no images in the range.
// Create in-memory wpf package, and serialize the content of selection into it
string xamlTextWithImages = WpfPayload.SaveRange(This.Selection, ref wpfContainerMemory, /*useFlowDocumentAsRoot:*/false);
if (xamlTextWithImages.Length > 0)
{
// ConfirmDataFormatSetting raises a public event - could throw recoverable exception.
if (wpfContainerMemory != null && ConfirmDataFormatSetting(This.UiScope, dataObject, DataFormats.XamlPackage))
{
dataObject.SetData(DataFormats.XamlPackage, wpfContainerMemory);
}
// ConfirmDataFormatSetting raises a public event - could throw recoverable exception.
if (ConfirmDataFormatSetting(This.UiScope, dataObject, DataFormats.Rtf))
{
// Convert xaml to rtf text to set rtf data into data object.
string rtfText = ConvertXamlToRtf(xamlTextWithImages, wpfContainerMemory);
if (rtfText != String.Empty)
{
dataObject.SetData(DataFormats.Rtf, rtfText, true);
}
}
}
// Add a CF_BITMAP if we have only one image selected.
Image image = This.Selection.GetUIElementSelected() as Image;
if (image != null && image.Source is System.Windows.Media.Imaging.BitmapSource)
{
dataObject.SetImage((System.Windows.Media.Imaging.BitmapSource)image.Source);
}
}
// Xaml format is availabe both in Full Trust and in Partial Trust
// Need to re-serialize xaml to avoid image references within a container:
StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture);
XmlTextWriter xmlWriter = new XmlTextWriter(stringWriter);
TextRangeSerialization.WriteXaml(xmlWriter, This.Selection, /*useFlowDocumentAsRoot:*/false, /*wpfPayload:*/null);
string xamlText = stringWriter.ToString();
//
if (xamlText.Length > 0)
{
// ConfirmDataFormatSetting rasies a public event - could throw recoverable exception.
//.........这里部分代码省略.........
示例2: PackageSelectionDataObject
/// <summary>
/// Returns a dataobject from selected nodes
/// </summary>
/// <param name="cutHighlightItems">boolean that defines if the selected items must be cut</param>
/// <returns>data object for selected items</returns>
internal virtual DataObject PackageSelectionDataObject(bool cutHighlightItems)
{
this.CleanupSelectionDataObject(false, false, false);
StringBuilder sb = new StringBuilder();
DataObject dataObject = null;
try
{
IList<HierarchyNode> selectedNodes = this.GetSelectedNodes();
if (selectedNodes != null)
{
this.InstantiateItemsDraggedOrCutOrCopiedList();
StringBuilder selectionContent = null;
// If there is a selection package the data
if (selectedNodes.Count > 1)
{
foreach (HierarchyNode node in selectedNodes)
{
selectionContent = node.PrepareSelectedNodesForClipBoard();
if (selectionContent != null)
{
sb.Append(selectionContent);
}
}
}
else if (selectedNodes.Count == 1)
{
HierarchyNode selectedNode = selectedNodes[0];
selectionContent = selectedNode.PrepareSelectedNodesForClipBoard();
if (selectionContent != null)
{
sb.Append(selectionContent);
}
}
}
// Add the project items first.
IntPtr ptrToItems = this.PackageSelectionData(sb, false);
if (ptrToItems == IntPtr.Zero)
{
return null;
}
FORMATETC fmt = DragDropHelper.CreateFormatEtc(DragDropHelper.CF_VSSTGPROJECTITEMS);
dataObject = new DataObject();
dataObject.SetData(fmt, ptrToItems);
// Now add the project path that sourced data. We just write the project file path.
IntPtr ptrToProjectPath = this.PackageSelectionData(new StringBuilder(this.GetMkDocument()), true);
if (ptrToProjectPath != IntPtr.Zero)
{
dataObject.SetData(DragDropHelper.CreateFormatEtc(DragDropHelper.CF_VSPROJECTCLIPDESCRIPTOR), ptrToProjectPath);
}
if (cutHighlightItems)
{
bool first = true;
IVsUIHierarchyWindow w = UIHierarchyUtilities.GetUIHierarchyWindow(this.site, HierarchyNode.SolutionExplorer);
foreach (HierarchyNode node in this.ItemsDraggedOrCutOrCopied)
{
ErrorHandler.ThrowOnFailure(w.ExpandItem((IVsUIHierarchy)this, node.ID, first ? EXPANDFLAGS.EXPF_CutHighlightItem : EXPANDFLAGS.EXPF_AddCutHighlightItem));
first = false;
}
}
}
catch (COMException e)
{
Trace.WriteLine("Exception : " + e.Message);
dataObject = null;
}
return dataObject;
}
示例3: PackageSelectionDataObject
/// <summary>
/// Returns a dataobject from selected nodes
/// </summary>
/// <param name="cutHighlightItems">boolean that defines if the selected items must be cut</param>
/// <returns>data object for selected items</returns>
private DataObject PackageSelectionDataObject(bool cutHighlightItems) {
StringBuilder sb = new StringBuilder();
DataObject dataObject = null;
IList<HierarchyNode> selectedNodes = this.GetSelectedNodes();
if (selectedNodes != null) {
this.InstantiateItemsDraggedOrCutOrCopiedList();
// If there is a selection package the data
foreach (HierarchyNode node in selectedNodes) {
string selectionContent = node.PrepareSelectedNodesForClipBoard();
if (selectionContent != null) {
sb.Append(selectionContent);
}
}
}
// Add the project items first.
IntPtr ptrToItems = this.PackageSelectionData(sb, false);
if (ptrToItems == IntPtr.Zero) {
return null;
}
FORMATETC fmt = DragDropHelper.CreateFormatEtc(DragDropHelper.CF_VSSTGPROJECTITEMS);
dataObject = new DataObject();
dataObject.SetData(fmt, ptrToItems);
// Now add the project path that sourced data. We just write the project file path.
IntPtr ptrToProjectPath = this.PackageSelectionData(new StringBuilder(this.GetMkDocument()), true);
if (ptrToProjectPath != IntPtr.Zero) {
dataObject.SetData(DragDropHelper.CreateFormatEtc(DragDropHelper.CF_VSPROJECTCLIPDESCRIPTOR), ptrToProjectPath);
}
if (cutHighlightItems) {
bool first = true;
foreach (HierarchyNode node in this.ItemsDraggedOrCutOrCopied) {
node.ExpandItem(first ? EXPANDFLAGS.EXPF_CutHighlightItem : EXPANDFLAGS.EXPF_AddCutHighlightItem);
first = false;
}
}
return dataObject;
}
示例4: PasteContentData
private static bool PasteContentData(TextEditor This, IDataObject dataObject, IDataObject dataObjectToApply, string formatToApply)
{
// CF_BITMAP - pasting a single image.
if (formatToApply == DataFormats.Bitmap && dataObjectToApply is DataObject)
{
// This demand is present to explicitly disable RTF independant of any
// asserts in the confines of partial trust
// We check unmanaged code instead of all clipboard because in paste
// there is a high level assert for all clipboard in commandmanager.cs
if (This.AcceptsRichContent && This.Selection is TextSelection &&
SecurityHelper.CheckUnmanagedCodePermission())
{
System.Windows.Media.Imaging.BitmapSource bitmapSource = GetPasteData(dataObjectToApply, DataFormats.Bitmap) as System.Windows.Media.Imaging.BitmapSource;
if (bitmapSource != null)
{
// Pack the image into a WPF container
MemoryStream packagedImage = WpfPayload.SaveImage(bitmapSource, WpfPayload.ImageBmpContentType);
// Place it onto a data object
dataObjectToApply = new DataObject();
formatToApply = DataFormats.XamlPackage;
dataObjectToApply.SetData(DataFormats.XamlPackage, packagedImage);
}
}
}
if (formatToApply == DataFormats.XamlPackage)
{
// This demand is present to explicitly disable RTF independant of any
// asserts in the confines of partial trust
// We check unmanaged code instead of all clipboard because in paste
// there is a high level assert for all clipboard in commandmanager.cs
if (This.AcceptsRichContent && This.Selection is TextSelection &&
SecurityHelper.CheckUnmanagedCodePermission())
{
object pastedData = GetPasteData(dataObjectToApply, DataFormats.XamlPackage);
MemoryStream pastedMemoryStream = pastedData as MemoryStream;
if (pastedMemoryStream != null)
{
object element = WpfPayload.LoadElement(pastedMemoryStream);
if ((element is Section || element is Span) && PasteTextElement(This, (TextElement)element))
{
return true;
}
else if (element is FrameworkElement)
{
((TextSelection)This.Selection).InsertEmbeddedUIElement((FrameworkElement)element);
return true;
}
}
}
// Fall to Xaml:
dataObjectToApply = dataObject; // go back to source data object
if (dataObjectToApply.GetDataPresent(DataFormats.Xaml))
{
formatToApply = DataFormats.Xaml;
}
else if (SecurityHelper.CheckUnmanagedCodePermission() && dataObjectToApply.GetDataPresent(DataFormats.Rtf))
{
formatToApply = DataFormats.Rtf;
}
else if (dataObjectToApply.GetDataPresent(DataFormats.UnicodeText))
{
formatToApply = DataFormats.UnicodeText;
}
else if (dataObjectToApply.GetDataPresent(DataFormats.Text))
{
formatToApply = DataFormats.Text;
}
}
if (formatToApply == DataFormats.Xaml)
{
if (This.AcceptsRichContent && This.Selection is TextSelection)
{
object pastedData = GetPasteData(dataObjectToApply, DataFormats.Xaml);
if (pastedData != null && PasteXaml(This, pastedData.ToString()))
{
return true;
}
}
// Fall to Rtf:
dataObjectToApply = dataObject; // go back to source data object
if (SecurityHelper.CheckUnmanagedCodePermission() && dataObjectToApply.GetDataPresent(DataFormats.Rtf))
{
formatToApply = DataFormats.Rtf;
}
else if (dataObjectToApply.GetDataPresent(DataFormats.UnicodeText))
{
formatToApply = DataFormats.UnicodeText;
}
else if (dataObjectToApply.GetDataPresent(DataFormats.Text))
{
formatToApply = DataFormats.Text;
}
//.........这里部分代码省略.........
示例5: PackageSelectionDataObject
DataObject PackageSelectionDataObject(bool cutHighlightItems){
CleanupSelectionDataObject(false, false, false);
IVsUIHierarchyWindow w = this.projectMgr.GetIVsUIHierarchyWindow(VsConstants.Guid_SolutionExplorer);
IVsSolution solution = this.GetService(typeof(IVsSolution)) as IVsSolution;
IVsMonitorSelection ms = this.GetService(typeof(IVsMonitorSelection)) as IVsMonitorSelection;
IntPtr psel;
IVsMultiItemSelect itemSelect;
IntPtr psc;
uint vsitemid;
StringBuilder sb = new StringBuilder();
ms.GetCurrentSelection(out psel, out vsitemid, out itemSelect, out psc);
IVsHierarchy sel = (IVsHierarchy)Marshal.GetTypedObjectForIUnknown(psel, typeof(IVsHierarchy));
ISelectionContainer sc = (ISelectionContainer)Marshal.GetTypedObjectForIUnknown(psc, typeof(ISelectionContainer));
const uint GSI_fOmitHierPtrs = 0x00000001;
if ((sel != (IVsHierarchy)this) || (vsitemid == VsConstants.VSITEMID_ROOT) || (vsitemid == VsConstants.VSITEMID_NIL))
throw new InvalidOperationException();
if ((vsitemid == VsConstants.VSITEMID_SELECTION) && (itemSelect != null)){
int singleHierarchy;
uint pcItems;
itemSelect.GetSelectionInfo(out pcItems, out singleHierarchy);
if (singleHierarchy != 0) // "!BOOL" == "!= 0" ?
throw new InvalidOperationException();
this.itemsDragged = new ArrayList();
VSITEMSELECTION[] items = new VSITEMSELECTION[pcItems];
itemSelect.GetSelectedItems(GSI_fOmitHierPtrs, pcItems, items);
for (uint i = 0; i < pcItems; i++){
if (items[i].itemid == VsConstants.VSITEMID_ROOT){
this.itemsDragged.Clear();// abort
break;
}
this.itemsDragged.Add(items[i].pHier);
string projref;
solution.GetProjrefOfItem((IVsHierarchy)this, items[i].itemid, out projref);
if ((projref == null) || (projref.Length == 0)){
this.itemsDragged.Clear(); // abort
break;
}
sb.Append(projref);
sb.Append('\0'); // separated by nulls.
}
} else if (vsitemid != VsConstants.VSITEMID_ROOT){
this.itemsDragged = new ArrayList();
this.itemsDragged.Add(this.projectMgr.NodeFromItemId(vsitemid));
string projref;
solution.GetProjrefOfItem((IVsHierarchy)this, vsitemid, out projref);
sb.Append(projref);
}
if (sb.ToString() == "" || this.itemsDragged.Count == 0)
return null;
sb.Append('\0'); // double null at end.
_DROPFILES df = new _DROPFILES();
int dwSize = Marshal.SizeOf(df);
Int16 wideChar = 0;
int dwChar = Marshal.SizeOf(wideChar);
IntPtr ptr = Marshal.AllocHGlobal(dwSize + ((sb.Length + 1) * dwChar));
df.pFiles = dwSize;
df.fWide = 1;
IntPtr data = DataObject.GlobalLock(ptr);
Marshal.StructureToPtr(df, data, false);
IntPtr strData = new IntPtr((long)data + dwSize);
DataObject.CopyStringToHGlobal(sb.ToString(), strData);
DataObject.GlobalUnLock(data);
DataObject dobj = new DataObject();
FORMATETC fmt = DragDropHelper.CreateFormatEtc();
dobj.SetData(fmt, ptr);
if (cutHighlightItems){
bool first = true;
foreach (HierarchyNode node in this.itemsDragged){
w.ExpandItem((IVsUIHierarchy)this.projectMgr, node.hierarchyId, first ? EXPANDFLAGS.EXPF_CutHighlightItem : EXPANDFLAGS.EXPF_AddCutHighlightItem);
first = false;
}
}
return dobj;
}
示例6: SetDataEx
/// <summary>
/// Sets managed data to a clipboard DataObject.
/// </summary>
/// <param name="dataObject">The DataObject to set the data on.</param>
/// <param name="format">The clipboard format.</param>
/// <param name="data">The data object.</param>
/// <remarks>
/// Because the underlying data store is not storing managed objects, but
/// unmanaged ones, this function provides intelligent conversion, allowing
/// you to set unmanaged data into the COM implemented IDataObject.</remarks>
public static void SetDataEx(this IDataObject dataObject, string format, object data)
{
DataFormats.Format dataFormat = DataFormats.GetFormat(format);
// Initialize the format structure
ComTypes.FORMATETC formatETC = new ComTypes.FORMATETC();
formatETC.cfFormat = (short)dataFormat.Id;
formatETC.dwAspect = ComTypes.DVASPECT.DVASPECT_CONTENT;
formatETC.lindex = -1;
formatETC.ptd = IntPtr.Zero;
// Try to discover the TYMED from the format and data
ComTypes.TYMED tymed = GetCompatibleTymed(format, data);
// If a TYMED was found, we can use the system DataObject
// to convert our value for us.
if (tymed != ComTypes.TYMED.TYMED_NULL)
{
formatETC.tymed = tymed;
// Set data on an empty DataObject instance
DataObject conv = new DataObject();
conv.SetData(format, true, data);
// Now retrieve the data, using the COM interface.
// This will perform a managed to unmanaged conversion for us.
ComTypes.STGMEDIUM medium;
((ComTypes.IDataObject)conv).GetData(ref formatETC, out medium);
try
{
// Now set the data on our data object
((ComTypes.IDataObject)dataObject).SetData(ref formatETC, ref medium, true);
}
catch
{
// On exceptions, release the medium
ReleaseStgMedium(ref medium);
throw;
}
}
else
{
// Since we couldn't determine a TYMED, this data
// is likely custom managed data, and won't be used
// by unmanaged code, so we'll use our custom marshaling
// implemented by our COM IDataObject extensions.
ComTypes.ComDataObjectExtensions.SetManagedData((ComTypes.IDataObject)dataObject, format, data);
}
}
示例7: TextAreaMouseMove
void TextAreaMouseMove(object sender, MouseEventArgs e)
#endif
{
#if GTK
if (gotmousedown == false) {
return;
}
#endif
ShowHiddenCursor();
if (dodragdrop) {
dodragdrop = false;
return;
}
doubleclick = false;
mousepos = new Point((int)args.Event.x, (int)args.Event.y);
if (textArea.GutterMargin.DrawingPosition.Contains(mousepos.X, mousepos.Y) || textArea.FoldMargin.DrawingPosition.Contains(mousepos.X, mousepos.Y)) {
if (button == 1) {
Point realmousepos = textArea.TextView.GetLogicalPosition(0, mousepos.Y /*- textArea.TextView.DrawingPosition.Y*/);
if (realmousepos.Y < textArea.Document.TotalNumberOfLines) {
if (selectionStartPos.Y == realmousepos.Y) {
textArea.SelectionManager.SetSelection(new DefaultSelection(textArea.Document, realmousepos, new Point(textArea.Document.GetLineSegment(realmousepos.Y).Length + 1, realmousepos.Y)));
} else if (selectionStartPos.Y < realmousepos.Y && textArea.SelectionManager.HasSomethingSelected) {
textArea.SelectionManager.ExtendSelection(textArea.SelectionManager.SelectionCollection[0].EndPosition, realmousepos);
} else {
textArea.SelectionManager.ExtendSelection(textArea.Caret.Position, realmousepos);
}
textArea.Caret.Position = realmousepos;
}
}
} else if (textArea.TextView.DrawingPosition.Contains(mousepos.X, mousepos.Y)) {
if (clickedOnSelectedText) {
#if GTK
// FIXME: GTKize?
if (Math.Abs(mousedownpos.X - mousepos.X) >= 5 ||
Math.Abs(mousedownpos.Y - mousepos.Y) >= 5) {
#else
if (Math.Abs(mousedownpos.X - mousepos.X) >= SystemInformation.DragSize.Width / 2 ||
Math.Abs(mousedownpos.Y - mousepos.Y) >= SystemInformation.DragSize.Height / 2) {
#endif
clickedOnSelectedText = false;
ISelection selection = textArea.SelectionManager.GetSelectionAt(textArea.Caret.Offset);
if (selection != null) {
string text = selection.SelectedText;
if (text != null && text.Length > 0) {
#if GTK
// FIXME: GTKize
#else
DataObject dataObject = new DataObject ();
dataObject.SetData(DataFormats.UnicodeText, true, text);
dataObject.SetData(selection);
dodragdrop = true;
textArea.DoDragDrop(dataObject, DragDropEffects.All);
#endif
}
}
}
return;
}
if (button == 1) {
if (gotmousedown) {
ExtendSelectionToMouse();
}
}
}
}
void ExtendSelectionToMouse()
{
Point realmousepos = textArea.TextView.GetLogicalPosition(mousepos.X /*- textArea.TextView.DrawingPosition.X*/,
mousepos.Y /*- textArea.TextView.DrawingPosition.Y*/);
Point oldPos = textArea.Caret.Position;
textArea.Caret.Position = realmousepos;
textArea.SelectionManager.ExtendSelection(oldPos, textArea.Caret.Position);
textArea.SetDesiredColumn();
}
Point selectionStartPos = new Point(-1, -1);
示例8: CopyTextToClipboard
const string LineSelectedType = "MSDEVLineSelect"; // This is the type VS 2003 and 2005 use for flagging a whole line copy
bool CopyTextToClipboard(string stringToCopy, bool asLine)
{
if (stringToCopy.Length > 0) {
DataObject dataObject = new DataObject();
dataObject.SetData(DataFormats.UnicodeText, true, stringToCopy);
if (asLine) {
MemoryStream lineSelected = new MemoryStream(1);
lineSelected.WriteByte(1);
dataObject.SetData(LineSelectedType, false, lineSelected);
}
// Default has no highlighting, therefore we don't need RTF output
if (textArea.Document.HighlightingStrategy.Name != "Default") {
dataObject.SetData(DataFormats.Rtf, RtfWriter.GenerateRtf(textArea));
}
OnCopyText(new CopyTextEventArgs(stringToCopy));
SafeSetClipboard(dataObject);
return true;
} else {
return false;
}
}
示例9: InsertImageToRichTextBox
/// <summary>
/// 向RichTextBox中插入图片
/// </summary>
public void InsertImageToRichTextBox()
{
if (OpenFileDialogForImageFile.ShowDialog() == WinForms.DialogResult.OK)
{
string FileName = OpenFileDialogForImageFile.FileName;
// Create an image object, in this case from a file.
System.Drawing.Image image = System.Drawing.Image.FromFile(FileName);
// 备份剪贴板的数据
IDataObject data = Clipboard.GetDataObject();
//Object clipBoardContents = null;
//获取剪贴板上的数据类型
string theFormat = string.Empty;
string[] formats = data.GetFormats(false);
Dictionary<string, object> datas = new Dictionary<string, object>();
//备份数据
foreach (string format in formats)
{
object datavalue = data.GetData(format);
if (datavalue != null)
{
datas.Add(format, datavalue);
}
}
// 将图片放置到剪贴板上
WinForms.Clipboard.SetImage(image);
// 插入到RichTextBox中
_rtf.Paste();
//将其设置为左对齐
EditingCommands.AlignLeft.Execute(null, _rtf);
// 清空剪贴板
Clipboard.Clear();
// 还原原始剪贴板数据
IDataObject newData = new DataObject();
foreach (string format in formats)
{
object o = datas[format];
newData.SetData(format, o);
}
WinForms.Clipboard.SetDataObject(newData);
}
}