csharp: WebBrowser read baidumap

setpoint.html:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>行政区域工具</title>
<script type="text/javascript" src="http://api.map.baidu.com/api?v=1.4"></script>
</head>
<body>
<div style="width:520px;height:340px;border:1px solid gray" id="container"></div>
<p><input id="startBtn" type="button" onclick="startTool();" value="开启取点工具" /><input type="button" onclick="map.clearOverlays();document.getElementById('info').innerHTML = '';points=[];" value="清除" /></p>
<div id="info"></div>
<div id="lng"></div>
<div id="lat"></div>
</body>
</html>
<script type="text/javascript">
var map = new BMap.Map("container");                        // 创建Map实例
map.centerAndZoom("北京", 11);     // 初始化地图,设置中心点坐标和地图级别
map.addControl(new BMap.NavigationControl());   
map.addControl(new BMap.ScaleControl()); 
 
var key = 1;    //开关
var newpoint;   //一个经纬度
var points = [];    //数组,放经纬度信息
var polyline = new BMap.Polyline(); //折线覆盖物
 
function startTool(){   //开关函数
if(key==1){
        document.getElementById("startBtn").style.background = "green";
        document.getElementById("startBtn").style.color = "white";
        document.getElementById("startBtn").value = "开启状态";
        key=0;
    }
    else{
        document.getElementById("startBtn").style.background = "red";
        document.getElementById("startBtn").value = "关闭状态";
        key=1;
    }
}
map.addEventListener("click",function(e){   //单击地图,形成折线覆盖物
    newpoint = new BMap.Point(e.point.lng,e.point.lat);
    if(key==0){
    //    if(points[points.length].lng==points[points.length-1].lng){alert(111);}
        points.push(newpoint);  //将新增的点放到数组中
        polyline.setPath(points);   //设置折线的点数组
        map.addOverlay(polyline);   //将折线添加到地图上
        document.getElementById("info").innerHTML += "new BMap.Point(" + e.point.lng + "," + e.point.lat + "),</br>";    //输出数组里的经纬度
       document.getElementById("lng").innerHTML= e.point.lng;
       document.getElementById("lat").innerHTML= e.point.lat;
    }
});
map.addEventListener("dblclick",function(e){   //双击地图,形成多边形覆盖物
if(key==0){
        map.disableDoubleClickZoom();   //关闭双击放大
var polygon = new BMap.Polygon(points);
        map.addOverlay(polygon);   //将折线添加到地图上
    }
});
</script>

  用Winform 读取百度地图的经纬度:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
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 System.Security.Permissions;
 
namespace baidudemo
{
 
 
    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
    [System.Runtime.InteropServices.ComVisibleAttribute(true)]
    public partial class Form2 : Form
    {
 
        /// <summary>
        ///
        /// </summary>
        public Form2()
        {
            InitializeComponent();
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form2_Load(object sender, EventArgs e)
        {
            string str_url = Application.StartupPath + "\\baidu\\setpoint.html";
            Uri url = new Uri(str_url);
            webBrowser1.Url = url;
            webBrowser1.ObjectForScripting = this;
 
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
 
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            string tag_lng = webBrowser1.Document.GetElementById("lng").InnerText;
            string tag_lat = webBrowser1.Document.GetElementById("lat").InnerText;
            this.textBox1.Text = tag_lat;
            this.textBox2.Text = tag_lng;
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void webBrowser1_LocationChanged(object sender, EventArgs e)
        {
;
        }
    }
}

  

1
2
3
4
5
6
7
8
9
10
11
12
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Web;
using System.Web.Script.Serialization; //引用System.Web.Extensions
using System.Data;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization.Formatters;

  

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
/// <summary>
///
/// </summary>
public class JsonHelper
{
    //对应JSON的singleInfo成员
    public string singleInfo = string.Empty;
 
    protected string _error = string.Empty;
    protected bool _success = true;
    protected long _totalCount = 0;
    protected System.Collections.ArrayList arrData = new ArrayList();
    protected System.Collections.ArrayList arrDataItem = new ArrayList();
 
    public JsonHelper()
    {
        //
        //TODO: 在此处添加构造函数逻辑
        //
    }
 
