c# - 如何在 C# 中使用 Microsoft Edge 以编程方式在同一选项卡中打开网页?
问题描述
对于 IE 浏览器,我知道我们可以使用SHDocVw.ShellWindows
IE 来控制在同一个标签页中导航的网页。
IE中的示例代码:
SHDocVw.ShellWindows windows = new SHDocVw.ShellWindows();
//enumerate windows
foreach (SHDocVw.InternetExplorer window in windows)
{
if (window.LocationURL.Contains(matchUrl))
{
window.Navigate(originalUrl, null, null, null, null);
break;
}
}
我想知道是否可以在 Edge 浏览器的同一选项卡中打开网页?谢谢。
解决方案
您可以尝试使用 C# 中的UIAutomation
API来实现类似的要求。
编辑:经过jerry的提醒,考虑到应用最小化时,可能需要使用ShowWindow
API在前台显示Edge。
一个简单的demo,请参考:
class Program
{
[DllImport("User32.dll")]
static extern int SetForegroundWindow(IntPtr point);
[DllImport("User32")]
private static extern int ShowWindow(int hwnd, int nCmdShow);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetWindowPlacement(IntPtr hWnd, ref Windowplacement lpwndpl);
private struct Windowplacement
{
public int length;
public int flags;
public int showCmd;
public System.Drawing.Point ptMinPosition;
public System.Drawing.Point ptMaxPosition;
public System.Drawing.Rectangle rcNormalPosition;
}
static void Main(string[] args)
{
Process[] procsEdge = System.Diagnostics.Process.GetProcessesByName("msedge");
foreach (Process proc in procsEdge)
{
Windowplacement placement = new Windowplacement();
GetWindowPlacement(proc.MainWindowHandle, ref placement);
// Check if window is minimized
if (placement.showCmd == 2)
{
//the window is hidden so we restore it
ShowWindow(proc.MainWindowHandle.ToInt32(), 9);
}
//Switch Edge tab to the first one
SetForegroundWindow(proc.MainWindowHandle);
SendKeys.SendWait("^1");
if (proc.MainWindowHandle == IntPtr.Zero)
continue;
string matchUrl = "https://www.bing.com";
string originalUrl = "http://www.google.com/";
int numTabs = procsEdge.Length;
int index = 1;
//loop all tabs in Edge
while (index <= numTabs)
{
//get the url of tab
AutomationElement root = AutomationElement.FromHandle(proc.MainWindowHandle);
var SearchBar = root.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, "Address and search bar"));
if (SearchBar != null)
{
string str = (string)SearchBar.GetCurrentPropertyValue(ValuePatternIdentifiers.ValueProperty);
//Determine whether the url matches and redirect
if (str.Contains(matchUrl))
{
SetForegroundWindow(proc.MainWindowHandle);
SendKeys.SendWait("^l");
SendKeys.SendWait(originalUrl);
SendKeys.SendWait("{Enter}");
break;
}
}
index++;
SendKeys.SendWait("^{TAB}"); // change focus to next tab
}
}
}
}
注意:请根据自己的情况适当修改页面url参数。