Exemplo n.º 1
0
        void pictureBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                this.pictureBox1.Image = null;
                DelImage();
            }
            if (e.Control == true && e.KeyCode == Keys.V)
            {
                System.Windows.Forms.IDataObject iData    = System.Windows.Forms.Clipboard.GetDataObject();
                System.Drawing.Image             retImage = null;
                if (iData != null)
                {
                    if (iData.GetDataPresent(System.Windows.Forms.DataFormats.Bitmap))
                    {
                        retImage = (System.Drawing.Image)iData.GetData(System.Windows.Forms.DataFormats.Bitmap);
                    }
                    else if (iData.GetDataPresent(System.Windows.Forms.DataFormats.Dib))
                    {
                        retImage = (System.Drawing.Image)iData.GetData(System.Windows.Forms.DataFormats.Dib);
                    }
                }

                if (retImage != null)
                {
                    AddImage(retImage);
                }
            }
        }
Exemplo n.º 2
0
 //读取剪贴板
 private void btnPast_Click(object sender, EventArgs e)
 {
     System.Windows.Forms.IDataObject iData = Clipboard.GetDataObject();
     if (iData.GetDataPresent(DataFormats.Text))  //如果剪贴板中的数据是文本格式
     {
         txtSend.AppendText((string)iData.GetData(DataFormats.Text));
     }
     if (iData.GetDataPresent(DataFormats.Bitmap))  //如果剪贴板中的数据是文本格式
     {
         imgShow.Image = (Bitmap)iData.GetData(DataFormats.Bitmap);
     }
     //Clipboard.SetDataObject(, true);
     //DataFormats.Format myFormat = DataFormats.GetFormat(DataFormats.Bitmap);
 }
Exemplo n.º 3
0
            private void ClipChanged()
            {
                try
                {
                    System.Windows.Forms.IDataObject iData = Clipboard.GetDataObject();

                    ClipboardFormat?format = null;

                    foreach (var f in formats)
                    {
                        if (iData.GetDataPresent(f))
                        {
                            format = (ClipboardFormat)Enum.Parse(typeof(ClipboardFormat), f);
                            break;
                        }
                    }

                    object data = iData.GetData(format.ToString());

                    if (data == null || format == null)
                    {
                        return;
                    }

                    OnClipboardChange?.Invoke((ClipboardFormat)format, data);

                    if (data is IDisposable disposable)
                    {
                        disposable.Dispose();
                    }
                }
                catch (Exception)
                { }
            }
Exemplo n.º 4
0
        public static object GetClipboardData()
        {
            object      ret    = null;
            ThreadStart method = delegate()
            {
                System.Windows.Forms.IDataObject dataObject = Clipboard.GetDataObject();
                if (dataObject != null && dataObject.GetDataPresent(DataFormats.Text))
                {
                    ret = dataObject.GetData(DataFormats.Text);
                }
            };

            if (Thread.CurrentThread.GetApartmentState() != ApartmentState.STA)
            {
                Thread thread = new Thread(method);
                thread.SetApartmentState(ApartmentState.STA);
                thread.Start();
                thread.Join();
            }
            else
            {
                method();
            }

            return(ret);
        }
Exemplo n.º 5
0
        private void contextMenuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            switch (e.ClickedItem.Name)
            {
            case "MenuItemCopy":
                this.txtSend.Copy();
                break;

            case "MenuItemPaset":
            {
                System.Windows.Forms.IDataObject data = Clipboard.GetDataObject(); //从剪贴板中获取数据
                if (data.GetDataPresent(typeof(Image)))                            //判断是否是图片类型
                {
                    MessageBox.Show(data.GetType().ToString());
                }
                //this.txtSend.Paste();
            }
            break;

            case "MenuItemCut":
                this.txtSend.Cut();
                break;

            case "MenuItemDel":
                this.txtSend.SelectedText = "";
                break;

            case "MenuItemSelAll":
                this.Focus();
                this.txtSend.SelectAll();
                break;
            }
        }
