如何从form1中的pictureBox1实时传递和更新实时更新?

时间:2015-05-29 11:49:06

标签: c# .net winforms

我在项目中添加了一个新表单,新表单包含在设计器webBrowser控件中。我正在做的是从html解析一些链接,然后导航到每个链接,然后截取屏幕并将我导航到webBrowser中的每个图像保存到硬盘。

最后当所有链接导航并且我在硬盘上有图像时,我用带有hScrollBar的Form1 pictureBox显示它们。 但现在反而等待它以新的形式完成,然后显示我想要在form1中的pictureBox中的硬盘上显示每个保存的图像的所有图像。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.IO;

namespace WebBrowserScreenshots.cs
{
    public partial class WebBrowserScreenshots : Form
    {

        private class MyComparer : IComparer<string>
        {
            [DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
            private static extern int StrCmpLogicalW(string x, string y);
            public int Compare(string x, string y)
            {
                return StrCmpLogicalW(x, y);
            }
        }

        List<string> newHtmls = new List<string>();
        string uri = "";
        public bool htmlloaded = false;
        int countlinks = 0;
        public int numberoflinks = 0;
        public int numberofimages = 0;
        public List<string> imageList = new List<string>();

        public WebBrowserScreenshots()
        {
            InitializeComponent();

            webBrowser1.ScrollBarsEnabled = false;
            webBrowser1.ScriptErrorsSuppressed = true;
            NavigateToSites();
        }

        string test;
        List<string> htmls;
        private void GetLinks()
        {
            htmlloaded = true;
            for (int i = 1; i < 304; i++)
            {
                if (newHtmls.Count == 1)
                    break;
                backgroundWorker1.ReportProgress(i);
                HtmlAgilityPack.HtmlWeb hw = new HtmlAgilityPack.HtmlWeb();
                HtmlAgilityPack.HtmlDocument doc = hw.Load("http://test/page" + i);
                htmls = new List<string>();
                foreach (HtmlAgilityPack.HtmlNode link in doc.DocumentNode.SelectNodes("//a[@href]"))
                {
                    string hrefValue = link.GetAttributeValue("href", string.Empty);
                    if (hrefValue.Contains("http") && hrefValue.Contains("attachment"))
                        htmls.Add(hrefValue);
                }
                if (htmls.Count > 0 && abovezero == false)
                RealTimeHtmlList();
            }
        }

        bool abovezero = false;
        private void RealTimeHtmlList()
        {
            abovezero = true;
            for (int x = 0; x < htmls.Count; x++)
            {
                test = htmls[x];
                int index = test.IndexOf("amp");
                string test1 = test.Substring(39, index - 25);
                test = test.Remove(39, index - 35);
                int index1 = test.IndexOf("amp");
                if (index1 > 0)
                    test = test.Remove(index1, 4);
                if (!newHtmls.Contains(test))
                {
                    while (true)
                    {
                        if (htmlloaded == true)
                        {
                            newHtmls.Add(test);
                            RealTimeNavigate(test);
                        }
                        else
                        {
                            break;
                        }
                    }
                }
            }
        }

        private void RealTimeNavigate(string tests)
        {

                    uri = test;
                    webBrowser1.Navigate(test);
                    htmlloaded = false;


        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            GetLinks();
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            numberoflinks = e.ProgressPercentage;
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            numberofimages = newHtmls.Count;
            htmlloaded = true;
        }

        private void NavigateToLinks()
        {
            if (countlinks != newHtmls.Count)
            {
                while (true)
                {
                    if (htmlloaded == true)
                    {
                        uri = newHtmls[countlinks];
                        webBrowser1.Navigate(newHtmls[countlinks]);
                        countlinks++;
                        htmlloaded = false;
                    }
                    else
                    {
                        break;
                    }
                }
            }
        }

        int imagescount = 0;
        public FileInfo[] filesinfo;
        public bool savedall = false;
        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (e.Url.ToString() == uri)
            {

                Bitmap bmp = new Bitmap(SaveImageFromWebBrowser(webBrowser1));
                bmp = ImageTrim.ImagesTrim(bmp);
                bmp.Save(@"e:\webbrowserimages\Image" + imagescount.ToString() + ".bmp",
                              System.Drawing.Imaging.ImageFormat.Bmp);
                bmp.Dispose();
                imagescount++;
                htmlloaded = true;
                RealTimeHtmlList();
            }
        }


        private void NavigateToSites()
        {
            backgroundWorker1.RunWorkerAsync();
        }

        [DllImport("user32.dll")]
        public static extern bool PrintWindow(IntPtr hwnd, IntPtr hdcBlt, uint nFlags);

        private Bitmap SaveImageFromWebBrowser(Control ctl)
        {
            Bitmap bmp = new Bitmap(ctl.ClientRectangle.Width, ctl.ClientRectangle.Height);
            using (Graphics graphics = Graphics.FromImage(bmp))
            {
                IntPtr hDC = graphics.GetHdc();
                try { PrintWindow(ctl.Handle, hDC, (uint)0); }
                finally { graphics.ReleaseHdc(hDC); }
            }
            return bmp;
        }


    }
}

在form1中我做了:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Runtime.InteropServices;

namespace WebBrowserScreenshots.cs
{
    public partial class Form1 : Form
    {

