コード例 #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);
                }
            }
        }
コード例 #2
0
ファイル: FrmChat.cs プロジェクト: xinqinglhj/CSkin.Example
 //读取剪贴板
 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);
 }
コード例 #3
0
        public string ReadMsword(string filePath)
        {
            Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();

            try
            {
                object miss = System.Reflection.Missing.Value;
                object path = filePath;
                //lbWordDocs.Items.Add(filePath);
                //rtbox.Text()
                object readOnly = false;
                Microsoft.Office.Interop.Word.Document docs = word.Documents.Open(ref path, ref miss, ref readOnly, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss);
                docs.ActiveWindow.Selection.WholeStory();
                docs.ActiveWindow.Selection.Copy();
                data = Clipboard.GetDataObject();
                //rtbox.Text = (string)(data.GetData(DataFormats.Text));
                docs.Close(ref miss, ref miss, ref miss);
                word.Quit(ref miss, ref miss, ref miss);
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(word);
            }

            //return (data.GetData(DataFormats.Text).ToString());
            return(data.GetData(DataFormats.Text).ToString());
        }
コード例 #4
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)
                { }
            }
コード例 #5
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);
        }
コード例 #6
0
        //--------------------------------------------------
        private Image m_Capture()
        {
            try
            {
                Clipboard.Clear();
                // get the next frame;
                SendMessage(mCapHwnd, WM_CAP_GET_FRAME, 0, 0);

                // copy the frame to the clipboard
                SendMessage(mCapHwnd, WM_CAP_COPY, 0, 0);

                // paste the frame into the event args image

                // get from the clipboard
                tempObj = Clipboard.GetDataObject();
                tempImg = (System.Drawing.Bitmap)tempObj.GetData(System.Windows.Forms.DataFormats.Bitmap);
                //int t1 = DateTime.Now.Millisecond;
                GC.Collect();
                //int t2 = DateTime.Now.Millisecond;
                //int t = t2 - t1;

                /*
                 * For some reason, the API is not resizing the video
                 * feed to the width and height provided when the video
                 * feed was started, so we must resize the image here
                 */
                //x.WebCamImage = tempImg.GetThumbnailImage(m_Width, m_Height, null, System.IntPtr.Zero);
            }
            catch (Exception excep)
            {
                MessageBox.Show("An error ocurred while capturing the video image. The video capture will now be terminated.\r\n\n" + excep.Message);
                Stop(); // stop the process
            }
            return(tempImg);
        }
コード例 #7
0
ファイル: ComBrowserManager.cs プロジェクト: formist/LinkMe
        protected internal override IRepositoryBrowserInfo[] OnDragDrop(DragDropEffects effect, int keyState,
                                                                        IDataObject data)
        {
            Debug.Assert(effect == DragDropEffects.Copy, "effect == DragDropEffects.Copy");

            object[] files = (object[])data.GetData(DataFormats.FileDrop);
            if (files == null)
            {
                return(null);
            }

            // The number of repositories we return may not be the same as the number of files dragged in.
            // If some of them fail to load (eg. they are not COM type libraries) still return the rest.

            ArrayList repositories = new ArrayList();

            foreach (string file in files)
            {
                try
                {
                    repositories.Add(GetTypeLibraryInfo(file));
                }
                catch (System.Exception)
                {
                }
            }

            return((IRepositoryBrowserInfo[])repositories.ToArray(typeof(IRepositoryBrowserInfo)));
        }
コード例 #8
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);
     }
 }
コード例 #9
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);
 }
コード例 #10
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);
        }
コード例 #11
0
ファイル: FrmChat.cs プロジェクト: xinqinglhj/CSkin.Example
 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);
         }
     }
 }
コード例 #12
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);
        }
コード例 #13
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);
        }
コード例 #14
0
ファイル: XPictureBox.cs プロジェクト: ywscr/CSharpWriter
 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);
 }
コード例 #15
0
        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];
                        }
                    }
                }
            }
        }
コード例 #16
0
ファイル: FrmQQChat.cs プロジェクト: xinqinglhj/CSkin.Example
        //截图方法
        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;
                }
            }
        }
