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

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

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

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那個(gè)Button也差不多是這樣的方法重復(fù)。
下面介紹一下更無(wú)恥的方法哈:
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處理,這是我同事想出來(lái)的,記錄一下!
可能還有更多更好的方法,希望各位多多指點(diǎn)了!
這里再分享一個(gè)網(wǎng)站,這個(gè)網(wǎng)站非常方便我們查找在C#中調(diào)用Win32中的API
http://www./
|