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

问题描述 投票:11回答:1

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

ProcessStartInfo pi = new ProcessStartInfo(browserExe, url);
Process.Start(pi);

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

ProcessStartInfo pi = new ProcessStartInfo(url);
Process.Start(pi);

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

c# .net internet-explorer
1个回答
24
投票

使用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
}

编辑:在某些情况下,您可能必须检查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
   }

您可能还会发现这些额外的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 
};
© www.soinside.com 2019 - 2024. All rights reserved.