文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>自动关闭webBrowser弹出的所有窗口

自动关闭webBrowser弹出的所有窗口

时间:2010-08-18  来源:lhking

在C# winform程序里,webBrowser是一个很好用的,类似浏览器的控件。在模拟post,get请求时,有些时候HttpWebRequest和HttpWebResponse,会不能用,因为有些网站有“防”(加js等)这种请求,必须要浏览器来请求才可以,这样我们就需要把HttpWebRequest的cookie传到WebBrowser里面。

传cookie的话要用到InternetSetCookie这个API函数

  [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
  public static extern bool InternetSetCookie(string lpszUrlName, string lbszCookieName, string lpszCookieData);

引用命名空间:using System.Runtime.InteropServices;

 

调用示例:InternetSetCookie(“url", "cookiename", "cookievalue");

 

虽然webBrowser很好用,但有些时候,会弹出一些js窗口,还有脚本错误之类的东东。

 

1、对于脚本错误的话,webBrowser有个ScriptErrorsSuppressed属性,默认是false,不阻止,要想阻止这类错误,只要设成true,就可以了。

 

2、对于js窗口,我用了windows api 函数FindWindow等。

我封装了一个类,在程序中调用就可以实现关闭所有弹出的js窗口。

调用代码:CloseJsWindow.StartCloseWindow();

类代码:

CloseJsWindow
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Threading;

namespace SUP
{
public class CloseJsWindow
{
[DllImport(
"user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

[DllImport(
"user32.dll", EntryPoint = "FindWindowEx", SetLastError = true)]
private static extern IntPtr FindWindowEx(IntPtr hwndParent, uint hwndChildAfter, string lpszClass, string lpszWindow);

[DllImport(
"user32.dll", EntryPoint = "SendMessage", SetLastError = true, CharSet = CharSet.Auto)]
private static extern int SendMessage(IntPtr hwnd, uint wMsg, IntPtr wParam, int lParam);

[DllImport(
"user32.dll", EntryPoint = "SetForegroundWindow", SetLastError = true)]
private static extern void SetForegroundWindow(IntPtr hwnd);

private static string windowTitle = "Message from webpage";
private const uint BM_CLICK = 0xF5; //鼠标点击的消息,对于各种消息的数值,大家还是得去API手册

static System.Threading.Timer findTimer;
static AutoResetEvent autoEvent;


/// <summary>
/// 开始监视js弹出的窗口
/// </summary>
public static void StartCloseWindow()
{
autoEvent
= new AutoResetEvent(false); //初始状态设置为非终止
TimerCallback timerDelegate = new TimerCallback(CloseWindow);
findTimer
= new System.Threading.Timer(timerDelegate, autoEvent, 1000, 800); //每0.8秒钟查找一次
}
/// <summary>
/// 停止监视js弹出的窗口
/// </summary>
public static void StopCloseWindow()
{
autoEvent.WaitOne(
10, false); //设置10毫秒,是让程序有一个等待,如果设为0,会一直弹窗口
findTimer.Dispose();
}
private static void CloseWindow(object state)
{
IntPtr hwnd
= FindWindow(null, windowTitle); //查找窗口的句柄
if (hwnd != IntPtr.Zero)
{
IntPtr hwndSure
= FindWindowEx(hwnd, 0, "Button", "确定"); //获取确定按钮的句柄
SendMessage(hwndSure, BM_CLICK, (IntPtr)0, 0); //发送单击消息
}
}
}
}

要想停止的话,只要调用 CloseJsWindow.StopCloseWindow()就行了。

相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载