//一个引用
using System.Runtime.InteropServices;
//一些定义,放在例如public partial class Form1 : Form下
const int WM_GETTEXT = 0x000D;
const int WM_SETTEXT = 0x000C;
const int WM_CLICK = 0x00F5;
[DllImport("User32.dll", EntryPoint = "FindWindow")]
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll", EntryPoint = "FindWindowEx")]
private static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
[DllImport("User32.dll", EntryPoint = "SendMessage")]
private static extern int SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, string lParam);
//下面的例子是针对一个弹出式web登录界面,你要用spy++找出你的登录窗口里的相关控件
void PopLogin()
{
tsslStatus.Text = "准备在弹出窗口登录......";
int retval = 0; //增加一个返回值用来判断操作是否成功
//下面的这些参数都可以用Spy++查到
string lpszParentClass = "#32770"; //整个窗口的类名
string lpszParentWindow = strWndName; //窗口标题
//string lpszClass = "Edit"; //需要查找的子窗口的类名,也就是输入框
string lpszClass_Submit = "Button"; //需要查找的Button的类名
string lpszName_Submit = "确定"; //需要查找的Button的标题
string text = "";
IntPtr ParenthWnd = new IntPtr(0);
IntPtr EdithWnd = new IntPtr(0);
IntPtr ip = new IntPtr(0);
//查到窗体,得到整个窗体
ParenthWnd = FindWindow(lpszParentClass, lpszParentWindow);
//等待5秒
int iSecCnt = 1;
while (ParenthWnd == IntPtr.Zero)
{
if (iSecCnt > 5) return;
tsslStatus.Text = "尝试登录......"+iSecCnt.ToString();
Thread.Sleep(1000);
ParenthWnd = FindWindow(lpszParentClass, lpszParentWindow);
iSecCnt++;
}
//判断这个窗体是否有效
if (!ParenthWnd.Equals(IntPtr.Zero))
{
EdithWnd = FindWindowEx(ParenthWnd, new IntPtr(0), "Edit", "");
//得到User Name这个子窗体,并设置其内容
EdithWnd = FindWindowEx(ParenthWnd, EdithWnd, "SysCredential", "");
if (!EdithWnd.Equals(IntPtr.Zero))
{
//MessageBox.Show("sc");
ip = EdithWnd;
//得到Password这个子窗体,并设置其内容
EdithWnd = FindWindowEx(ip, new IntPtr(0), "Edit", "");
if (!EdithWnd.Equals(IntPtr.Zero))
{
text = strGPwd;
SendMessage(EdithWnd, WM_SETTEXT, (IntPtr)0, text);
retval++;
}
EdithWnd = FindWindowEx(ip, new IntPtr(0), "ComboBoxEx32", "");
if (!EdithWnd.Equals(IntPtr.Zero))
{
//MessageBox.Show("cbe");
ip = EdithWnd;
EdithWnd = FindWindowEx(ip, new IntPtr(0), "ComboBox", "");
if (!EdithWnd.Equals(IntPtr.Zero))
{
//MessageBox.Show("cb");
ip = EdithWnd;
EdithWnd = FindWindowEx(ip, new IntPtr(0), "Edit", "");
if (!EdithWnd.Equals(IntPtr.Zero))
{
text = strGAcnt;
//调用SendMessage方法设置其内容
SendMessage(EdithWnd, WM_SETTEXT, (IntPtr)0, text);
retval++;
}
}
}
}
//得到Domain这个子窗体,并设置其内容
//EdithWnd = FindWindowEx(ParenthWnd, EdithWnd, lpszClass, "");
//if (!EdithWnd.Equals(IntPtr.Zero))
//{
// text = this.tbDomain.Text.Trim();
// SendMessage(EdithWnd, WM_SETTEXT, (IntPtr)0, text);
// retval++;
//}
//得到Button这个子窗体,并触发它的Click事件
EdithWnd = FindWindowEx(ParenthWnd, new IntPtr(0), lpszClass_Submit, lpszName_Submit);
if (!EdithWnd.Equals(IntPtr.Zero))
{
SendMessage(EdithWnd, WM_CLICK, (IntPtr)0, "0");
retval++;
}
}
tsslStatus.Text = "尝试登录已完成。";
//return retval;
}
C# API 应用(根据句柄,实现向另一应用程序登录窗体实现登录)
最新推荐文章于 2021-12-22 16:52:05 发布