Access is denied - when trying to get the url (text) from address bar's handle

旧巷老猫 提交于 2019-12-01 17:27:33

问题


I'm trying to extract the URL from the address bar of IE. (IE 8 on Windows 7) using the following C# code.

        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;
        } 

The GetWindowText call returns an "Access is denied" exception. On running the app with admin privileges, it throws a "System cannot find the file specified".

Any ideas?


回答1:


GetWindowText() can't retrieve the text of a control in another process, instead you should use SendMessage() with WM_GETTEXTLENGTH / WM_GETTEXT.

Edit; Version agnostic way:

(Add a ref to c:\WINDOWS\system32\shdocvw.dll)

using SHDocVw;
.
.
foreach (InternetExplorer ieInst in new ShellWindowsClass())
   Console.WriteLine(ieInst.LocationURL);


来源:https://stackoverflow.com/questions/3288092/access-is-denied-when-trying-to-get-the-url-text-from-address-bars-handle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!