感觉很久不写模拟器代码了,昨天调试的时候碰了点壁,记录下来,避免大家再跟我犯同样的错误。
加入Javascript脚本的地方:
HtmlElement jsElement = webBrowser1.Document.CreateElement("script");
jsElement.SetAttribute("type", "text/javascript");
jsElement.SetAttribute("text", "showMeAction = function(e) { window.alert(e);}");
webBrowser1.Document.Body.AppendChild(jsElement);
HtmlElement jsElement = webBrowser1.Document.CreateElement("script");
jsElement.SetAttribute("type", "text/javascript");
jsElement.SetAttribute("text", "showMeAction = function(e) { window.alert(e);}");
webBrowser1.Document.Body.AppendChild(jsElement);
调用的地方:
string[] args = new string[1];
args[0] = "Hello element!";
webBrowser1.Document.InvokeScript("showMeAction", args);
大家特别注意的是后面脚本调用的时候,只能出现函数名与参数值列表,不能增加其他内容,否则调用就不会成功。
使用的脚本代码:(这里的脚本代码模拟了鼠标移动的基础需求,通过Js直接发鼠标事件的方式来实现自动机器人)
function createEvent(eventName, ofsx, ofsy)
{
var evt = document.createEvent('MouseEvents');
evt.initMouseEvent(eventName, true, false, null, 0, 0, 0, ofsx, ofsy, false, false, false, false, 0, null);
return evt;
}
function moveElement(pxToMove)
{
var sliderKnob = document.getElementsByClassName("gt_slider_knob")[0];
var boxRect = sliderKnob.getBoundingClientRect();
var move = createEvent('mousemove', boxRect.left + sliderKnob.offsetLeft + pxToMove, boxRect.top + sliderKnob.offsetTop);
var down = createEvent('mousedown', boxRect.left + sliderKnob.offsetLeft, boxRect.top + sliderKnob.offsetTop);
var up = createEvent('mouseup');
sliderKnob.dispatchEvent(down);
document.dispatchEvent(move);
sliderKnob.dispatchEvent(up);
}
{
var sliderKnob = document.getElementsByClassName("gt_slider_knob")[0];
var boxRect = sliderKnob.getBoundingClientRect();
var move = createEvent('mousemove', boxRect.left + sliderKnob.offsetLeft + pxToMove, boxRect.top + sliderKnob.offsetTop);
var down = createEvent('mousedown', boxRect.left + sliderKnob.offsetLeft, boxRect.top + sliderKnob.offsetTop);
var up = createEvent('mouseup');
sliderKnob.dispatchEvent(down);
document.dispatchEvent(move);
sliderKnob.dispatchEvent(up);
}