Exemplo n.º 6
0
 /// <summary>
 /// Invalidates the drag image.
 /// </summary>
 /// <param name="dataObject">The data object for which to invalidate the drag image.</param>
 /// <remarks>This call tells the drag image manager to reformat the internal
 /// cached drag image, based on the already set drag image bitmap and current drop
 /// description.</remarks>
 public static void InvalidateDragImage(IDataObject dataObject)
 {
     if (dataObject.GetDataPresent("DragWindow"))
     {
         IntPtr hwnd = GetIntPtrFromData(dataObject.GetData("DragWindow"));
         PostMessage(hwnd, WM_INVALIDATEDRAGIMAGE, IntPtr.Zero, IntPtr.Zero);
     }
 }
Exemplo n.º 7
0
 public static string GetUri(System.Windows.Forms.IDataObject _iDataObject)
 {
     if (_iDataObject.GetDataPresent("UniformResourceLocator"))
     {
         MemoryStream stream = _iDataObject.GetData("UniformResourceLocator") as MemoryStream;
         byte[]       buffer = new byte[stream.Length];
         stream.Read(buffer, 0, buffer.Length);
         return(ASCIIEncoding.UTF8.GetString(buffer, 0, buffer.Length).TrimEnd('\0'));
     }
     return(null);
 }
Exemplo n.º 8
0
        private static MemoryStream GetFileGroupDescriptor(this System.Windows.Forms.IDataObject data)
        {
            MemoryStream ms = null;

            if (data.GetDataPresent("FileGroupDescriptorW"))
            {
                ms = (MemoryStream)data.GetData("FileGroupDescriptorW", true);
            }

            return(ms);
        }
Exemplo n.º 9
0
 private void txtSend_KeyDown(object sender, KeyEventArgs e)
 {
     if (e.Control && e.KeyCode == Keys.V)
     {
         System.Windows.Forms.IDataObject iData = Clipboard.GetDataObject();
         if (iData.GetDataPresent(DataFormats.Bitmap))  //如果剪贴板中的数据是文本格式
         {
             imgShow.Image = (Bitmap)iData.GetData(DataFormats.Bitmap);
         }
     }
 }
Exemplo n.º 10
0
        private void Form1_Load(object sender, System.EventArgs e)
        {
            System.Windows.Forms.IDataObject o = System.Windows.Forms.Clipboard.GetDataObject();

            if (o.GetDataPresent(System.Windows.Forms.DataFormats.CommaSeparatedValue))
            {
                System.IO.StreamReader sr = new System.IO.StreamReader((System.IO.Stream)o.GetData(DataFormats.CommaSeparatedValue));
                string s = sr.ReadToEnd();
                sr.Close();
                label1.Text = s;
            }
        }
