在C#的现有IE窗口的选项卡中启动URL

Fed*_*rne 12 .net c# internet-explorer

当browserExe指向Firefox,Safari或Chrome时,以下代码会在现有浏览器窗口中打开链接.当指向IEXPLORE.EXE(IE7)时,将打开一个新窗口.

ProcessStartInfo pi = new ProcessStartInfo(browserExe, url);
Process.Start(pi);
Run Code Online (Sandbox Code Playgroud)

当IE是默认浏览器时,这将按预期在现有窗口中打开选项卡.

ProcessStartInfo pi = new ProcessStartInfo(url);
Process.Start(pi);
Run Code Online (Sandbox Code Playgroud)

当IE不是默认浏览器时,如何重用现有的IE窗口?

jms*_*era 25

使用shdocvw库(添加对它的引用,您可以在windows\system32中找到它),您可以获取实例列表并使用newtab参数调用navigate:

ShellWindows iExplorerInstances = new ShellWindows();
if (iExplorerInstances.Count > 0)
{
  IEnumerator enumerator = iExplorerInstances.GetEnumerator();
  enumerator.MoveNext();
  InternetExplorer iExplorer = (InternetExplorer)enumerator.Current;
  iExplorer.Navigate(url, 0x800); //0x800 means new tab
}
else
{
  //No iexplore running, use your processinfo method
}
Run Code Online (Sandbox Code Playgroud)

编辑:在某些情况下,您可能必须检查shellwindow是否对应于真正的iexplorer而不是任何其他Windows shell(在w7中所有实例都返回,现在不知道其他人).

   bool found=false;
   foreach (InternetExplorer iExplorer in iExplorerInstances)
   {
       if (iExplorer.Name == "Windows Internet Explorer")
       {
           iExplorer.Navigate(ur, 0x800);
           found=true;
           break;
       }
   }
   if(!found)
   {
      //run with processinfo
   }
Run Code Online (Sandbox Code Playgroud)

您可能还会发现这些额外的IE Navigate Flags非常有用.有关这些标志的完整说明,请访问http://msdn.microsoft.com/en-us/library/dd565688(v=vs.85).aspx

enum BrowserNavConstants 
{ 
    navOpenInNewWindow = 0x1, 
    navNoHistory = 0x2, 
    navNoReadFromCache = 0x4, 
    navNoWriteToCache = 0x8, 
    navAllowAutosearch = 0x10, 
    navBrowserBar = 0x20, 
    navHyperlink = 0x40, 
    navEnforceRestricted = 0x80, 
    navNewWindowsManaged = 0x0100, 
    navUntrustedForDownload = 0x0200, 
    navTrustedForActiveX = 0x0400, 
    navOpenInNewTab = 0x0800, 
    navOpenInBackgroundTab = 0x1000, 
    navKeepWordWheelText = 0x2000, 
    navVirtualTab = 0x4000, 
    navBlockRedirectsXDomain = 0x8000, 
    navOpenNewForegroundTab = 0x10000 
};
Run Code Online (Sandbox Code Playgroud)

  • 奇迹般有效.知道如何从枚举器中找到最后使用的浏览器窗口吗?(与点击电子邮件中的链接等时的行为相同) (5认同)