    //对应于JSON的success成员
    public bool success
    {
        get
        {
            return _success;
        }
        set
        {
            //如设置为true则清空error
            if (success) _error = string.Empty;
            _success = value;
        }
    }
 
    //对应于JSON的error成员
    public string error
    {
        get
        {
            return _error;
        }
        set
        {
            //如设置error,则自动设置success为false
            if (value != "") _success = false;
            _error = value;
        }
    }
 
    public long totlalCount
    {
        get { return _totalCount; }
        set { _totalCount = value; }
    }
 
 
    //重置,每次新生成一个json对象时必须执行该方法
    public void Reset()
    {
        _success = true;
        _error = string.Empty;
        singleInfo = string.Empty;
        arrData.Clear();
        arrDataItem.Clear();
    }
 
 
 
    public void AddItem(string name, string value)
{
    arrData.Add("/" + name + "/:" + "/" + value + "/");
}
 
 
 
    public void ItemOk()
    {
        arrData.Add("<BR>");
        //返回总记录条数
        totlalCount++;
    }
 
    //序列化JSON对象,得到返回的JSON代码
    public override string ToString()
   {
    StringBuilder sb = new StringBuilder();
    sb.Append("{");
    sb.Append("/totalCount/:/" + _totalCount.ToString() + "/,");
    sb.Append("/success/:" + _success.ToString().ToLower() + "/,");
    sb.Append("/error/:/" + _error.Replace("/", "///") + "/,");
    sb.Append("/data/:/[");
 
    int index = 0;
    sb.Append("{");
    if (arrData.Count <= 0)
    {
        sb.Append("}");
    }
    else
    {
        foreach (string val in arrData)
        {
            index++;
 
            if (val != "<BR>")
            {
                sb.Append(val + ",");
            }
            else
            {
                sb = sb.Replace(",", "", sb.Length - 1, 1);
                sb.Append("},");
                if (index < arrData.Count)
                {
                    sb.Append("{");
                }
            }
 
        }
        sb = sb.Replace(",", "", sb.Length - 1, 1);
        sb.Append("]");
    }
 
    sb.Append("}");
    return sb.ToString();
}
 
    public string ToSingleString()
    {
        StringBuilder sb = new StringBuilder();
        sb.Append("{");
 
        sb.Append("success:" + _success.ToString().ToLower() + ",");
 
        sb.Append("data:");
 
        int index = 0;
        sb.Append("{");
        if (arrData.Count <= 0)
        {
            sb.Append("}");
        }
        else
        {
            foreach (string val in arrData)
            {
                index++;
 
                if (val != "<BR>")
                {
                    sb.Append(val + ",");
                }
                else
                {
                    sb = sb.Replace(",", "", sb.Length - 1, 1);
                    sb.Append("},");
                    if (index < arrData.Count)
                    {
                        sb.Append("{");
                    }
                }
 
            }
            sb = sb.Replace(",", "", sb.Length - 1, 1);
            sb.Append("");
        }
 
        sb.Append("}");
        return sb.ToString();
    }
 
 
 