Exemplo n.º 11
0
        public static T GetFromClipboard()
        {
            T retrievedObj = null;

            System.Windows.Forms.IDataObject dataObj = Clipboard.GetDataObject();
            string format = typeof(T).FullName;

            if (dataObj.GetDataPresent(format))
            {
                retrievedObj = dataObj.GetData(format) as T;
            }
            return(retrievedObj);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Determines if the IsShowingLayered flag is set on the data object.
        /// </summary>
        /// <param name="dataObject">The data object.</param>
        /// <returns>True if the flag is set, otherwise false.</returns>
        private static bool IsShowingLayered(IDataObject dataObject)
        {
            if (dataObject.GetDataPresent(IsShowingLayeredFormat))
            {
                object data = dataObject.GetData(IsShowingLayeredFormat);
                if (data != null)
                {
                    return(GetBooleanFromData(data));
                }
            }

            return(false);
        }
Exemplo n.º 13
0
        IDragHandler IDragDropService.GetDragHandler(System.Windows.Forms.IDataObject data)
        {
            TreeListNode node = GetNode(data);

            if (node != null && !data.GetDataPresent(typeof(DragDataObject)))
            {
                XRControl[]    controls = GetTemplateControlsFromData(node);
                DragDataObject obj      = CreateDragData(controls, ZoomService.GetInstance(DesignerHost));
                data.SetData(typeof(DragDataObject), obj);
                return(new MyControlDragHandler(DesignerHost));
            }
            return(base.GetDragHandler(data));
        }
Exemplo n.º 14
0
 public bool Paste()
 {
     System.Windows.Forms.IDataObject d = System.Windows.Forms.Clipboard.GetDataObject();
     if (d.GetDataPresent(System.Windows.Forms.DataFormats.Bitmap))
     {
         System.Drawing.Image img = (System.Drawing.Image)d.GetData(System.Windows.Forms.DataFormats.Bitmap);
         if (img != null)
         {
             myImage           = img;
             mySelectionBounds = Rectangle.Empty;
             OnImageChanged();
             return(true);
         }
     }
     return(false);
 }
        private void PerformPaste()
        {
            System.Windows.Forms.IDataObject dtObj = System.Windows.Forms.Clipboard.GetDataObject();
            // get unicode text instead of text
            if (dtObj.GetDataPresent(DataFormats.UnicodeText, true))
            {
                string buffer = (string)dtObj.GetData(DataFormats.UnicodeText, true);

                StringDataToArray(buffer, out int totalRows, out int totalColumns, out string[,] values);

                if (totalRows == 0 || totalColumns == 0)
                {
                    return;
                }

                int currentSelectedRow    = dataGridView.SelectedCells[0].RowIndex;
                int currentSelectedColumn = dataGridView.SelectedCells[0].ColumnIndex;

                if (dataGridView.Rows.Count < (currentSelectedRow + totalRows))
                {
                    int rowCount = currentSelectedRow + totalRows - dataGridView.Rows.Count;

                    while (rowCount > 0)
                    {
                        AddRow(RecordPropertiesDataTable);
                        rowCount--;
                    }

                    RefreshDatasource();
                }

                for (int i = 0; i < totalRows; i++)
                {
                    int currentRow = currentSelectedRow + i;
                    for (int j = 0; j < totalColumns; j++)
                    {
                        int currentColumn = currentSelectedColumn + j;

                        if (dataGridView.Columns.Count - 1 >= currentColumn)
                        {
                            dataGridView.Rows[currentRow].Cells[currentColumn].Value = values[i, j];
                        }
                    }
                }
            }
        }
Exemplo n.º 16
0
        //截图方法
        private void StartCapture()
        {
            FrmCapture imageCapturer = new FrmCapture();

            if (imageCapturer.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                System.Windows.Forms.IDataObject iData = Clipboard.GetDataObject();
                if (iData.GetDataPresent(DataFormats.Bitmap))  //如果剪贴板中的数据是文本格式
                {
                    GifBox gif = this.chatBoxSend.InsertImage((Bitmap)iData.GetData(DataFormats.Bitmap));
                    this.chatBoxSend.Focus();
                    this.chatBoxSend.ScrollToCaret();
                    imageCapturer.Close();
                    imageCapturer = null;
                }
            }
        }
Exemplo n.º 17
0
        //protected void CopyFromClipboardShape(int inlineShapeId, WordApplication wordApplication)
        //{
        //    object missing = Type.Missing;
        //    object i = inlineShapeId + 1;
        //    var shape = wordApplication.ActiveDocument.Shapes.get_Item(ref i);
        //    shape.Select(ref missing);
        //    wordApplication.Selection.Copy();
        //    Image img = Clipboard.GetImage();
        //    /*...*/
        //}

        protected static void SaveInlineShapeToFile(int inlineShapeId, WordApplication wordApplication)
        {
            // Get the shape, select, and copy it to the clipboard
            var inlineShape = wordApplication.ActiveDocument.InlineShapes[inlineShapeId];

            inlineShape.Select();
            wordApplication.Selection.Copy();
            // var name1 = @"D:\!Work\story-data\word\Images\" + String.Format("img_{0}.png", inlineShapeId);
            // var name2 = @"D:\!Work\story-data\word\Images\" + String.Format("img_{0}.gif", inlineShapeId);
            var worker = workers[photoCounter - 1];
            var name3  = @"D:\!Work\story-data\word\Images\" + String.Format("{0} {1}.jpeg", worker.Code, worker.Name);

            // Check data is in the clipboard
            if (Clipboard.GetDataObject() != null)
            {
                //var data = Clipboard.GetDataObject();

                System.Windows.Forms.IDataObject data = Clipboard.GetDataObject();
                if (data != null && data.GetDataPresent(System.Windows.Forms.DataFormats.Bitmap))
                {
                    Image image = (Image)data.GetData(System.Windows.Forms.DataFormats.Bitmap, true);
                    if (image != null)
                    {
                        //            image.Save(name2, System.Drawing.Imaging.ImageFormat.Gif);
                        image.Save(name3, System.Drawing.Imaging.ImageFormat.Jpeg);
                        photoCounter++;
                        if (photoCounter % 100 == 0)
                        {
                            Console.WriteLine("construct images: " + photoCounter + " \\ " + workers.Count);
                        }
                    }
                    else
                    {
                        //Console.WriteLine("image is null :(");
                    }
                }
                else
                {
                    // Console.WriteLine("The Data In Clipboard is not as image format");
                }
            }
        }
Exemplo n.º 18
0
        private void dlgSpecifyPaste_Load(object sender, EventArgs e)
        {
            IntPtr hwnd = DCSoft.WinForms.Native.User32.GetClipboardOwner();

            if (hwnd != IntPtr.Zero)
            {
                DCSoft.WinForms.Native.WindowInformation info = new WinForms.Native.WindowInformation(hwnd);
                if (info.Handle != IntPtr.Zero)
                {
                    lblSource.Text = lblSource.Text + info.Text;
                }
            }
            if (_DataObject == null)
            {
                _DataObject = System.Windows.Forms.Clipboard.GetDataObject();
            }

            foreach (string name in DocumentControler.SupportDataFormats)
            {
                if (_DataObject.GetDataPresent(name))
                {
                    if (this.Document != null)
                    {
                        if (this.Document.DocumentControler.CanInsertObject(
                                -1,
                                _DataObject,
                                name,
                                DomAccessFlags.Normal) == false)
                        {
                            continue;
                        }
                    }
                    lstFormat.Items.Add(name);
                }
            }
            lstFormat.Text = this.ResultFormat;
            if (lstFormat.SelectedIndex < 0 && lstFormat.Items.Count > 0)
            {
                lstFormat.SelectedIndex = 0;
            }
        }
Exemplo n.º 19
0
        private Bitmap[] Scan4Word(string filePath)
        {
            //复制目标文件,后续将操作副本
            string tmpFilePath = AppDomain.CurrentDomain.BaseDirectory + "\\" + Path.GetFileName(filePath) + ".tmp";

            File.Copy(filePath, tmpFilePath);

            List <Bitmap> bmList = new List <Bitmap>();

            MSWord.ApplicationClass wordApplicationClass = new MSWord.ApplicationClass();
            wordApplicationClass.Visible = false;
            object missing = System.Reflection.Missing.Value;

            try
            {
                object readOnly       = false;
                object filePathObject = tmpFilePath;

                MSWord.Document document = wordApplicationClass.Documents.Open(ref filePathObject, ref missing,
                                                                               ref readOnly, ref missing, ref missing, ref missing,
                                                                               ref missing, ref missing, ref missing, ref missing,
                                                                               ref missing, ref missing, ref missing, ref missing,
                                                                               ref missing, ref missing);

                bool finished = false;
                while (!finished)
                {
                    document.Content.CopyAsPicture(); //拷贝到粘贴板
                    System.Windows.Forms.IDataObject data = Clipboard.GetDataObject();
                    if (data.GetDataPresent(DataFormats.MetafilePict))
                    {
                        object   obj      = data.GetData(DataFormats.MetafilePict);
                        Metafile metafile = MetafileHelper.GetEnhMetafileOnClipboard(IntPtr.Zero); //从粘贴板获取数据
                        Bitmap   bm       = new Bitmap(metafile.Width, metafile.Height);
                        using (Graphics g = Graphics.FromImage(bm))
                        {
                            g.Clear(Color.White);
                            g.DrawImage(metafile, 0, 0, bm.Width, bm.Height);
                        }
                        bmList.Add(bm);
                        Clipboard.Clear();
                    }

                    object What       = MSWord.WdGoToItem.wdGoToPage;
                    object Which      = MSWord.WdGoToDirection.wdGoToFirst;
                    object startIndex = "1";
                    document.ActiveWindow.Selection.GoTo(ref What, ref Which, ref missing, ref startIndex); // 转到下一页
                    MSWord.Range start = document.ActiveWindow.Selection.Paragraphs[1].Range;
                    MSWord.Range end   = start.GoToNext(MSWord.WdGoToItem.wdGoToPage);
                    finished = (start.Start == end.Start);
                    if (finished) //最后一页
                    {
                        end.Start = document.Content.End;
                    }

                    object oStart = start.Start;
                    object oEnd   = end.Start;
                    document.Range(ref oStart, ref oEnd).Delete(ref missing, ref missing); //处理完一页,就删除一页。
                }

                ((MSWord._Document)document).Close(ref missing, ref missing, ref missing);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(document);

                return(bmList.ToArray());
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                wordApplicationClass.Quit(ref missing, ref missing, ref missing);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApplicationClass);
                File.Delete(tmpFilePath); //删除临时文件
            }
        }
