欢迎光临

木子屋

标题: C#事件防止重复注册和移除全部事件示例

作者: dnawo

日期: 2015-01-05 09:19 PM

分类: Win编程

内容: 复制内容到剪贴板 程序代码public class WebBrowserEventManager
{
private EventHandlerList _ehList = new EventHandlerList();
private WebBrowser _wb = null;
/// <summary>
/// 构造函数
/// </summary>
/// <param name="webbrowser"></param>
public WebBrowserEventManager(WebBrowser webbrowser)
{
_wb = webbrowser;
}
/// <summary>
/// 注册事件(不可重复注册)
/// </summary>
/// <param name="eventHandler"></param>
public void AddDocumentCompletedEvent(WebBrowserDocumentCompletedEventHandler eventHandler)
{
RemoveDocumentCompletedEvent(eventHandler);
_wb.DocumentCompleted += eventHandler;
_ehList.AddHandler(_wb.Name, eventHandler);
}
/// <summary>
/// 注册事件(移除全部事件再注册)
/// </summary>
/// <param name="eventHandler"></param>
public void AddDocumentCompletedEventEx(WebBrowserDocumentCompletedEventHandler eventHandler)
{
RemoveAllDocumentCompletedEvent();
_wb.DocumentCompleted += eventHandler;
_ehList.AddHandler(_wb.Name, eventHandler);
}
/// <summary>
/// 移除事件
/// </summary>
/// <param name="eventHandler"></param>
public void RemoveDocumentCompletedEvent(WebBrowserDocumentCompletedEventHandler eventHandler)
{
Delegate dg = _ehList[_wb.Name];
if (dg != null)
{
Delegate[] ivList = dg.GetInvocationList();
if (ivList != null)
{
for (int i = ivList.Length - 1; i >= 0; i--)
{
if (eventHandler == null || (eventHandler != null && (ivList[i] as WebBrowserDocumentCompletedEventHandler) == eventHandler))
{
_wb.DocumentCompleted -= ivList[i] as WebBrowserDocumentCompletedEventHandler;
_ehList.RemoveHandler(_wb.Name, ivList[i]);
}
//return; //不退出循环移除重复注册事件
}
}
}
}
/// <summary>
/// 移除全部事件
/// </summary>
public void RemoveAllDocumentCompletedEvent()
{
RemoveDocumentCompletedEvent(null);
}
}
调用示例：
复制内容到剪贴板 程序代码using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private WebBrowserEventManager manager;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
manager = new WebBrowserEventManager(webBrowser1);
}
private void button1_Click(object sender, EventArgs e)
{
manager.AddDocumentCompletedEventEx(Todo1);
webBrowser1.Navigate("http://www.baidu.com/");
}
private void button2_Click(object sender, EventArgs e)
{
manager.AddDocumentCompletedEventEx(Todo2);
webBrowser1.Navigate("http://www.google.com/");
}
private void Todo1(object sender, WebBrowserDocumentCompletedEventArgs e)
{
MessageBox.Show("打开了百度。");
//针对百度页面的操作
}
private void Todo2(object sender, WebBrowserDocumentCompletedEventArgs e)
{
MessageBox.Show("打开了谷歌。");
//针对谷歌页面的操作
}
}
}
参考资料
[1].C#中删除任意控件任意事件的事件列表的实现：http://blog.csdn.net/softman11/article/details/5615267

+ 查看当前日志评论 (0)

登录

────────────

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 2.414 ms

返回

标题: C#事件防止重复注册和移除全部事件示例

你没有权限发表评论

────────────

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 2.414 ms

返回

暂无评论

返回

────────────

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 2.461 ms

返回