通过鼠标的位置获取窗口的类名和窗口名
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace qqPrj
{
class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
//[STAThread]
[StructLayout(LayoutKind.Sequential)]//定义与API相兼容结构体,实际上是一种内存转换
public struct POINTAPI
{
public int X;
public int Y;
}
[DllImport("user32.dll", EntryPoint = "GetCursorPos")]//获取鼠标坐标
public static extern int GetCursorPos(
ref POINTAPI lpPoint
);
[DllImport("user32.dll", EntryPoint = "WindowFromPoint")]//指定坐标处窗体句柄
public static extern int WindowFromPoint(
int xPoint,
int yPoint
);
[DllImport("user32.dll", EntryPoint = "GetWindowText")]
public static extern int GetWindowText(
int hWnd,
StringBuilder lpString,
int nMaxCount
);
[DllImport("user32.dll", EntryPoint = "GetClassName")]
public static extern int GetClassName(
int hWnd,
StringBuilder lpString,
int nMaxCont
);
/// <summary>
/// 根据类名和窗口名获取句柄
/// </summary>
/// <param name="lpClassName"></param>
/// <param name="lpWindowName"></param>
/// <returns></returns>
[DllImport("user32.dll")]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
/// <summary>
/// 给窗口发送消息
/// </summary>
/// <param name="hwnd"></param>
/// <param name="wMsg"></param>
/// <param name="wParam"></param>
/// <param name="lParam"></param>
/// <returns></returns>
[DllImport("user32.dll", EntryPoint = "SendMessage")]
private static extern int SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
[DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hwnd, int msg, IntPtr wParam, [MarshalAs(UnmanagedType.LPStr)] string lParam);
//粘贴
const int WM_PASTE = 0x0302;
const int WM_COPY = 0x0301;
//键盘命令
const int WM_SETHOTKEY = 0x0032;
//enter键
const int HOTKEYF_EXT = 0x08;
const int WM_KEYDOWN = 0x0100;
const int VK_RETURN = 0x0D;
static void Main()
{
POINTAPI point = new POINTAPI();//必须用与之相兼容的结构体,类也可以
//add some wait time
Thread.Sleep(5000);
GetCursorPos(ref point);//获取当前鼠标坐标
int hwnd = WindowFromPoint(point.X, point.Y);//获取指定坐标处窗口的句柄
StringBuilder name = new StringBuilder(256);
GetWindowText(hwnd, name, 256);
Console.WriteLine(name.ToString());
GetClassName(hwnd, name, 256);
Console.WriteLine(name.ToString());
var qq = FindWindow("TXGuiFoundation", "国土N1419高聪");
SendMessage(qq, WM_PASTE, 0, 0);//关闭窗体
int flag = SendMessage(qq, WM_KEYDOWN, VK_RETURN, 0);//关闭窗体
if (flag == 1)
{
}
//测试
//MessageBox.Show(name.ToString());
}
}
}