コード例 #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");
                }
            }
        }
コード例 #18
0
        //キャプチャ画像をファイルに保存する
        //http://dobon.net/vb/dotnet/graphics/screencapture.html
        private void setCaptureImageIFile(string savefilePass)
        {
            //画面全体のイメージをクリップボードにコピー
            //SendKeys.SendWait("^{PRTSC}");
            //次のようにすると、アクティブなウィンドウのイメージをコピー
            SendKeys.SendWait("%{PRTSC}");
            SendKeys.SendWait("{PRTSC}");

            //クリップボードにあるデータの取得
            System.Windows.Forms.IDataObject d = System.Windows.Forms.Clipboard.GetDataObject();

            //クリップボードにデータがあったか確認
            if (d != null)
            {
                System.Drawing.Image img = (System.Drawing.Image)d.GetData(System.Windows.Forms.DataFormats.Bitmap);

                if (img != null)
                {
                    img.Save(savefilePass);
                    img.Dispose();
                }
            }
        }
コード例 #19
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);
        }
コード例 #20
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);
			}
		}
コード例 #21
0
ファイル: CProcDataObject.cs プロジェクト: sonygod/dotahit
        //Note: GetdataPresent is not reliable for IDataObject that did not originate
        //from .Net. This rtn is called if it did, but we still don't use GetdataPresent.
        private void ProcessNetDataObject(System.Windows.Forms.IDataObject NetObject)
        {
            if (!(NetObject.GetData(typeof(ArrayList)) == null))
            {
                Type   AllowedType = typeof(CShItem);
                object oCSI;
                foreach (object tempLoopVar_oCSI in NetObject.GetData(typeof(ArrayList)) as IEnumerable)
                {
                    oCSI = tempLoopVar_oCSI;
                    if (!AllowedType.Equals(oCSI.GetType()))
                    {
                        m_Draglist = new ArrayList();
                        goto endOfForLoop;
                    }
                    else
                    {
                        m_Draglist.Add(oCSI);
                    }
                }
endOfForLoop:
                1.GetHashCode();                  //nop
            }

            //Shell IDList Array is preferred to HDROP, see if we have one
            if (!(NetObject.GetData("Shell IDList Array") == null))
            {
                //Get it and also mark that we had one
                m_StreamCIDA = NetObject.GetData("Shell IDList Array") as MemoryStream;
                //has one, ASSUME that it matchs what we may have gotten from
                // ArrayList, if we had one of those
                if (m_Draglist.Count < 1)               //if we didn't have an ArrayList, have to build m_DragList
                {
                    if (!MakeDragListFromCIDA())        //Could not make it
                    {
                        return;                         //leaving m_IsValid as false
                    }
                }
            }
            //FileDrop is only used to build m_DragList if not already done
            if (m_Draglist.Count < 1)
            {
                if (!(NetObject.GetData("FileDrop") == null))
                {
                    string S;
                    foreach (string tempLoopVar_S in NetObject.GetData("FileDrop", true) as IEnumerable)
                    {
                        S = tempLoopVar_S;
                        try                         //if GetCShitem returns Nothing(it's failure marker) then catch it
                        {
                            m_Draglist.Add(ExpTreeLib.CShItem.GetCShItem(S));
                        }
                        catch (Exception ex)                         //Some problem, throw the whole thing away
                        {
                            Debug.WriteLine("CMyDataObject -- Error in creating CShItem for " + S + "\r\n" + "Error is: " + ex.ToString());
                            m_Draglist = new ArrayList();
                        }
                    }
                }
            }
            //At this point we must have a valid m_DragList
            if (m_Draglist.Count < 1)
            {
                return;                 //no list, not valid
            }

            //ensure that DataObject has a Shell IDList Array
            if (m_StreamCIDA == null)             //wouldn't be Nothing if it had one
            {
                m_StreamCIDA = MakeShellIDArray(m_Draglist);
                NetObject.SetData("Shell IDList Array", true, m_StreamCIDA);
            }
            //At this point, we have a valid DragList and have ensured that the DataObject
            // has a CIDA.
            m_IsValid = true;
            return;
        }
