昨天在做一個網(wǎng)頁測試時,它會彈出一個對話框(如下圖)對用戶進(jìn)行一個認(rèn)證。

使用Spy++偵測這個對話框的結(jié)構(gòu)如下,我們看到兩個Edit就在最后兩個節(jié)點(diǎn)上。

我們現(xiàn)在就可以利用FindWindow以及FindWindowEx這兩個函數(shù)來幫我們找到這個窗體及窗體上所有的控件,然后幫我們完成自動化測試。
下面這個程序就是幫我們自動輸入用戶名與密碼。

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; using System.Threading;
namespace ConsoleApplication79 { class Program { [DllImport("user32.dll", EntryPoint = "FindWindow", CharSet = CharSet.Auto)] private extern static IntPtr FindWindow(string classname, string captionName);
[DllImport("user32.dll", EntryPoint = "FindWindowEx", CharSet = CharSet.Auto)] private extern static IntPtr FindWindowEx(IntPtr parent,IntPtr child,string classname, string captionName);
[DllImport("user32.dll")] static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, [MarshalAs(UnmanagedType.LPStr)] string lParam);
[DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] static extern bool SetForegroundWindow(IntPtr hWnd);
static void Main(string[] args) {
IntPtr mwh1 = IntPtr.Zero;
while (mwh1 == IntPtr.Zero) { Thread.Sleep(1000); mwh1 = FindWindow(null, "Windows Security"); }
IntPtr panel = FindWindowEx(mwh1, IntPtr.Zero, "DirectUIHWND", null);
IntPtr CtrlNotifySink = IntPtr.Zero;
CtrlNotifySink = FindWindowEx(panel, IntPtr.Zero, "CtrlNotifySink", null);
for (int i = 1; i < 7; i++) { CtrlNotifySink = FindWindowEx(panel, CtrlNotifySink, "CtrlNotifySink", null); }
IntPtr editor = FindWindowEx(CtrlNotifySink, IntPtr.Zero, null, null);
uint WM_SETTEXT = 0xC;
SendMessage(editor, WM_SETTEXT, IntPtr.Zero, "username");
CtrlNotifySink = FindWindowEx(panel, CtrlNotifySink, "CtrlNotifySink", null); editor = FindWindowEx(CtrlNotifySink, IntPtr.Zero, null, null);
SendMessage(editor, WM_SETTEXT, IntPtr.Zero, "password"); } } }

主要注意的一點(diǎn)就是代碼里使用FindWindowEx循環(huán)查找子控件,因?yàn)檫@些控件都是具有相同類名的。
輸入好信息后,查找OK那個Button也差不多是這樣的方法重復(fù)。
下面介紹一下更無恥的方法哈:
static void Main(string[] args) {
IntPtr mwh1 = IntPtr.Zero;
while (mwh1 == IntPtr.Zero) { Thread.Sleep(1000); mwh1 = FindWindow(null, "Windows Security"); }
SetForegroundWindow(mwh1); System.Windows.Forms.SendKeys.SendWait("username"); System.Windows.Forms.SendKeys.SendWait("{TAB}"); System.Windows.Forms.SendKeys.SendWait("password"); System.Windows.Forms.SendKeys.SendWait("{TAB}"); System.Windows.Forms.SendKeys.SendWait("{TAB}"); System.Windows.Forms.SendKeys.SendWait("{ENTER}");
}
呵呵!其實(shí)就是將需要處理的窗口激活,用SendKey處理,這是我同事想出來的,記錄一下!
可能還有更多更好的方法,希望各位多多指點(diǎn)了!
這里再分享一個網(wǎng)站,這個網(wǎng)站非常方便我們查找在C#中調(diào)用Win32中的API
http://www./
|