Exemplo n.º 20
0
        private void btnCreateIssue_Click(object sender, RibbonControlEventArgs e)
        {
            application = Globals.ThisAddIn.Application;

            Word.Selection selection     = application.Selection;
            string         selectionText = selection.Text; // TODO: we may need to clean things up, or iterate through each line as an issue?

            if (String.IsNullOrWhiteSpace(selectionText))
            {
                MessageBox.Show("Text is required to create an issue.");
                return;
            }

            selectionText = System.Text.RegularExpressions.Regex.Replace(selectionText, @"\t|\n|\r", "");
            while (selectionText.EndsWith("/"))
            {
                selectionText = selectionText.Remove(selectionText.Length - 1);
            }

            InlineShapes inlineShapes = selection.InlineShapes;

            List <System.Drawing.Image> images = new List <System.Drawing.Image>();

            foreach (InlineShape inlineShape in inlineShapes)
            {
                inlineShape.Select(); // TODO: this resets the selection, which prevents multiple image uploads.
                selection.Copy();
                if (System.Windows.Forms.Clipboard.GetDataObject() != null)
                {
                    System.Windows.Forms.IDataObject data = System.Windows.Forms.Clipboard.GetDataObject();

                    if (data.GetDataPresent(System.Windows.Forms.DataFormats.Bitmap))
                    {
                        System.Drawing.Image image = (System.Drawing.Image)data.GetData(System.Windows.Forms.DataFormats.Bitmap, true);
                        images.Add(image);
                    }
                    else
                    {
                        System.Windows.Forms.MessageBox.Show("The Data In Clipboard is not as image format");
                    }
                }
                else
                {
                    // MessageBox.Show("The Clipboard was empty");
                }
            }

            // get currently selected project id
            int projectId = api.Projects.Find(x => x.Name == drpDwnProjects.SelectedItem.Label).Id;

            var createdIssue = api.CreateIssue(selectionText, api.HubId, projectId);

            foreach (System.Drawing.Image image in images)
            {
                api.CreateViewpoint(api.HubId, projectId, createdIssue.Id, image);
                image.Dispose();
            }


            // https://[hubName].bimtrackapp.co/Projects/{projectId}/Issues/{issueNumber}
            // Convert selected text to link to newly created issue.
            //  TODO: link creation is broken since I added the image.
            Object hyperlink = $"https://{api.HubName}.bimtrackapp.co/Projects/" + createdIssue.ProjectId + "/Issues/" + createdIssue.Number;
            Object oRange    = selection.Range;

            selection.Hyperlinks.Add(oRange, ref hyperlink);
        }
