C#通過Win32 API操作IE瀏覽器 — 獲得IE的URL

來源:互聯網
上載者:User

        Windows作業系統是一個訊息驅動的作業系統,所以要想操作Windows作業系統中的任何控制項,都可以用訊息來進行。Windows作業系統開放了大量的API給使用者,使用者可以通過這些API從底層來操作Windows系統中的控制項,並且是以訊息的方式進行的,下面以C#通過Win32 API來操作IE瀏覽器 --- 獲得IE的URL為例: 至於API訊息函數的原型,可以在MSDN中查到,至於API訊息函數的原型在C#中怎麼用C#語言的元素表示出來,可以通過以下的例子看出來。

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices; //操作Win32API必須要引入的命名空間

namespace IEManipulation
{
    public class IEManipulation
    {
        [DllImport("User32.dll")] //User32.dll是Windows作業系統的核心動態庫之一
         static extern int FindWindow(string lpClassName, string lpWindowName);
        [DllImport("User32.dll")]
         static extern int FindWindowEx(int hwndParent, int hwndChildAfter, string lpszClass, string lpszWindow);
        [DllImport("User32.dll")]
         static extern int GetWindowText(int hwnd, StringBuilder buf, int nMaxCount);
        [DllImport("User32.dll")]
         static extern int SendMessage(int hWnd, int Msg, int wParam, StringBuilder lParam);

        const int WM_GETTEXT = 0x000D; //獲得簡訊的16進位表示

        /// <summary>
        /// Get the URL of the current opened IE
        /// </summary>
        public static string GetURL() 
        {
            int parent = FindWindow("IEFrame", null);
            int child = FindWindowEx(parent, 0, "WorkerW", null);
            child = FindWindowEx(child, 0, "ReBarWindow32", null);
            child = FindWindowEx(child, 0, "ComboBoxEx32", null);
            child = FindWindowEx(child, 0, "ComboBox", null);
            child = FindWindowEx(child, 0, "Edit", null);   //通過SPY++獲得地址欄的階層,然後一層一層獲得
            StringBuilder buffer = new StringBuilder(1024);
            
            //child表示要操作表單的控制代碼號
            //WM_GETTEXT表示一個訊息,怎麼樣來驅動表單
            //1024表示要獲得text的大小
            //buffer表示獲得text的值存放在記憶體緩衝中
            int num = SendMessage(child, WM_GETTEXT, 1024, buffer);
            string URL = buffer.ToString();
            return URL;
        }
    }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.