コード例 #22
0
ファイル: WriteIntoWord.cs プロジェクト: junbao520/DXA
        /// <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);
            }
        }
コード例 #23
0
        static string[] GetFileGroupDescriptor(System.Windows.Forms.IDataObject _data)
        {
            MemoryStream fileGroupDescriptorStream = (MemoryStream)_data.GetData("FileGroupDescriptor");

            if (fileGroupDescriptorStream != null)
            {
                IntPtr fileGroupDescriptorAPointer = IntPtr.Zero;
                try
                {
                    byte[] fileGroupDescriptorBytes = new byte[fileGroupDescriptorStream.Length];

                    fileGroupDescriptorStream.Read(fileGroupDescriptorBytes, 0, fileGroupDescriptorBytes.Length);
                    fileGroupDescriptorStream.Close();

                    fileGroupDescriptorAPointer = Marshal.AllocHGlobal(fileGroupDescriptorBytes.Length);
                    Marshal.Copy(fileGroupDescriptorBytes, 0, fileGroupDescriptorAPointer, fileGroupDescriptorBytes.Length);

                    object fileGroupDescriptorObject = Marshal.PtrToStructure(fileGroupDescriptorAPointer, typeof(NativeMethods.FILEGROUPDESCRIPTORA));
                    NativeMethods.FILEGROUPDESCRIPTORA fileGroupDescriptor = (NativeMethods.FILEGROUPDESCRIPTORA)fileGroupDescriptorObject;

                    string[] fileNames = new string[fileGroupDescriptor.cItems];

                    IntPtr fileDescriptorPointer = (IntPtr)((int)fileGroupDescriptorAPointer + Marshal.SizeOf(fileGroupDescriptor.cItems));

                    for (int fileDescriptorIndex = 0; fileDescriptorIndex < fileGroupDescriptor.cItems; fileDescriptorIndex++)
                    {
                        NativeMethods.FILEDESCRIPTORA fileDescriptor = (NativeMethods.FILEDESCRIPTORA)Marshal.PtrToStructure(fileDescriptorPointer, typeof(NativeMethods.FILEDESCRIPTORA));
                        fileNames[fileDescriptorIndex] = fileDescriptor.cFileName;

                        fileDescriptorPointer = (IntPtr)((int)fileDescriptorPointer + Marshal.SizeOf(fileDescriptor));
                    }

                    return(fileNames);
                }
                finally
                {
                    Marshal.FreeHGlobal(fileGroupDescriptorAPointer);
                }
            }

            fileGroupDescriptorStream = (MemoryStream)_data.GetData("FileGroupDescriptorW");
            if (fileGroupDescriptorStream != null)
            {
                IntPtr fileGroupDescriptorWPointer = IntPtr.Zero;
                try
                {
                    byte[] fileGroupDescriptorBytes = new byte[fileGroupDescriptorStream.Length];
                    int    length = fileGroupDescriptorStream.Read(fileGroupDescriptorBytes, 0, fileGroupDescriptorBytes.Length);
                    fileGroupDescriptorStream.Close();

                    fileGroupDescriptorWPointer = Marshal.AllocHGlobal(length);
                    Marshal.Copy(fileGroupDescriptorBytes, 0, fileGroupDescriptorWPointer, length);

                    object fileGroupDescriptorObject = Marshal.PtrToStructure(fileGroupDescriptorWPointer, typeof(NativeMethods.FILEGROUPDESCRIPTORW));
                    NativeMethods.FILEGROUPDESCRIPTORW fileGroupDescriptor = (NativeMethods.FILEGROUPDESCRIPTORW)fileGroupDescriptorObject;

                    string[] fileNames = new string[fileGroupDescriptor.cItems];

                    IntPtr fileDescriptorPointer = (IntPtr)((int)fileGroupDescriptorWPointer + Marshal.SizeOf(fileGroupDescriptor.cItems));

                    for (int fileDescriptorIndex = 0; fileDescriptorIndex < fileGroupDescriptor.cItems; fileDescriptorIndex++)
                    {
                        NativeMethods.FILEDESCRIPTORW fileDescriptor = (NativeMethods.FILEDESCRIPTORW)Marshal.PtrToStructure(fileDescriptorPointer, typeof(NativeMethods.FILEDESCRIPTORW));
                        fileNames[fileDescriptorIndex] = fileDescriptor.cFileName;

                        fileDescriptorPointer = (IntPtr)((int)fileDescriptorPointer + Marshal.SizeOf(fileDescriptor));
                    }

                    return(fileNames);
                }
                finally
                {
                    Marshal.FreeHGlobal(fileGroupDescriptorWPointer);
                }
            }

            return(null);
        }
