当试图列出浏览器Chrome的所有打开标签时,我得到异常如何解决?

时间:2015-03-26 12:53:26

标签: c# .net ui-automation

我在Program.cs中有一个新项目,我有:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Automation;
using System.Windows.Forms;
using System.Threading;

namespace List_all_opened_tabs_of_Firefox
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> firefoxUrls = new List<string>();

            Process firefox = Process.GetProcessesByName("chrome")[0];
            AutomationElement rootElement = AutomationElement.FromHandle(firefox.MainWindowHandle);

在原版中&#34; chrome&#34;它是&#34; firefox&#34; 但是我没有Firefox,所以我把它改成了chrome,然后我就变成了例外:

AutomationElement rootElement = AutomationElement.FromHandle(firefox.MainWindowHandle);

hwnd不能是IntPtr.Zero或null

System.ArgumentException was unhandled
  HResult=-2147024809
  Message=hwnd cannot be IntPtr.Zero or null.
  Source=UIAutomationClient
  StackTrace:
       at System.Windows.Automation.AutomationElement.FromHandle(IntPtr hwnd)
       at List_all_opened_tabs_of_Firefox.Program.Main(String[] args) in c:\listopentabs\List all opened tabs of Firefox\List all opened tabs of Firefox\Program.cs:line 20
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 

第20行是:

AutomationElement rootElement = AutomationElement.FromHandle(firefox.MainWindowHandle);

我试图获取所有已打开的Chrome标签的列表。 从这里下载并尝试了源代码:

List Open Tabs

1 个答案:

答案 0 :(得分:1)

查看任务管理器,有4个chrome进程正在运行。因此,循环遍历它们并选择具有非零MainWindowHandle的那个。

        var cp = Process.GetProcessesByName("chrome");
        IntPtr ww = IntPtr.Zero;
        foreach (var p in cp) {
            if (p.MainWindowHandle != IntPtr.Zero) {
                ww = p.MainWindowHandle;
            }
        }