Exemplo n.º 21
0
        /// <summary>
        /// </summary>
        ///<param name="parLableName">域标签</param>
        /// <param name="parFillName">写入域中的内容</param>
        ///
        //打开word,将对应数据写入word里对应书签域
        public Bitmap[] WordtoImage(string filePath)
        {
            string tmpPath = AppDomain.CurrentDomain.BaseDirectory + "\\" + Path.GetFileName(filePath) + ".tmp";

            File.Copy(filePath, tmpPath);

            List <Bitmap> imageLst = new List <Bitmap>();

            Microsoft.Office.Interop.Word.Application wordApplicationClass = new Microsoft.Office.Interop.Word.Application();
            wordApplicationClass.Visible = false;
            object missing = System.Reflection.Missing.Value;

            try
            {
                object filePathObject = tmpPath;

                Document document = wordApplicationClass.Documents.Open(ref filePathObject, ref missing,
                                                                        false, ref missing, ref missing, ref missing,
                                                                        ref missing, ref missing, ref missing, ref missing,
                                                                        ref missing, ref missing, ref missing, ref missing,
                                                                        ref missing, ref missing);

                bool finished = false;
                while (!finished)
                {
                    document.Content.CopyAsPicture();
                    System.Windows.Forms.IDataObject data = Clipboard.GetDataObject();
                    if (data.GetDataPresent(DataFormats.MetafilePict))
                    {
                        object   obj      = data.GetData(DataFormats.MetafilePict);
                        Metafile metafile = MetafileHelper.GetEnhMetafileOnClipboard(IntPtr.Zero);
                        Bitmap   bm       = new Bitmap(metafile.Width, metafile.Height);
                        using (Graphics g = Graphics.FromImage(bm))
                        {
                            g.Clear(Color.White);
                            g.DrawImage(metafile, 0, 0, bm.Width, bm.Height);
                        }
                        imageLst.Add(bm);
                        Clipboard.Clear();
                    }

                    object Next       = WdGoToItem.wdGoToPage;
                    object First      = WdGoToDirection.wdGoToFirst;
                    object startIndex = "1";
                    document.ActiveWindow.Selection.GoTo(ref Next, ref First, ref missing, ref startIndex);
                    Range start = document.ActiveWindow.Selection.Paragraphs[1].Range;
                    Range end   = start.GoToNext(WdGoToItem.wdGoToPage);
                    finished = (start.Start == end.Start);
                    if (finished)
                    {
                        end.Start = document.Content.End;
                    }

                    object oStart = start.Start;
                    object oEnd   = end.Start;
                    document.Range(ref oStart, ref oEnd).Delete(ref missing, ref missing);
                }

                ((_Document)document).Close(ref missing, ref missing, ref missing);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(document);

                return(imageLst.ToArray());
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                wordApplicationClass.Quit(ref missing, ref missing, ref missing);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApplicationClass);
                File.Delete(tmpPath);
            }
        }
