自動化測試中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

http://www.pinvoke.net/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM