1. 程式人生 > >自動化測試中FindWindow與FindWindowEx的使用示例

自動化測試中FindWindow與FindWindowEx的使用示例

昨天在做一個網頁測試時,它會彈出一個對話方塊(如下圖)對使用者進行一個認證。

Capture

使用Spy++偵測這個對話方塊的結構如下,我們看到兩個Edit就在最後兩個節點上。

Capture1

我們現在就可以利用FindWindow以及FindWindowEx這兩個函式來幫我們找到這個窗體及窗體上所有的控制元件,然後幫我們完成自動化測試。

下面這個程式就是幫我們自動輸入使用者名稱與密碼。

複製程式碼
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");
}
}
}
複製程式碼

主要注意的一點就是程式碼裡使用FindWindowEx迴圈查詢子控制元件,因為這些控制元件都是具有相同類名的。

輸入好資訊後,查詢OK那個Button也差不多是這樣的方法重複。

下面介紹一下更無恥的方法哈:

複製程式碼
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}");


}
複製程式碼

呵呵!其實就是將需要處理的視窗啟用,用SendKey處理,這是我同事想出來的,記錄一下!

可能還有更多更好的方法,希望各位多多指點了!

這裡再分享一個網站,這個網站非常方便我們查詢在C#中呼叫Win32中的API

相關推薦

no