Exemplo n.º 22
0
		/// <summary>
		/// Invalidates the drag image.
		/// </summary>
		/// <param name="dataObject">The data object for which to invalidate the drag image.</param>
		/// <remarks>This call tells the drag image manager to reformat the internal
		/// cached drag image, based on the already set drag image bitmap and current drop
		/// description.</remarks>
		public static void InvalidateDragImage(IDataObject dataObject) {
			if (dataObject.GetDataPresent("DragWindow")) {
				IntPtr hwnd = GetIntPtrFromData(dataObject.GetData("DragWindow"));
				PostMessage(hwnd, WM_INVALIDATEDRAGIMAGE, IntPtr.Zero, IntPtr.Zero);
			}
		}
Exemplo n.º 23
0
 protected internal override DragDropEffects OnDragOver(DragDropEffects allowedEffect, int keyState,
                                                        IDataObject data)
 {
     return(((allowedEffect & DragDropEffects.Copy) == DragDropEffects.Copy &&
             data.GetDataPresent(DataFormats.FileDrop)) ? DragDropEffects.Copy : DragDropEffects.None);
 }
Exemplo n.º 24
0
		/// <summary>
		/// Determines if the IsShowingLayered flag is set on the data object.
		/// </summary>
		/// <param name="dataObject">The data object.</param>
		/// <returns>True if the flag is set, otherwise false.</returns>
		private static bool IsShowingLayered(IDataObject dataObject) {
			if (dataObject.GetDataPresent(IsShowingLayeredFormat)) {
				object data = dataObject.GetData(IsShowingLayeredFormat);
				if (data != null)
					return GetBooleanFromData(data);
			}

			return false;
		}
    public String get_image()
    {
        var random_base_name = get_formatted_date();
        //var random_base_name = DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString() +"_"+ rnd.Next().ToString();
        var file_name       = $@"{OS.GetUserDataDir()}\images\{current_project_name}\{random_base_name}.png";
        var file_name_linux = $@"{OS.GetUserDataDir()}/images/{current_project_name}/{random_base_name}.png";

        //var file_name_linux = $@"/home/dream/{random_base_name}.png";

        //if (Clipboard.ContainsImage())
        //{
        //	GD.Print("Found image in clipboard");
        //	System.Drawing.Image clip_image = Clipboard.GetImage();
        //	clip_image.Save(
        //		file_name, System.Drawing.Imaging.ImageFormat.Png);

        //	return file_name;
        //	//var width = clip_image.Width;
        //	//var height = clip_image.Height;
        //	//var new_image = new Image();
        //	//new_image.CreateFromData(width, height,true, Image.Format.BptcRgba, clip_image);

        //}
        if (OperatingSystem.IsWindows())
        {
            if (Clipboard.ContainsImage())
            {
                //GD.Print("Clipboard contains image.");

                // ImageUIElement.Source = Clipboard.GetImage(); // does not work
                System.Windows.Forms.IDataObject clipboardData = System.Windows.Forms.Clipboard.GetDataObject();
                if (clipboardData != null)
                {
                    //GD.Print("Clipboard data retrieved.");

                    if (clipboardData.GetDataPresent(System.Windows.Forms.DataFormats.Bitmap))
                    {
                        //GD.Print("Clipboard data has bitmap.");

                        System.Drawing.Bitmap bitmap = (System.Drawing.Bitmap)clipboardData.GetData(System.Windows.Forms.DataFormats.Bitmap);
                        //GD.Print("Cast to bitmap.");
                        //GD.Print("Attempt to save to " + file_name);

                        bitmap.Save(file_name, ImageFormat.Png);
                        //ImageUIElement.Source = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(bitmap.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
                        //Console.WriteLine("Clipboard copied to UIElement");
                        return(file_name);
                    }
                }
            }
        }
        else if (OperatingSystem.IsLinux())
        {
            GD.Print("Linux detected from Mono.");
            var result = $"xclip -selection clipboard -t TARGETS -o | grep -q 'image' && xclip -selection clipboard -t image/png -o > {file_name_linux} &&  echo 'saved' || echo 'not matched'".Bash();
            GD.Print("Result of shell: " + result.ToString());
            if (result.Contains("saved"))
            {
                return(file_name_linux);
            }
        }
        //GD.Print("No Image Found in Clipboard.");
        return(null);
    }
Exemplo n.º 26
0
 /// <summary>
 /// Determines whether data stored in this instance is associated with, or can be converted to, the specified format.
 /// </summary>
 /// <param name="format">A <see cref="T:System.Type"></see> representing the format for which to check. See <see cref="T:System.Windows.Forms.DataFormats"></see> for predefined formats.</param>
 /// <returns>
 /// true if data stored in this instance is associated with, or can be converted to, the specified format; otherwise, false.
 /// </returns>
 public bool GetDataPresent(Type format)
 {
     return(_underlyingDataObject.GetDataPresent(format));
 }