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