コード例 #24
0
        /// <summary>
        /// Retrieves the data associated with the specified data format, using a Boolean to determine whether to convert the data to the format.
        /// </summary>
        /// <param name="format">The format of the data to retrieve. See <see cref="T:System.Windows.Forms.DataFormats"></see> for predefined formats.</param>
        /// <param name="autoConvert">true to convert the data to the specified format; otherwise, false.</param>
        /// <returns>
        /// The data associated with the specified format, or null.
        /// </returns>
        public object GetData(string format, bool autoConvert)
        {
            //handle the "FileGroupDescriptor" and "FileContents" format request in this class otherwise pass through to underlying IDataObject
            switch (format)
            {
            case "FileGroupDescriptor":
                //override the default handling of FileGroupDescriptor which returns a
                //MemoryStream and instead return a string array of file names
                var fileGroupDescriptorAPointer = IntPtr.Zero;
                try
                {
                    //use the underlying IDataObject to get the FileGroupDescriptor as a MemoryStream
                    var fileGroupDescriptorStream =
                        (MemoryStream)_underlyingDataObject.GetData("FileGroupDescriptor", autoConvert);

                    var fileGroupDescriptorBytes = new byte[fileGroupDescriptorStream.Length];
                    fileGroupDescriptorStream.Read(fileGroupDescriptorBytes, 0, fileGroupDescriptorBytes.Length);
                    fileGroupDescriptorStream.Close();

                    //copy the file group descriptor into unmanaged memory
                    fileGroupDescriptorAPointer = Marshal.AllocHGlobal(fileGroupDescriptorBytes.Length);
                    Marshal.Copy(fileGroupDescriptorBytes, 0, fileGroupDescriptorAPointer,
                                 fileGroupDescriptorBytes.Length);

                    //marshal the unmanaged memory to to FILEGROUPDESCRIPTORA struct
                    var fileGroupDescriptorObject = Marshal.PtrToStructure(fileGroupDescriptorAPointer,
                                                                           typeof(NativeMethods.Filegroupdescriptora));
                    var fileGroupDescriptor = (NativeMethods.Filegroupdescriptora)fileGroupDescriptorObject;

                    //create a new array to store file names in of the number of items in the file group descriptor
                    var fileNames = new string[fileGroupDescriptor.cItems];

                    //get the pointer to the first file descriptor
                    var fileDescriptorPointer =
                        (IntPtr)((int)fileGroupDescriptorAPointer + Marshal.SizeOf(fileGroupDescriptorAPointer));

                    //loop for the number of files acording to the file group descriptor
                    for (var fileDescriptorIndex = 0;
                         fileDescriptorIndex < fileGroupDescriptor.cItems;
                         fileDescriptorIndex++)
                    {
                        //marshal the pointer top the file descriptor as a FILEDESCRIPTORA struct and get the file name
                        var fileDescriptor =
                            (NativeMethods.Filedescriptora)
                            Marshal.PtrToStructure(fileDescriptorPointer, typeof(NativeMethods.Filedescriptora));
                        fileNames[fileDescriptorIndex] = fileDescriptor.cFileName;

                        //move the file descriptor pointer to the next file descriptor
                        fileDescriptorPointer =
                            (IntPtr)((int)fileDescriptorPointer + Marshal.SizeOf(fileDescriptor));
                    }

                    //return the array of filenames
                    return(fileNames);
                }
                finally
                {
                    //free unmanaged memory pointer
                    Marshal.FreeHGlobal(fileGroupDescriptorAPointer);
                }

            case "FileGroupDescriptorW":
                //override the default handling of FileGroupDescriptorW which returns a
                //MemoryStream and instead return a string array of file names
                var fileGroupDescriptorWPointer = IntPtr.Zero;
                try
                {
                    //use the underlying IDataObject to get the FileGroupDescriptorW as a MemoryStream
                    var fileGroupDescriptorStream =
                        (MemoryStream)_underlyingDataObject.GetData("FileGroupDescriptorW");
                    var fileGroupDescriptorBytes = new byte[fileGroupDescriptorStream.Length];
                    fileGroupDescriptorStream.Read(fileGroupDescriptorBytes, 0, fileGroupDescriptorBytes.Length);
                    fileGroupDescriptorStream.Close();

                    //copy the file group descriptor into unmanaged memory
                    fileGroupDescriptorWPointer = Marshal.AllocHGlobal(fileGroupDescriptorBytes.Length);
                    Marshal.Copy(fileGroupDescriptorBytes, 0, fileGroupDescriptorWPointer,
                                 fileGroupDescriptorBytes.Length);

                    //marshal the unmanaged memory to to FILEGROUPDESCRIPTORW struct
                    var fileGroupDescriptorObject = Marshal.PtrToStructure(fileGroupDescriptorWPointer,
                                                                           typeof(NativeMethods.Filegroupdescriptorw));
                    var fileGroupDescriptor = (NativeMethods.Filegroupdescriptorw)fileGroupDescriptorObject;

                    //create a new array to store file names in of the number of items in the file group descriptor
                    var fileNames = new string[fileGroupDescriptor.cItems];

                    //get the pointer to the first file descriptor
                    var fileDescriptorPointer =
                        (IntPtr)((int)fileGroupDescriptorWPointer + Marshal.SizeOf(fileGroupDescriptorWPointer));

                    //loop for the number of files acording to the file group descriptor
                    for (var fileDescriptorIndex = 0;
                         fileDescriptorIndex < fileGroupDescriptor.cItems;
                         fileDescriptorIndex++)
                    {
                        //marshal the pointer top the file descriptor as a FILEDESCRIPTORW struct and get the file name
                        var fileDescriptor =
                            (NativeMethods.Filedescriptorw)
                            Marshal.PtrToStructure(fileDescriptorPointer, typeof(NativeMethods.Filedescriptorw));
                        fileNames[fileDescriptorIndex] = fileDescriptor.cFileName;

                        //move the file descriptor pointer to the next file descriptor
                        fileDescriptorPointer =
                            (IntPtr)((int)fileDescriptorPointer + Marshal.SizeOf(fileDescriptor));
                    }

                    //return the array of filenames
                    return(fileNames);
                }
                finally
                {
                    //free unmanaged memory pointer
                    Marshal.FreeHGlobal(fileGroupDescriptorWPointer);
                }

            case "FileContents":
                //override the default handling of FileContents which returns the
                //contents of the first file as a memory stream and instead return
                //a array of MemoryStreams containing the data to each file dropped

                //get the array of filenames which lets us know how many file contents exist
                var fileContentNames = (string[])GetData("FileGroupDescriptor");

                //create a MemoryStream array to store the file contents
                var fileContents = new MemoryStream[fileContentNames.Length];

                //loop for the number of files acording to the file names
                for (var fileIndex = 0; fileIndex < fileContentNames.Length; fileIndex++)
                {
                    //get the data at the file index and store in array
                    fileContents[fileIndex] = GetData(format, fileIndex);
                }

                //return array of MemoryStreams containing file contents
                return(fileContents);
            }

            //use underlying IDataObject to handle getting of data
            return(_underlyingDataObject.GetData(format, autoConvert));
        }
コード例 #25
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); //删除临时文件
            }
        }
コード例 #26
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;
            }
        }
コード例 #27
0
    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);
    }
コード例 #28
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;
		}