C#写个类操作窗口(句柄操作)
实现过程:
过程一:找到当前鼠标位置的句柄
您的使用2个WinAPI(俺喜欢自己封装下来用): View Code
[DllImport("user32.dll", EntryPoint = "GetCursorPos")]
public static extern bool GetCursorPos(out Point pt);
[DllImport("user32.dll", EntryPoint = "WindowFromPoint")]
public static extern IntPtr WindowFromPoint(Point pt);
//鼠标位置的坐标
public static Point GetCursorPosPoint()
{
Point p = new Point();
if (GetCursorPos(out p))
{
return p;
}
return default(Point);
}
/// <summary>
/// 找到句柄
/// </summary>
/// <param name="p">坐标</param>
/// <returns></returns>
public static IntPtr GetHandle(Point p)
{
return WindowFromPoint(p);
}
过程二:改变窗口的Text
您的使用1个WinAPI: View Code
[DllImport("user32.dll", EntryPoint = "SendMessage")]
private static extern int SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, string lParam);
/// <summary>
/// 给窗口发送内容
/// </summary>
/// <param name="hWnd">句柄</param>
/// <param name="lParam">要发送的内容</param>
public static void SetText(IntPtr hWnd, string lParam)
{
SendMessage(hWnd, WM_SETTEXT, IntPtr.Zero, lParam);
}
private const int WM_SETTEXT = 0x000C; 通过这个方法就能改变Text的值了。
思考:如果俺把这个窗口的句柄记录下来,下次不用鼠标获取,直接就能改变值不蛮好的嘛。
例如:我有个桌面系统老叫我输入用户名,密码。我记录用户名和密码的窗口句柄,然后改变他们的输入值,这样多省事。(只是举例,不考虑安全性) 问题:你会告诉我,窗口句柄的每次重建会变的呀,咋办。
回答:类名不变呀。
过程三:您的准备一些工具吧,例如:句柄找类名呀,类名找句柄什么的等等,下面会用到一些WinAPI View Code
[DllImport("user32.dll", EntryPoint = "FindWindow")]
private static extern IntPtr FindWindow(string IpClassName, string IpWindowName);
[DllImport("user32.dll", EntryPoint = "FindWindowEx")]
private static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string
lpszClass, string lpszWindow);
[DllImport("user32.dll", EntryPoint = "GetParent")]
public static extern IntPtr GetParent(IntPtr hWnd);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);
/// <summary>
/// 找到句柄
/// </summary>
/// <param name="IpClassName">类名</param>
/// <returns></returns>
public static IntPtr GetHandle(string IpClassName)
{
return FindWindow(IpClassName, null);
}
/// <summary>
/// 子窗口句柄
/// </summary>
/// <param name="hwndParent">父窗口句柄</param>
/// <param name="hwndChildAfter">前一个同目录级同名窗口句柄</param>
/// <param name="lpszClass">类名</param>
/// <returns></returns>
public static IntPtr GetChildHandle(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass)
{
return FindWindowEx(hwndParent, hwndChildAfter, lpszClass, null);
}
/// <summary>