日期:2014-05-17  浏览次数:20849 次

这样的代码居然也会出错??
本帖最后由 onefox 于 2014-01-19 16:05:06 编辑
想做一个C#操控IE的东西,系统时Windows7,浏览器是IE7,VS是2008
网上Copy了一点代码,但慕名奇妙得出差了。


            InternetExplorer ie = null;
            if (p != null)
            {
                SHDocVw.ShellWindows allBrowser = new ShellWindows();
                if (allBrowser.Count != 0)
                {
                    
                    for (int i = 0; i < allBrowser.Count; i++)
                    {
                        InternetExplorer x = (InternetExplorer)allBrowser.Item(i);
                        int m = 0 + x.HWND; //这里VS报错
                        MessageBox.Show("x.HWND = " + m); //但这个消息框会正常显示,里面还有6位数的m值
                    }
                }
            }



错误信息:

未处理 System.InvalidCastException
  Message="指定的转换无效。"
  Source="Interop.SHDocVw"
  StackTrace:
       在 SHDocVw.IWebBrowser2.get_HWND()
       在 testWindows1.Form1.button1_Click(Object sender, EventArgs e) 位置 D:\Visual Studio Projects\Projects\testWindows1\testWindows1\Form1.cs:行号 42
       在 System.Windows.Forms.Control.OnClick(EventArgs e)
       在 System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       在 System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       在 System.Windows.Forms.Control.WndProc(Message& m)
       在 System.Windows.Forms.ButtonBase.WndProc(Message& m)
       在 System.Windows.Forms.Button.WndProc(Message& m)
       在 System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       在 System.Windows.Forms.NativeWindow.DebuggableCallb