private bool AcceptDragData(System.Windows.IDataObject data) { IFileContainer dropTarget = Model as IFileContainer; if (dropTarget == null) { dropTarget = Parent; } var draggedItem = data.GetData(MenuLayoutViewModel.DragDataFormat) as IFile; bool accept = draggedItem != null; if (accept) { accept = ShouldAcceptDraggedItem(draggedItem); /* * var draggedItemParent = draggedItem.Parent; * accept = (draggedItem != this.Model); * if (accept && (dropTarget != null)) * { * var draggedContainer = draggedItem as IFileContainer; * if (draggedContainer != null) * { * accept = !draggedContainer.ContainsChild(dropTarget) && (draggedContainer != dropTarget); * } * if (accept) * { * accept = (dropTarget.Size < FileSystemConstants.MaxItemCount) || (dropTarget == draggedItemParent); * } * if (accept) * { * int currentDepth = DepthFromRoot; * int draggedItemDepth = draggedItem.Depth; * if (draggedContainer != null) * { ++draggedItemDepth; // count folders as one extra layer of depth, since they are pointless w/o containing any items * } * accept = currentDepth + draggedItemDepth <= FileSystemConstants.MaximumDepth; * } * } */ } else { IEnumerable <ProgramDescription> draggedPrograms = data.GetData(ProgramDescriptionViewModel.DragDataFormat) as IEnumerable <ProgramDescription>; accept = (draggedPrograms != null) && (draggedPrograms.Any() && ((draggedPrograms.Count() + dropTarget.Size) <= FileSystemConstants.MaxItemCount)); } return(accept); }
public static List <string[]> ParseClipboardData() { List <string[]> clipboardData = null; object clipboardRawData = null; ParseFormat parseFormat = null; // get the data and set the parsing method based on the format // currently works with CSV and Text DataFormats System.Windows.IDataObject dataObj = Clipboard.GetDataObject(); if ((clipboardRawData = dataObj.GetData(DataFormats.CommaSeparatedValue)) != null) { parseFormat = ParseCsvFormat; } else if ((clipboardRawData = dataObj.GetData(DataFormats.Text)) != null) { parseFormat = ParseTextFormat; } if (parseFormat != null) { string rawDataStr = clipboardRawData as string; if (rawDataStr == null && clipboardRawData is MemoryStream) { // cannot convert to a string so try a MemoryStream MemoryStream ms = clipboardRawData as MemoryStream; StreamReader sr = new StreamReader(ms); rawDataStr = sr.ReadToEnd(); } Debug.Assert(rawDataStr != null, string.Format("clipboardRawData: {0}, could not be converted to a string or memorystream.", clipboardRawData)); string[] rows = rawDataStr.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); if (rows != null && rows.Length > 0) { clipboardData = new List <string[]>(); foreach (string row in rows) { clipboardData.Add(parseFormat(row)); } } else { Debug.WriteLine("unable to parse row data. possibly null or contains zero rows."); } } return(clipboardData); }
private void InsertAnswerImage() { //获取剪切板上的图片,如果剪切板上的图片为空,则提示 System.Windows.IDataObject clip1 = System.Windows.Clipboard.GetDataObject(); bool ifCanGetClilp = clip1.GetDataPresent(typeof(System.Drawing.Bitmap)); if (true == ifCanGetClilp) { Bitmap clipBitMap = (Bitmap)clip1.GetData(typeof(System.Drawing.Bitmap)); String imagePath = @"../../TestCases/temp.png"; clipBitMap.Save(imagePath, System.Drawing.Imaging.ImageFormat.Png); int QuestionID = 0; int.TryParse(textBox4.Text, out QuestionID); try { Question u = Question.Find(QuestionID); u.AnswerMedia_width = clipBitMap.Width; u.AnswerMedia_height = clipBitMap.Height; clipBitMap.Dispose(); FileStream fs1 = new FileStream(imagePath, FileMode.Open, FileAccess.Read); Byte[] tempFile3 = new Byte[fs1.Length]; fs1.Read(tempFile3, 0, (int)fs1.Length); u.AnswerMediaContent = tempFile3; u.UpdateAndFlush(); fs1.Close(); textBlock1.Text = "答案图片:" + u.AnswerMedia_width.ToString(); } catch { MessageBox.Show("找不到题序"); } } }
public void LoadDroppedFile(IDataObject data) { if (!data.GetDataPresent(DataFormats.FileDrop)) { return; } var filePaths = (string[])(data.GetData(DataFormats.FileDrop)); if (filePaths == null || filePaths.Length <= 0) { return; } var filePath = filePaths[0]; if (filePath == null) { return; } var ext = Path.GetExtension(filePath); ext = ext.ToLower(); if (String.Compare(ext, ".sdf", StringComparison.OrdinalIgnoreCase) != 0) { return; } dataSource = filePaths[0]; AnalyzeDatabase(); }
/// <summary> /// PasteTextToRow. /// </summary> protected override void PasteTextToRow() { System.Windows.IDataObject dataObject = null; dataObject = Clipboard.GetDataObject(); var clipBoardContent = dataObject.GetData(DataFormats.UnicodeText) as string; string[] records = Regex.Split(clipBoardContent.ToString(), @"\r\n"); if (dataGrid.SelectionUnit == GridSelectionUnit.Row) { dataGrid.Focus(); bool isAddNewRow = this.dataGrid.IsAddNewIndex(this.dataGrid.SelectionController.CurrentCellManager.CurrentRowColumnIndex.RowIndex); if (isAddNewRow) { PasteNewRow(records); } else { base.PasteTextToRow(); } } else { base.PasteTextToRow(); } }
private async void OnDropItem(IDataObject data) { var filePath = (string[])data.GetData(DataFormats.FileDrop); if (filePath != null) { var fileList = new List <string>(filePath); var fileSystemItems = await AddFileSystemItems(fileList); if (fileSystemItems != null) { if (FileList == null) { FileList = FileList.Create(); } foreach (var item in fileSystemItems) { FileList.Items.Add(item); } } } if (FileList.Items.Count == 0) { FileList = null; } }
/// <summary> /// コピーした項目を貼り付け /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void PasteItem_Execute(object sender, System.Windows.Input.ExecutedRoutedEventArgs e) { // クリップボードの文字列をItemにパースして追加 System.Windows.IDataObject data = System.Windows.Clipboard.GetDataObject(); if (data.GetDataPresent(System.Windows.DataFormats.CommaSeparatedValue)) { string str = (string)data.GetData(System.Windows.DataFormats.CommaSeparatedValue); mViewModel.Items.Add(ViewModel.Item.Parse(str)); } }
public static string GetTextPath() { System.Windows.IDataObject data = Clipboard.GetDataObject(); string ClipboardText = ""; if (data.GetDataPresent(DataFormats.Text)) { ClipboardText = (string)data.GetData(DataFormats.Text); // クリップボードのテキストを改行毎に配列に設定 string[] ClipBoardList = ClipboardText.Split('\n'); foreach (string file in ClipBoardList) { FileInfo fileinfo = new FileInfo(file); DirectoryInfo dirinfo = new DirectoryInfo(file); if (fileinfo.Exists || dirinfo.Exists) { ClipboardText = fileinfo.FullName; break; } } } if (data.GetDataPresent(DataFormats.FileDrop)) { foreach (string file in (string[])data.GetData(DataFormats.FileDrop)) { FileInfo fileinfo = new FileInfo(file); DirectoryInfo dirinfo = new DirectoryInfo(file); if (fileinfo.Exists || dirinfo.Exists) { ClipboardText = fileinfo.FullName; break; } } } return(ClipboardText); }
private string GetStringData() { string ret = ""; System.Windows.IDataObject iData = System.Windows.Clipboard.GetDataObject(); if (iData.GetDataPresent(System.Windows.DataFormats.Text)) { ret = (string)iData.GetData(System.Windows.DataFormats.Text); } return(ret); }
private void BasicTest() { Question u = Question.Find(3); //label1.Content = u.用户名; u = Question.Find(3); //通过剪切板进入到数据库 System.Windows.IDataObject clip1 = System.Windows.Clipboard.GetDataObject(); bool ifCanGetClilp = clip1.GetDataPresent(typeof(System.Drawing.Bitmap)); //object clipBitMap = clip1.GetData(DataFormats.Bitmap); Bitmap clipBitMap = (Bitmap)clip1.GetData(typeof(System.Drawing.Bitmap)); String imagePath = @"../../TestCases/temp.png"; //另存为临时文件 clipBitMap.Save(imagePath, System.Drawing.Imaging.ImageFormat.Png); u.Media_width = clipBitMap.Width; u.Media_height = clipBitMap.Height; clipBitMap.Dispose(); //读一个二进制文件,将该文件内容写入到DB中 FileStream fs1 = new FileStream(imagePath, FileMode.Open, FileAccess.Read); Byte[] tempFile3 = new Byte[fs1.Length]; fs1.Read(tempFile3, 0, (int)fs1.Length); u.MediaContent = tempFile3; u.AnswerText = "测试"; u.UpdateAndFlush(); fs1.Close(); u = Question.TryFind(4); if (u == null) { u = new Question(); u.QuestionID = 4; //u.用户名 = "u4"; u.CreateAndFlush(); } else { u.DeleteAndFlush(); } }
public static string GetText() { System.Windows.IDataObject data = Clipboard.GetDataObject(); string ClipboardText = ""; if (data.GetDataPresent(DataFormats.Text)) { ClipboardText = (string)data.GetData(DataFormats.Text); // クリップボードのテキストを改行毎に配列に設定 string[] ClipBoardList = ClipboardText.Split('\n'); ClipboardText = string.Join(" ", ClipBoardList); /* * foreach (string text in ClipBoardList) * { * if (text.Trim().Length > 0) * ClipboardText = text; * } */ } if (data.GetDataPresent(DataFormats.FileDrop)) { foreach (string file in (string[])data.GetData(DataFormats.FileDrop)) { FileInfo fileinfo = new FileInfo(file); DirectoryInfo dirinfo = new DirectoryInfo(file); if (fileinfo.Exists || dirinfo.Exists) { ClipboardText = fileinfo.Name; break; } } } return(ClipboardText); }
protected override void OnDrop(DragEventArgs e) { Win32Point wp; e.Effects = DragDropEffects.Copy; Point p = e.GetPosition(this); wp.x = (int)p.X; wp.y = (int)p.Y; IDropTargetHelper dropHelper = (IDropTargetHelper) new DragDropHelper(); dropHelper.Drop((ComIDataObject)e.Data, ref wp, (int)e.Effects); if (e.Data.GetDataPresent(DataFormats.FileDrop)) { string[] files = e.Data.GetData(DataFormats.FileDrop) as string[]; this.OpenImage(files[0]); } System.Windows.IDataObject data = e.Data; string[] formats = data.GetFormats(); if (formats.Contains("text/html")) { var obj = data.GetData("text/html"); string html = string.Empty; if (obj is string) { html = (string)obj; } else if (obj is MemoryStream) { MemoryStream ms = (MemoryStream)obj; byte[] buffer = new byte[ms.Length]; ms.Read(buffer, 0, (int)ms.Length); if (buffer[1] == (byte)0) // Detecting unicode { html = System.Text.Encoding.Unicode.GetString(buffer); } else { html = System.Text.Encoding.ASCII.GetString(buffer); } } // Using a regex to parse HTML, but JUST FOR THIS EXAMPLE :-) var match = new Regex(@"<img[^>]+src=""([^""]*)""").Match(html); if (match.Success) { Uri uri = new Uri(match.Groups[1].Value); SetImageFromUri(uri); } } }
/// <summary> /// Gets managed data from a clipboard DataObject. /// </summary> /// <param name="dataObject">The DataObject to obtain the data from.</param> /// <param name="format">The format for which to get the data in.</param> /// <returns>The data object instance.</returns> public static object GetDataEx(this IDataObject dataObject, string format) { // Get the data object data = dataObject.GetData(format, true); // If the data is a stream, we'll check to see if it // is stamped by us for custom marshaling if (data is Stream) { object data2 = ComDataObjectExtensions.GetManagedData((ComIDataObject)dataObject, format); if (data2 != null) { return(data2); } } return(data); }
private void getClipDataFromPC() { byte[] PCClipData = null; //PC向Phone侧发起握手,开始写 String handShakeFlag = "00000000"; byte[] data = System.Text.Encoding.Default.GetBytes(handShakeFlag); /* int ret = DR2.Server.DataManager.sendRawData(data); * if (ret == -1) * { * System.Windows.Forms.MessageBox.Show("pc与phone通信失败"); * } * * else */ { //获得pc剪贴板内容,往手机侧送 // GetDataObject检索当前剪贴板上的数据 System.Windows.IDataObject iData = System.Windows.Clipboard.GetDataObject(); // 将数据与指定的格式进行匹配,返回bool if (iData.GetDataPresent(System.Windows.DataFormats.Text)) { // GetData检索数据并指定一个格式 String clipText = (string)iData.GetData(System.Windows.DataFormats.Text); PCClipData = System.Text.Encoding.Default.GetBytes(clipText); } else { System.Windows.Forms.MessageBox.Show("剪贴板中数据不可转换为文本", "错误"); } int isSuccess = DataManager.sendRawData(PCClipData); //if(isSuccess==1) // System.Windows.Forms.MessageBox.Show("pc向手机拷贝成功"); //else // System.Windows.Forms.MessageBox.Show("pc向手机拷贝失败"); } }
private static IEnumerable <Tuple <int, string> > InnerGetNamesWithPosition(System.Windows.IDataObject target, string groupDescriptorTitle, Encoding encoding, int recordSize) { using (var inputStream = (MemoryStream)target.GetData( groupDescriptorTitle)) { int count = inputStream.ReadByte(); for (int i = 0; i < count; i++) { var buffer = new byte[recordSize]; int count1 = buffer.Length; inputStream.FillBuffer(buffer, 0, count1); var end = FileGroupDescriptorNameLocation; while (buffer[end] != 0 || buffer[end + 1] != 0) { end += 2; } var retStr = encoding.GetString(buffer, FileGroupDescriptorNameLocation, end - FileGroupDescriptorNameLocation); yield return(Tuple.Create(i, retStr)); } } }
public Stream GetStreamFromIDataObject(IDataObject dataObject) { var formats = dataObject.GetFormats(); if (!formats.Contains("FileGroupDescriptorW")) { if (!formats.Contains("FileDrop")) { return(null); } var paths = (string[])dataObject.GetData("FileDrop"); foreach (var path in paths) { var attr = File.GetAttributes(path); if (attr.HasFlag(FileAttributes.Directory)) { // To-Do continue; } return(File.OpenRead(path)); } return(null); } var fileGroupDescriptorStream = (MemoryStream)dataObject.GetData("FileGroupDescriptorW", true); var fileGroupDescriptorBytes = new byte[fileGroupDescriptorStream.Length]; fileGroupDescriptorStream.Read(fileGroupDescriptorBytes, 0, fileGroupDescriptorBytes.Length); fileGroupDescriptorStream.Close(); var fileGroupDescriptorWPointer = Marshal.AllocHGlobal(fileGroupDescriptorBytes.Length); Marshal.Copy(fileGroupDescriptorBytes, 0, fileGroupDescriptorWPointer, fileGroupDescriptorBytes.Length); var fileGroupDescriptorObject = Marshal.PtrToStructure(fileGroupDescriptorWPointer, typeof(FileGroupDescriptor)); var fileGroupDescriptor = (FileGroupDescriptor)fileGroupDescriptorObject; var fileNames = new string[fileGroupDescriptor.cItems]; var fileDescriptorPointer = (IntPtr)((int)fileGroupDescriptorWPointer + Marshal.SizeOf(fileGroupDescriptor.cItems)); for (int fileDescriptorIndex = 0; fileDescriptorIndex < fileGroupDescriptor.cItems; fileDescriptorIndex++) { var fileDescriptor = (FileDescriptor)Marshal.PtrToStructure(fileDescriptorPointer, typeof(FileDescriptor)); fileNames[fileDescriptorIndex] = fileDescriptor.cFileName; fileDescriptorPointer = (IntPtr)((int)fileDescriptorPointer + Marshal.SizeOf(fileDescriptor)); } Marshal.FreeHGlobal(fileGroupDescriptorWPointer); var comDataObject = (System.Runtime.InteropServices.ComTypes.IDataObject)dataObject; var dataFormat = DataFormats.GetDataFormat("FileContents"); for (int i = 0; i < fileGroupDescriptor.cItems; i++) { var format = new FORMATETC(); format.cfFormat = (short)dataFormat.Id; format.dwAspect = DVASPECT.DVASPECT_CONTENT; format.lindex = i; format.tymed = TYMED.TYMED_ISTREAM | TYMED.TYMED_HGLOBAL | TYMED.TYMED_ISTORAGE | TYMED.TYMED_FILE; var medium = new STGMEDIUM(); comDataObject.GetData(ref format, out medium); if (medium.tymed == TYMED.TYMED_HGLOBAL) { var handle = medium.unionmember; var pointer = GlobalLock(handle); var size = GlobalSize(handle); var bytes = new byte[size]; Marshal.Copy(pointer, bytes, 0, size); var index = 0; var serializedObjectID = new Guid("FD9EA796-3B13-4370-A679-56106BB288FB").ToByteArray(); var isSerializedObject = false; if (size > serializedObjectID.Length) { isSerializedObject = true; for (int j = 0; j < serializedObjectID.Length; j++) { if (serializedObjectID[j] != bytes[j]) { isSerializedObject = false; break; } } if (isSerializedObject) { index = serializedObjectID.Length; } } GlobalUnlock(handle); var memoryStream = new MemoryStream(bytes, index, bytes.Length - index); if (isSerializedObject) { var formatter = new BinaryFormatter(); formatter.AssemblyFormat = FormatterAssemblyStyle.Simple; var deserializedObject = formatter.Deserialize(memoryStream); } return(memoryStream); } if (medium.tymed == TYMED.TYMED_ISTREAM) { var iStream = (IStream)Marshal.GetObjectForIUnknown(medium.unionmember); Marshal.Release(medium.unionmember); var iStreamStat = new STATSTG(); iStream.Stat(out iStreamStat, 0); var iStreamSize = (int)iStreamStat.cbSize; var iStreamContent = new byte[iStreamSize]; iStream.Read(iStreamContent, iStreamContent.Length, IntPtr.Zero); Marshal.ReleaseComObject(iStream); return(new MemoryStream(iStreamContent)); } } return(null); }
public static IEnumerable <IFile> GetDroppedFiles(this System.Windows.IDataObject item, Func <string, IFile> fileFromDiskPath) { var fileNames = (item.GetData(DataFormats.FileDrop) as string[]) ?? new string[0]; return(fileNames.Length > 0 ? fileNames.Select(fileFromDiskPath) : item.GetFileDescriptorFiles()); }
private void Tag_Image_Drop(object sender, System.Windows.DragEventArgs e) { //should be a URL or a file URI //http://stackoverflow.com/questions/8442085/receiving-an-image-dragged-from-web-page-to-wpf-window System.Windows.IDataObject data = e.Data; string[] formats = data.GetFormats(); object obj = null; bool found = false; if (formats.Contains("text/html")) { obj = data.GetData("text/html"); found = true; } else if (formats.Contains("HTML Format")) { obj = data.GetData("HTML Format"); found = true; } if (found) { string html = string.Empty; if (obj is string) { html = (string)obj; } else if (obj is MemoryStream) { MemoryStream ms = (MemoryStream)obj; byte[] buffer = new byte[ms.Length]; ms.Read(buffer, 0, (int)ms.Length); if (buffer[1] == (byte)0) // Detecting unicode { html = System.Text.Encoding.Unicode.GetString(buffer); } else { html = System.Text.Encoding.ASCII.GetString(buffer); } } // Using a regex to parse HTML, but JUST FOR THIS EXAMPLE :-) var match = new Regex(@"<img[^/]src=""([^""]*)""").Match(html); if (match.Success) { Uri uri = new Uri(match.Groups[1].Value); SetImageFromUri(uri); } else { // Try look for a URL to an image, encoded (thanks google image search....) match = new Regex(@"url=(.*?)&").Match(html); //url=http%3A%2F%2Fi.imgur.com%2FK1lxb2L.jpg& if (match.Success) { Uri uri = new Uri(Uri.UnescapeDataString(match.Groups[1].Value)); SetImageFromUri(uri); } } } }
public ClipboardDataForCache(System.Windows.IDataObject data, DateTime time) { Format = data.GetData(DataFormats.Serializable); Time = time; }
private void Tag_Image_Drop(object sender, System.Windows.DragEventArgs e) { //should be a URL or a file URI //http://stackoverflow.com/questions/8442085/receiving-an-image-dragged-from-web-page-to-wpf-window System.Windows.IDataObject data = e.Data; string[] formats = data.GetFormats(); object obj = null; bool found = false; if (formats.Contains("text/html")) { obj = data.GetData("text/html"); found = true; } else if (formats.Contains("HTML Format")) { obj = data.GetData("HTML Format"); found = true; } if (found) { string html = string.Empty; if (obj is string) { html = (string)obj; //remove any whitespace, linebreaks html = html.Replace(" ", "").Replace("\r\n", ""); } else if (obj is MemoryStream) { MemoryStream ms = (MemoryStream)obj; byte[] buffer = new byte[ms.Length]; ms.Read(buffer, 0, (int)ms.Length); if (buffer[1] == (byte)0) // Detecting unicode { html = System.Text.Encoding.Unicode.GetString(buffer); } else { html = System.Text.Encoding.ASCII.GetString(buffer); } } // Using a basic regex to parse HTML var match = new Regex(@"<img[^>]*src=""([^""]*)""", RegexOptions.IgnoreCase).Match(html); if (match.Success) { Uri uri = new Uri(match.Groups[1].Value); SetImageFromUri(uri); } else { // Try look for a URL to an image, encoded (thanks google image search....) match = new Regex(@"(url|src)=[""]?(.*?)(&|"")").Match(html); //url=http%3A%2F%2Fi.imgur.com%2FK1lxb2L.jpg& if (match.Success) { bool successImg = false; int i = 0; while (i < match.Groups.Count && successImg == false) { i++; try { Uri uri = new Uri(Uri.UnescapeDataString(match.Groups[i].Value)); successImg = SetImageFromUri(uri); } catch (Exception) { //probably nothing to worry about... } } } //Samples: //< IMG width = "432" height = "432" id = "irc_mi" style = "margin-top: 0px;" onload = "typeof google==='object'&&google.aft&&google.aft(this)" alt = "Image result for Aperio Mindfield Seasons Changing" src = "https://i1.sndcdn.com/artworks-000298160676-shcuz7-t500x500.jpg" ></ A >< !--EndFragment-- ></ DIV ></ BODY ></ HTML > //<IMGclass="n3VNCb"style="margin:0px;width:585px;height:585px;"alt="Identities2(2020,File)|Discogs"src="https://img.discogs.com/wzI0NTRfX35BLMsrm-c1gFSY-qU=/fit-in/600x600/filters:strip_icc():format(jpeg):mode_rgb():quality(90)/discogs-images/R-15423379-1591302400-6122.jpeg.jpg } } }