     public static string ObjectToJSON(object obj)   
     {       
         JavaScriptSerializer jss =new JavaScriptSerializer();       
         try       
         {           
             return jss.Serialize(obj);       
         }       
         catch(Exception ex)       
         {           
             throw new Exception("JSONHelper.ObjectToJSON(): "+ ex.Message);       
         }   
     }   
     public static List<Dictionary<string,object>>DataTableToList(DataTable dt)   
     {       
         List<Dictionary<string,object>> list=new List<Dictionary<string,object>>();       
         foreach(DataRow dr in dt.Rows)       
         {           
             Dictionary<string,object> dic =new Dictionary<string,object>();           
             foreach(DataColumn dc in dt.Columns)           
             {               
                 dic.Add(dc.ColumnName, dr[dc.ColumnName]);           
             }           
             list.Add(dic);       
         }        return list;   
     
    /// <summary>
    ///
    /// </summary>
    /// <param name="ds"></param>
    /// <returns></returns>
    public static Dictionary<string,List<Dictionary<string,object>>>DataSetToDic(DataSet ds)   
    {       
        Dictionary<string,List<Dictionary<string,object>>> result =new Dictionary<string,List<Dictionary<string,object>>>();       
        foreach(DataTable dt in ds.Tables)           
            result.Add(dt.TableName,DataTableToList(dt));       
        return result;   
    }   
    /// <summary>
    ///
    /// </summary>
    /// <param name="dt"></param>
    /// <returns></returns>
    public static string DataTableToJSON(DataTable dt)   
    {       
        return ObjectToJSON(DataTableToList(dt));   
    }      
    /// <summary>
    ///
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="jsonText"></param>
    /// <returns></returns>
    public static T JSONToObject<T>(string jsonText)   
    {       
        JavaScriptSerializer jss =new JavaScriptSerializer();       
        try       
        {           
            return jss.Deserialize<T>(jsonText);       
        }       
        catch(Exception ex)       
        {           
            throw new Exception("JSONHelper.JSONToObject(): "+ ex.Message);       
        }   
    
    /// <summary>
    ///
    /// </summary>
    /// <param name="jsonText"></param>
    /// <returns></returns>
    public static Dictionary<string,List<Dictionary<string,object>>>TablesDataFromJSON(string jsonText)   
    {       
        return JSONToObject<Dictionary<string,List<Dictionary<string,object>>>>(jsonText);   
    }   
    /// <summary>
    ///
    /// </summary>
    /// <param name="jsonText"></param>
    /// <returns></returns>
    public static Dictionary<string,object>DataRowFromJSON(string jsonText)   
    {       
        return JSONToObject<Dictionary<string,object>>(jsonText);   
    }
 
     
 
 public static string ToJsJson(object item)//参数要装换成JSON的对象 
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(item.GetType()); 
    using(MemoryStream ms=new MemoryStream()) 
    
        serializer.WriteObject(ms, item); 
        StringBuilder sb = new StringBuilder(); 
        sb.Append(Encoding.UTF8.GetString(ms.ToArray())); 
        return sb.ToString(); 
    
 
//反序列化 
//T指定要序列化的对象,jsonString是JSON字符串变量
public static T FromJsonTo<T>(string jsonString) 
    DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); 
    using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString))) 
    
