C# winform加载网页,调用网页中js方法并保存图片

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


前言

winform中嵌入html页面,并调用前台页面的js方法


一、将html页面嵌入到winform项目中

1.从工具栏拖拽一个webBrowser控件到需要位置;

2.在FormLoad方法中初始化网页地址;

private void UC_History_Load(object sender, EventArgs e)
        {
            try
            {
                webBrowser1.Size = new Size(800, 700);
                webBrowser1.Location = new Point(30, 100);

                string currPath = System.AppDomain.CurrentDomain.BaseDirectory;
                string demoPath = currPath + "Demo\\index.html";
                string boardUrl = demoPath;
                webBrowser1.Navigate(boardUrl);
                webBrowser1.Refresh();

            }
            catch (Exception ex)
            {

            }
        }

二、调用html js方法

1.这里是可以传多个参数的

webBrowser1.Document.InvokeScript("initLine", new object[] {1,2,3});

2.js方法

function initLine(a,b,c)
{
	....
}

三、将html保存成图片

1.写一个保存方法(之前在别的地方看到说控件保存时好时坏,所以用这个);

				//调用
				private void  BtnClick(object sender, EventArgs e)
				{
					Bitmap myPic = WriteBmp();
				}
        
			
        [DllImport("user32.dll")]
        private static extern bool PrintWindow(IntPtr hwnd, IntPtr hdcBlt, uint nFlags);

        public Bitmap WriteBmp()
        {
            IntPtr myIntptr = webBrowser1.Handle;
            int hwndInt = myIntptr.ToInt32();
            IntPtr hwnd = myIntptr;

            // Set hdc to the bitmap
            Rectangle myRec = new Rectangle(0, 0, 800, 620);
            Bitmap bm = new Bitmap(800, 620);
            Graphics g = Graphics.FromImage(bm);
            IntPtr hdc = g.GetHdc();

            // Snapshot the WebBrowser

            bool result = PrintWindow(hwnd, hdc, 0);
            g.ReleaseHdc(hdc);
            g.Flush();

            // Save the bitmap, if successful
            return bm;
            //if (result == true)
            //    bm.Save(bmpPath);
        }

总结

如果需要修改内核,则去用webkit

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值