本文代碼下載(VS2010開發):http://download.csdn.net/source/2796362
本文摘要:
1:一個簡單的例子
1.1:EnumChildWindows介紹
1.2:主要源碼
2:難點:如何獲取指定的控件句柄
2.1:使用SPY++
2.2:獲取控件位置
2.3:獲取控件ID
在日常編碼過程中,我們常常會進行自動化測試。這裡的自動化測試不是指單元測試,而是模擬人工輸入來進行快速的、高並發的測試。可以使用的自動化工具有LOADRUNNER,以及目前在VS2010中的功能很強大的測試工作平台(錄制操作步驟,自動生成代碼)。但是,這些工具的熟練掌握也有一定的時間成本,並且,最主要的,對於一個程序員來說,那不夠靈活。所以,比較高效的一個做法是,調用WINDOWS API,自己動手寫編碼來實現。
下面做一個簡單的演示。為了簡便起見,假設存在這樣一個應用程序:
1:提供一個WINFORM窗體,上面存在一個TextBox,以及一個Button;
2:點擊Button,會彈出提示框,提示框內容為TextBox的值;
現在,測試要求如下:
1:在300台機器上運行上面的程序;
2:到這300台機器上去點擊這個Button,看看上文中的功能2有沒有實現;
很顯然,實際情況中沒有這麼簡單的程序,實際的情況有可能是點擊Button,統一下載一個文件,而測試的要求可能就變為考核服務器的負載。現在,測試部顯然也沒有300個人坐在客戶機上驗證測試的結果,這個時候,就需要我們提供一個自動化的測試工具,來完成必要的測試任務。
測試工具,首先也是一個C#的程序,它的主要目的是:
1:獲取上文應用程序的窗口句柄,繼而獲取TextBox句柄及Button句柄;
2:為TextBox隨機填入一些字符;
3:模擬點擊Button;
在這裡需要介紹下EnumChildWindows,
EnumChildWindows可是個好東西,可以枚舉一個父窗口的所有子窗口:
BOOL EnumChildWindows(
HWND hWndParent, // handle to parent window // 父窗口句柄
WNDENUMPROC lpEnumFunc, // callback function // 回調函數的地址
LPARAM lParam // application-defined value // 你自已定義的參數
);
就這麼簡單,讓我們再定義一個回調函數,像下面這樣:
BOOL CALLBACK EnumChildProc(
HWND hwnd, // handle to child window
LPARAM lParam // application-defined value
);
在調用EnumChildWindows 這個函數時,直到調用到最個一個子窗口被枚舉或回調函數返回一個false,否則將一直枚舉下去。
測試工具的主要代碼如下:
private void button1_Click(object sender, EventArgs e)
{
//獲取測試程序的窗體句柄
IntPtr mainWnd = FindWindow(null, "FormLogin");
List<IntPtr> listWnd = new List<IntPtr>();
//獲取窗體上OK按鈕的句柄
IntPtr hwnd_button = FindWindowEx(mainWnd, new IntPtr(0), null, "OK");
//獲取窗體上所有控件的句柄
EnumChildWindows(mainWnd, new CallBack(delegate(IntPtr hwnd, int lParam)
{
listWnd.Add(hwnd);
return true;
}), 0);
foreach (IntPtr item in listWnd)
{
if (item != hwnd_button)
{
char[] UserChar = "luminji".ToCharArray();
foreach (char ch in UserChar)
{
SendChar(item, ch, 100);
}
}
}
SendMessage(hwnd_button, WM_CLICK, mainWnd, "0");
}
public void SendChar(IntPtr hand, char ch, int SleepTime)
{
PostMessage(hand, WM_CHAR, ch, 0);
System.Threading.Thread.Sleep(SleepTime);
}
public static int WM_CHAR = 0x102;
public static int WM_CLICK = 0x00F5;
[DllImport("User32.dll", EntryPoint = "SendMessage")]
public static extern int SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, string lParam);
[DllImport("user32.dll")]
public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter,
string lpszClass, string lpszWindow);
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")]
public static extern int AnyPopup();
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern int GetWindowText(IntPtr hWnd,