        T jsonObject = (T)ser.ReadObject(ms); 
        return jsonObject; 
    
}

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
/// <summary>
    /// 提供 Http 相关方法。
    /// </summary>
    public class HttpUtils
    {
 
        /// <summary>
        /// 执行HTTP GET请求。
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="parameters">请求参数</param>
        /// <returns>HTTP响应</returns>
        public static string DoGet(string url, IDictionary<string, string> parameters)
        {
            if (parameters != null && parameters.Count > 0)
            {
                if (url.Contains("?"))
                {
                    url = url + "&" + BuildPostData(parameters);
                }
                else
                {
                    url = url + "?" + BuildPostData(parameters);
                }
            }
 
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.ServicePoint.Expect100Continue = false;
            req.Method = "GET";
            req.KeepAlive = true;
            req.UserAgent = "Test";
            req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
 
            HttpWebResponse rsp = null;
            try
            {
                rsp = (HttpWebResponse)req.GetResponse();
            }
            catch (WebException webEx)
            {
                if (webEx.Status == WebExceptionStatus.Timeout)
                {
                    rsp = null;
                }
            }
 
            if (rsp != null)
            {
                if (rsp.CharacterSet != null)
                {
                    Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
                    return GetResponseAsString(rsp, encoding);
                }
                else
                {
                    return string.Empty;
                }
            }
            else
            {
                return string.Empty;
            }
        }
 
        /// <summary>
        /// 把响应流转换为文本。
        /// </summary>
        /// <param name="rsp">响应流对象</param>
        /// <param name="encoding">编码方式</param>
        /// <returns>响应文本</returns>
        private static string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
        {
            StringBuilder result = new StringBuilder();
            Stream stream = null;
            StreamReader reader = null;
 
            try
            {
                // 以字符流的方式读取HTTP响应
                stream = rsp.GetResponseStream();
                reader = new StreamReader(stream, encoding);
 
                // 每次读取不大于256个字符,并写入字符串
                char[] buffer = new char[256];
                int readBytes = 0;
                while ((readBytes = reader.Read(buffer, 0, buffer.Length)) > 0)
                {
                    result.Append(buffer, 0, readBytes);
                }
            }
            catch (WebException webEx)
            {
                if (webEx.Status == WebExceptionStatus.Timeout)
                {
                    result = new StringBuilder();
                }
            }
            finally
            {
                // 释放资源
                if (reader != null) reader.Close();
                if (stream != null) stream.Close();
                if (rsp != null) rsp.Close();
            }
 
            return result.ToString();
        }
 
        /// <summary>
        /// 组装普通文本请求参数。
        /// </summary>
        /// <param name="parameters">Key-Value形式请求参数字典。</param>
        /// <returns>URL编码后的请求数据。</returns>
        private static string BuildPostData(IDictionary<string, string> parameters)
        {
            StringBuilder postData = new StringBuilder();
            bool hasParam = false;
 
            IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
            while (dem.MoveNext())
            {
                string name = dem.Current.Key;
                string value = dem.Current.Value;
                // 忽略参数名或参数值为空的参数
                if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(value))
                {
                    if (hasParam)
                    {
                        postData.Append("&");
                    }
 
                    postData.Append(name);
                    postData.Append("=");
                    postData.Append(Uri.EscapeDataString(value));
                    hasParam = true;
                }
            }
 
            return postData.ToString();
        }
        /*
         GoBack():后退
        GoForward():前进
        Refresh():刷新
        Stop():停止
        GoHome():浏览主页
        WebBrowser控件的常用属性:
        Document:获取当前正在浏览的文档
        DocumentTitle:获取当前正在浏览的网页标题
        StatusText:获取当前状态栏的文本
        Url:获取当前正在浏览的网址的Uri
        ReadyState:获取浏览的状态
        WebBrowser控件的常用事件:
        DocumentTitleChanged,
        CanGoBackChanged,
        CanGoForwardChanged,
        DocumentTitleChanged,
        ProgressChanged,
        ProgressChanged
          
         */
        /// <summary>
        /// 根据Name获取元素
        /// </summary>
        /// <param name="wb"></param>
        /// <param name="Name"></param>
        /// <returns></returns>
        public HtmlElement GetElement_Name(WebBrowser wb, string Name)
        {
            HtmlElement e = wb.Document.All[Name];
            return e;
        }
 
        /// <summary>
        /// 根据Id获取元素
        /// </summary>
        /// <param name="wb"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public HtmlElement GetElement_Id(WebBrowser wb, string id)
        {
            HtmlElement e = wb.Document.GetElementById(id);
            return e;
        }
 
        /// <summary>
        /// 根据Index获取元素
        /// </summary>
        /// <param name="wb"></param>
        /// <param name="index"></param>
        /// <returns></returns>
        public HtmlElement GetElement_Index(WebBrowser wb, int index)
        {
            HtmlElement e = wb.Document.All[index];
            return e;
        }
 
        /// <summary>
        /// 获取form表单名name,返回表单
        /// </summary>
        /// <param name="wb"></param>
        /// <param name="form_name"></param>
        /// <returns></returns>
        public HtmlElement GetElement_Form(WebBrowser wb, string form_name)
        {
            HtmlElement e = wb.Document.Forms[form_name];
            return e;
        }
 
 
        /// <summary>
        /// 设置元素value属性的值
        /// </summary>
        /// <param name="e"></param>
        /// <param name="value"></param>
        public void Write_value(HtmlElement e, string value)
        {
            e.SetAttribute("value", value);
        }
 
        /// <summary>
        /// 执行元素的方法,如:click,submit(需Form表单名)等
        /// </summary>
        /// <param name="e"></param>
        /// <param name="s"></param>
        public void Btn_click(HtmlElement e, string s)
        {
 
            e.InvokeMember(s);
        }
    }

  工作流程图:

https://jsplumbtoolkit.com/demos/toolkit/flowchart-builder/index.html

posted @   ®Geovin Du Dream Park™  阅读(805)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示