        private class MyComparer : IComparer<string>
        {
            [DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
            private static extern int StrCmpLogicalW(string x, string y);
            public int Compare(string x, string y)
            {
                return StrCmpLogicalW(x, y);
            }
        }


        public List<string> imageList = new List<string>();
        List<string> numbers = new List<string>();
        WebBrowserScreenshots wbss;

        public Form1()
        {
            InitializeComponent();

            pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
            this.imageList = Directory.GetFiles(@"e:\webbrowserimages\", "*.bmp").ToList();
            this.imageList.Sort(new MyComparer());

            if (this.imageList.Count > 0)
            {
                hScrollBar1.Minimum = 0;
                hScrollBar1.Value = 0;
                hScrollBar1.Maximum = this.imageList.Count - 1;
                hScrollBar1.SmallChange = 1;
                hScrollBar1.LargeChange = 1;
                pictureBox1.Image = Image.FromFile(this.imageList[0]);
            }
            else
            {
                timer1.Start();
                wbss = new WebBrowserScreenshots();
                wbss.Show();
            }

        }

        FileInfo[] myFile;
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (wbss.savedall == true)
            {
                timer1.Stop();
                hScrollBar1.Enabled = true;
                hScrollBar1.Minimum = 0;
                hScrollBar1.Value = 0;
                hScrollBar1.Maximum = wbss.imageList.Count - 1;
                hScrollBar1.SmallChange = 1;
                hScrollBar1.LargeChange = 1;
                pictureBox1.Image = Image.FromFile(wbss.imageList[0]);
            }
            else
            {
                if (wbss.htmlloaded == true)
                {
                    var directory = new DirectoryInfo(@"e:\webbrowserimages\");
                    myFile = directory.GetFiles("*.bmp");
                    if (myFile.Length > 0)
                    {
                        var myFiles = (from f in directory.GetFiles("*.bmp")
                                       orderby f.LastWriteTime descending
                                       select f).First();
                        hScrollBar1.Enabled = true;
                        hScrollBar1.Minimum = 0;
                        hScrollBar1.Value = 0;
                        hScrollBar1.Maximum = 1;
                        hScrollBar1.SmallChange = 1;
                        hScrollBar1.LargeChange = 1;
                        pictureBox1.Image = Image.FromFile(myFiles.Name);
                    }
                }

            }
        }

        private void hScrollBar1_Scroll(object sender, ScrollEventArgs e)
        {
            int index = (int)hScrollBar1.Value;
            if (pictureBox1.Image != null) pictureBox1.Image.Dispose();
            if (this.imageList.Count > 0)
            {
                pictureBox1.Image = Image.FromFile(this.imageList[index]);
                label1.Text = "Displaying image " + index + " of " + (this.imageList.Count - 1);
            }
            else
            {
                pictureBox1.Image = Image.FromFile(wbss.imageList[index]);
                label1.Text = "Displaying image " + index + " of " + (wbss.imageList.Count - 1);
            }
        }
    }
}

在form1中,我有两个选项可以完成。 如果我在新表单中使用的方式是我等待后台工作完成然后等待直到它将导航到List newHtmls中的所有链接,然后在硬盘上保存所有图像之后例如2453图像然后我在form1 pictureBox和hScrollBar中浏览它们。

或者我现在使用的第二个选项是,一旦图像以新形式保存到硬盘,我将在form1 pictureBox1中显示图像。 然后保存另一个图像,现在硬盘上有两个图像,所以现在显示最后保存的图像。等等,一旦保存图像,就将其显示在form1 pictureBox上。

只是为了展示它。因此,我将看到每个X秒图像在form1 pictureBox中发生变化。

我现在面临的问题是这部分的Form1:

if (wbss.htmlloaded == true)
                {
                    var directory = new DirectoryInfo(@"e:\webbrowserimages\");
                    myFile = directory.GetFiles("*.bmp");
                    if (myFile.Length > 0)
                    {
                        var myFiles = (from f in directory.GetFiles("*.bmp")
                                       orderby f.LastWriteTime descending
                                       select f).First();
                        hScrollBar1.Enabled = true;
                        hScrollBar1.Minimum = 0;
                        hScrollBar1.Value = 0;
                        hScrollBar1.Maximum = 1;
                        hScrollBar1.SmallChange = 1;
                        hScrollBar1.LargeChange = 1;
                        pictureBox1.Image = Image.FromFile(myFiles.Name);
                    }
                }

在线:

pictureBox1.Image = Image.FromFile(myFiles.Name);

FileNotFoundException:Image3.bmp

但在我的硬盘上我看到了Image3.bmp

我会尽量缩小一些代码,但它们都将新表单与form1连接起来。

1 个答案:

答案 0 :(得分:1)

您需要使用myFiles.FullNamemyFiles.Name只有相对于文件所在目录的路径,这不足以找到该文件。 FullName包含目录,因此它是文件的完整绝对路径。

对于gasake,请为控件命名。 Form1不是一个好名字。 pictureBox1不是一个好名字。即使是变量名也会产生误导 - myFile表示文件集合,然后myFiles表示单个文件?当您在GetFiles中有列表时,为什么还要再次拨打myFile?为什么甚至检查文件长度?为什么不做directory.GetFiles("*.bmp").OrderByDescending(i => i.LastWriteTime).Select(i => i.FullName).FirstOrDefault()