WebBrowser捕获网页关闭事件

 最近在做项目的时候用到了WebBrowser,需要在关闭网页的同时关闭WebBroser所在的WinForm界面,在网上及MSDN找到的方法都不是很好,偶然在code project中找到了比较好的方法,特意摘录再次,供大家分享。

   

实现方案:

  1. 重写 WndProc 方法
  2. 判断 WM_PARENTNOTIFY 消息
  3. 判断 WM_DESTROY 消息参数
  4. 执行事件委托方法

#region Raises the Quit event when the browser window is about to be destroyed   
  
        
/// <summary>   
        
/// Overridden   
        
/// </summary>   
        
/// <param name="m">The <see cref="Message"/> send to this procedure</param>   
        [PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")]   
        
protected override void WndProc(ref Message m)   
        {   
            
if (m.Msg == (int)WindowsMessages.WM_PARENTNOTIFY)   
            {   
                
//int lp = m.LParam.ToInt32();   
                int wp = m.WParam.ToInt32();   
  
                
int X = wp & 0xFFFF;   
                
//int Y = (wp >> 16) & 0xFFFF;   
                if (X == (int)WindowsMessages.WM_DESTROY)   
                    
this.OnQuit();   
            }   
  
            
base.WndProc(ref m);   
        }   
  
        
/// <summary>   
        
/// A list of all the available window messages   
        
/// </summary>   
        enum WindowsMessages   
        {      
            WM_DESTROY 
= 0x2,   
            WM_PARENTNOTIFY 
= 0x210,   
        }   
  
        
/// <summary>   
        
/// Raises the <see cref="Quit"/> event   
        
/// </summary>   
        protected void OnQuit()   
        {   
            EventHandler h 
= Quit;   
            
if (null != h)   
                h(
this, EventArgs.Empty);   
        }   
  
        
/// <summary>   
        
/// Raised when the browser application quits   
        
/// </summary>   
        
/// <remarks>   
        
/// Do not confuse this with DWebBrowserEvents2.Quit That's something else.   
        
/// </remarks>   
        public event EventHandler Quit;  
 
 
        
#endregion  

 

fer:

Jeroen Landheer

posted @ 2010-09-17 08:52  peterlee  阅读(2032)  评论(0)    收藏  举报