WinForm制作定时显示基金净值的桌面小工具(续)

在“ WinForm制作定时显示基金净值的桌面小工具”一文中,是利用HtmlAgilityPack解析抓取的html源代码,还有下面另一种方法,最终得到的结果是一样的:


分析http://fund.eastmoney.com/000167.html的源代码,
找到
<script type="text/javascript">
    var fundcode = '000167';
    var fundname = '广发聚优灵活配置混合';
    var fundtype = '002';
    </script>
在其中一个JS链接http://j5.dfcfw.com/js/pinzhong/pzdefault_20131218105522.js中找到
function reGetGZ(code) {
    JsLoader("http://fund.eastmoney.com/data/funddataforgznew.aspx?t=basewap&cb=jsonp&fc=" + code + "&rt=" + new Date().getTime(), "utf-8", function () {
    });
}
把里面的链接加入参数和随机数得到
http://fund.eastmoney.com/data/funddataforgznew.aspx?t=basewap&cb=jsonp&fc=000167&rt=1000000
在浏览器中输入得到:
jsonp({"fundcode":"000167","name":"广发聚优灵活配置混合","jzrq":"2014-03-06","dwjz":"1.1750","gsz":"1.1749","gszzl":"-0.01","gztime":"2014-03-07 15:00"});

这种不是标准的JSON格式,要转为标准的JSON格式,开始和结束的字符需要处理为:
[{"fundcode":"000167","name":"广发聚优灵活配置混合","jzrq":"2014-03-06","dwjz":"1.1750","gsz":"1.1749","gszzl":"-0.01","gztime":"2014-03-07 15:00"}]

这样在C#中才能利用内置的JavaScriptSerializer来序列化和反序列化

建立一个对应上面JSON的类文件:

 public class Fund
    {
        public string Fundcode { get; set; }
        public string Name { get; set; }
        public string Jzrq { get; set; }
        public double Dwjz { get; set; }
        public double Gsz { get; set; }
        public double Gszzl { get; set; }
        public string Gztime { get; set; }
    }

js的new Date().getTime()可以对应下面的C#代码:

  private long lLeft = 621355968000000000;
  //将时间变成数字
  public long GetIntFromTime(DateTime dt)
  {
       DateTime dt1 = dt.ToUniversalTime();
       long Sticks = (dt1.Ticks - lLeft) / 10000000;
       return Sticks;
  }


C#定时抓取:

CancellationTokenSource cts = new CancellationTokenSource();
        private void Do(CancellationTokenSource cts)
        {
            while (!cts.IsCancellationRequested)
            {
                long rt = GetIntFromTime(DateTime.Now);
                string url = "http://fund.eastmoney.com/data/funddataforgznew.aspx?t=basewap&cb=jsonp&fc=000167&rt=" + rt.ToString();

                string html = Utils.GetHtmlSource(url, Encoding.UTF8);
                if (!string.IsNullOrEmpty(html))
                {
                    html = html.Replace("(", "[").Replace(")", "]").Substring(5).TrimEnd(';');
                    var serializer = new JavaScriptSerializer();
                    var deserializedResult = serializer.Deserialize<List<Fund>>(html);

                    double s1 = deserializedResult[0].Gsz;
                    double s2 = deserializedResult[0].Gszzl;
                    double s3 = Math.Round(deserializedResult[0].Gszzl / deserializedResult[0].Dwjz, 2);
                    string s4 = deserializedResult[0].Gztime;
                  
                    this.SafeCall(() =>
                    {
                        lblInfo1.Text = s1 + "\r\n" + s2 + "\r\n" + s3 + "%\r\n" + s4 + "\r\n" + "update:" + DateTime.Now.ToString("HH:mm:ss");
                    });
                }

                Thread.Sleep(1000 * 60); //每隔60s查询
            }
        }


完整代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using HtmlAgilityPack;
using System.Threading.Tasks;
using System.Threading;
using System.Runtime.InteropServices;
using System.Web.Script.Serialization;//引用System.Web.Extensions

namespace AutoLogin
{
    public partial class Form8 : Form
    {
        public Form8()
        {
            InitializeComponent();
            lblInfo1.Text = "";
            this.ShowInTaskbar = false;
            this.Opacity = 0.60;
            this.TopMost = true;

            Task.Factory.StartNew(() => Do(cts));
        }
       
        CancellationTokenSource cts = new CancellationTokenSource();
        private void Do(CancellationTokenSource cts)
        {
            while (!cts.IsCancellationRequested)
            {
                long rt = GetIntFromTime(DateTime.Now);
                string url = "http://fund.eastmoney.com/data/funddataforgznew.aspx?t=basewap&cb=jsonp&fc=000167&rt=" + rt.ToString();
                
                string html = Utils.GetHtmlSource(url, Encoding.UTF8);
                if (!string.IsNullOrEmpty(html))
                {
                    html = html.Replace("(", "[").Replace(")", "]").Substring(5).TrimEnd(';');
                    var serializer = new JavaScriptSerializer();
                    var deserializedResult = serializer.Deserialize<List<Fund>>(html);

                    double s1 = deserializedResult[0].Gsz;
                    double s2 = deserializedResult[0].Gszzl;
                    double s3 = Math.Round(deserializedResult[0].Gszzl / deserializedResult[0].Dwjz, 2);
                    string s4 = deserializedResult[0].Gztime;                   

                    this.SafeCall(() =>
                    {
                        lblInfo1.Text = s1 + "\r\n" + s2 + "\r\n" + s3 + "%\r\n" + s4 + "\r\n" + "update:" + DateTime.Now.ToString("HH:mm:ss");
                    });
                }
                Thread.Sleep(1000 * 60); //每隔60s查询
            }
        }

        private long lLeft = 621355968000000000;
        //将时间变成数字 
        public long GetIntFromTime(DateTime dt)
        {
            DateTime dt1 = dt.ToUniversalTime();
            long Sticks = (dt1.Ticks - lLeft) / 10000000;
            return Sticks;
        }

        [DllImport("user32.dll")]
        //方法扑捉
        public static extern bool ReleaseCapture();
        [DllImport("user32.dll")]
        public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
        public const int WM_SYSCOMMAND = 0x0112;
        public const int SC_MOVE = 0xF010;
        public const int HTCAPTION = 0x0002;
        void Panel2MouseDown(object sender, MouseEventArgs e)
        {
            //扑捉事件
            ReleaseCapture();
            //发送消息给window Api 来实现
            SendMessage(this.Handle, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0);//
        }
        private void label2_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
        /// <summary>  
        /// 隐藏窗体,并显示托盘图标  
        /// </summary>  
        private void HideForm()
        {
            this.Visible = false;
            this.WindowState = FormWindowState.Minimized;
            notifyIcon1.Visible = true;
        }

        /// <summary>  
        /// 显示窗体  
        /// </summary>  
        private void ShowForm()
        {
            this.Visible = true;
            this.WindowState = FormWindowState.Normal;
            notifyIcon1.Visible = false;
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            ShowForm();
        }

        private void ToolStripMenuItemShow_Click(object sender, EventArgs e)
        {
            ShowForm();
        }

        private void toolStripMenuItemExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void label1_Click(object sender, EventArgs e)
        {
            HideForm();
        }
    }
    public class Fund
    {
        public string Fundcode { get; set; }
        public string Name { get; set; }
        public string Jzrq { get; set; }
        public double Dwjz { get; set; }
        public double Gsz { get; set; }
        public double Gszzl { get; set; }
        public string Gztime { get; set; }
    }

}



你可能感兴趣的:(WinForm制作定时显示基金净值的桌面小工具(续))