好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

使用C# 的webBrowser写模拟器时的javascript脚本调用问题

感觉很久不写模拟器代码了,昨天调试的时候碰了点壁,记录下来,避免大家再跟我犯同样的错误。

加入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);

调用的地方:

?

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);

}

以上所述是小编给大家介绍的使用C# 的webBrowser写模拟器时的javascript脚本调用问题,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!

原文链接:http://blog.csdn.net/jackxinxu2100/article/details/74905348?utm_source=tuicool&utm_medium=referral

dy("nrwz");

查看更多关于使用C# 的webBrowser写模拟器时的javascript脚本调用问题的详细内容...

  阅读:40次