访问被拒绝 - 尝试从地址栏的句柄获取URL(文本)时

Sam*_*eet 5 c# winapi handle access-denied

我正在尝试从IE的地址栏中提取URL.(使用以下C#代码在Windows 7上的IE 8).

        static string GetUrlFromIE()
        {
            IntPtr windowHandle = APIFuncs.getForegroundWindow();
            IntPtr childHandle;
            String strUrlToReturn = "";

            //try to get a handle to IE's toolbar container
            childHandle = APIFuncs.FindWindowEx(windowHandle, IntPtr.Zero, "WorkerW", IntPtr.Zero);
            if (childHandle != IntPtr.Zero)
            {
                //get a handle to address bar
                childHandle = APIFuncs.FindWindowEx(childHandle, IntPtr.Zero, "ReBarWindow32", IntPtr.Zero);
                if (childHandle != IntPtr.Zero)
                {
                    childHandle = APIFuncs.FindWindowEx(childHandle, IntPtr.Zero, "Address Band Root", IntPtr.Zero);
                    if (childHandle != IntPtr.Zero)
                    {
                        childHandle = APIFuncs.FindWindowEx(childHandle, IntPtr.Zero, "Edit", IntPtr.Zero);
                        if (childHandle != IntPtr.Zero)
                        {
                            strUrlToReturn = new string((char)0, 256);
                            GetWindowText(hwnd, strUrlToReturn , strUrlToReturn.Length);
                        }
                    }
                 }
            }
            return strUrlToReturn;
        } 
Run Code Online (Sandbox Code Playgroud)

GetWindowText调用返回"访问被拒绝"异常.在使用管理员权限运行应用程序时,它会抛出"系统无法找到指定的文件".

有任何想法吗?

Ale*_* K. 2

GetWindowText()无法在另一个进程中检索控件的文本,您应该SendMessage()WM_GETTEXTLENGTH/一起使用WM_GETTEXT

编辑; 版本无关的方式:

(添加对 c:\WINDOWS\system32\shdocvw.dll 的引用)

using SHDocVw;
.
.
foreach (InternetExplorer ieInst in new ShellWindowsClass())
   Console.WriteLine(ieInst.LocationURL);
Run Code Online (Sandbox Code Playgroud)